Programs & Examples On #Sage

SageMath, the Sage Mathematical Software System: free software for Computational Mathematics, based on Python. See longer description for links to other similar-sounding tags.

Launch Pycharm from command line (terminal)

Update: My answer no longer works as of PyCharm 2018.X

On MacOS, I have this alias in my bashrc:

alias pycharm="open -a /Applications/PyCharm*.app"

I can use it like this: pycharm <project dir or file>

The advantage of launching PyCharm this way is that you can open the current dir in PyCharm using pycharm . (unlike /Applications/PyCharm*.app/Contents/MacOS/pycharm . which opens the PyCharm application dir instead)


Update: I switched to JetBrains Toolbox to install PyCharm. Finding PyCharm has gotten a bit more complex, but so far I was lucky with this monster:

alias pycharm="open -a \"\$(ls -r  /Applications/apps/PyCharm*/*/*/PyCharm*.app | head -n 1 | sed 's/:$//')\""

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Get Element value with minidom with Python

It should just be

name[0].firstChild.nodeValue

git status shows modifications, git checkout -- <file> doesn't remove them

We faced a similar situation in our company. None of the proposed methods did not help us. As a result of the research, the problem was revealed. The thing was that in Git there were two files, the names of which differed only in the register of symbols. Unix-systems saw them as two different files, but Windows was going crazy. To solve the problem, we deleted one of the files on the server. After that, at the local repositories on Windows helped the next few commands (in different sequences):

git reset --hard
git pull origin
git merge

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

Getting an Embedded YouTube Video to Auto Play and Loop

Had same experience, however what did the magic for me is not to change embed to v.

So the code will look like this...

<iframe width="560" height="315" src="https://www.youtube.com/embed/cTYuscQu-Og?Version=3&loop=1&playlist=cTYuscQu-Og" frameborder="0" allowfullscreen></iframe>

Hope it helps...

How can I calculate the difference between two dates?

With Swift 5 and iOS 12, according to your needs, you may use one of the two following ways to find the difference between two dates in days.


#1. Using Calendar's dateComponents(_:from:to:) method

import Foundation

let calendar = Calendar.current

let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!

let dateComponents = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)

print(dateComponents) // prints: day: 1621 isLeapMonth: false
print(String(describing: dateComponents.day)) // prints: Optional(1621)

#2. Using DateComponentsFormatter's string(from:to:) method

import Foundation

let calendar = Calendar.current

let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [NSCalendar.Unit.day]

let elapsedTime = formatter.string(from: startDate, to: endDate)
print(String(describing: elapsedTime)) // prints: Optional("1,621 days")

How do I ZIP a file in C#, using no 3rd-party APIs?

Add these 4 functions to your project:

        public const long BUFFER_SIZE = 4096;
    public static void AddFileToZip(string zipFilename, string fileToAdd)
    {
        using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
        {
            string destFilename = ".\\" + Path.GetFileName(fileToAdd);
            Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
            if (zip.PartExists(uri))
            {
                zip.DeletePart(uri);
            }
            PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
            using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
            {
                using (Stream dest = part.GetStream())
                {
                    CopyStream(fileStream, dest);
                }
            }
        }
    }
    public static void CopyStream(global::System.IO.FileStream inputStream, global::System.IO.Stream outputStream)
    {
        long bufferSize = inputStream.Length < BUFFER_SIZE ? inputStream.Length : BUFFER_SIZE;
        byte[] buffer = new byte[bufferSize];
        int bytesRead = 0;
        long bytesWritten = 0;
        while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
            bytesWritten += bytesRead;
        }
    }
    public static void RemoveFileFromZip(string zipFilename, string fileToRemove)
    {
        using (Package zip = global::System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
        {
            string destFilename = ".\\" + fileToRemove;
            Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
            if (zip.PartExists(uri))
            {
                zip.DeletePart(uri);
            }
        }
    }
    public static void Remove_Content_Types_FromZip(string zipFileName)
    {
        string contents;
        using (ZipFile zipFile = new ZipFile(File.Open(zipFileName, FileMode.Open)))
        {
            /*
            ZipEntry startPartEntry = zipFile.GetEntry("[Content_Types].xml");
            using (StreamReader reader = new StreamReader(zipFile.GetInputStream(startPartEntry)))
            {
                contents = reader.ReadToEnd();
            }
            XElement contentTypes = XElement.Parse(contents);
            XNamespace xs = contentTypes.GetDefaultNamespace();
            XElement newDefExt = new XElement(xs + "Default", new XAttribute("Extension", "sab"), new XAttribute("ContentType", @"application/binary; modeler=Acis; version=18.0.2application/binary; modeler=Acis; version=18.0.2"));
            contentTypes.Add(newDefExt);
            contentTypes.Save("[Content_Types].xml");
            zipFile.BeginUpdate();
            zipFile.Add("[Content_Types].xml");
            zipFile.CommitUpdate();
            File.Delete("[Content_Types].xml");
            */
            zipFile.BeginUpdate();
            try
            {
                zipFile.Delete("[Content_Types].xml");
                zipFile.CommitUpdate();
            }
            catch{}
        }
    }

And use them like this:

foreach (string f in UnitZipList)
{
    AddFileToZip(zipFile, f);
    System.IO.File.Delete(f);
}
Remove_Content_Types_FromZip(zipFile);

Convert a hexadecimal string to an integer efficiently in C?

For larger Hex strings like in the example I needed to use strtoul.

SQL LIKE condition to check for integer?

That will select (by a regex) every book which has a title starting with a number, is that what you want?

SELECT * FROM books WHERE title ~ '^[0-9]'

if you want integers which start with specific digits, you could use:

SELECT * FROM books WHERE CAST(price AS TEXT) LIKE '123%'

or use (if all your numbers have the same number of digits (a constraint would be useful then))

SELECT * FROM books WHERE price BETWEEN 123000 AND 123999;

How to set DataGrid's row Background, based on a property value using data bindings

Use a DataTrigger:

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

Add and remove attribute with jquery

Once you remove the ID "page_navigation" that element no longer has an ID and so cannot be found when you attempt to access it a second time.

The solution is to cache a reference to the element:

$(document).ready(function(){
    // This reference remains available to the following functions
    // even when the ID is removed.
    var page_navigation = $("#page_navigation1");

    $("#add").click(function(){
        page_navigation.attr("id","page_navigation1");
    });     

    $("#remove").click(function(){
        page_navigation.removeAttr("id");
    });     
});

Blurring an image via CSS?

Yes there is using the following code will allow you to apply a blurring effect to the specified image and also it will allow you to choose the amount of blurring.

img {
  -webkit-filter: blur(10px);
    filter: blur(10px);
}

Oracle query to fetch column names

You can try this:

describe 'Table Name'

It will return all column names and data types

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How do I convert an interval into a number of hours with postgres?

         select date 'now()' - date '1955-12-15';

Here is the simple query which calculates total no of days.

Get first 100 characters from string, respecting full words

function truncate ($str, $length) {
    if (strlen($str) > $length) {
        $str = substr($str, 0, $length+1);
        $pos = strrpos($str, ' ');
        $str = substr($str, 0, ($pos > 0)? $pos : $length);
    }
    return $str;
}

Example:

print truncate('The first step to eternal life is you have to die.', 25);

string(25) "The first step to eternal"

print truncate('The first step to eternal life is you have to die.', 12);

string(9) "The first"

print truncate('FirstStepToEternalLife', 5);

string(5) "First"

AmazonS3 putObject with InputStream length example

Because the original question was never answered, and I had to run into this same problem, the solution for the MD5 problem is that S3 doesn't want the Hex encoded MD5 string we normally think about.

Instead, I had to do this.

// content is a passed in InputStream
byte[] resultByte = DigestUtils.md5(content);
String streamMD5 = new String(Base64.encodeBase64(resultByte));
metaData.setContentMD5(streamMD5);

Essentially what they want for the MD5 value is the Base64 encoded raw MD5 byte-array, not the Hex string. When I switched to this it started working great for me.

Opening Android Settings programmatically

You can try to call:

startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));

for other screen in setting screen, you can go to

https://developer.android.com/reference/android/provider/Settings.html

Hope help you in this case.

fe_sendauth: no password supplied

Do not use passwords. Use peer authentication instead:

postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.

How do I copy SQL Azure database to my local development server?

I couldn't get the SSIS import / export to work as I got the error 'Failure inserting into the read-only column "id"'. Nor could I get http://sqlazuremw.codeplex.com/ to work, and the links above to SQL Azure Data Sync didn't work for me.

But I found an excellent blog post about BACPAC files: http://dacguy.wordpress.com/2012/01/24/sql-azure-importexport-service-has-hit-production/

In the video in the post the blog post's author runs through six steps:

  1. Make or go to a storage account in the Azure Management Portal. You'll need the Blob URL and the Primary access key of the storage account.

  2. The blog post advises making a new container for the bacpac file and suggests using the Azure Storage Explorer for that. (N.B. you'll need the Blob URL and the Primary access key of the storage account to add it to the Azure Storage Explorer.)

  3. In the Azure Management Portal select the database you want to export and click 'Export' in the Import and Export section of the ribbon.

  4. The resulting dialogue requires your username and password for the database, the blob URL, and the access key. Don't forget to include the container in the blob URL and to include a filename (e.g. https://testazurestorage.blob.core.windows.net/dbbackups/mytable.bacpac).

  5. After you click Finish the database will be exported to the BACPAC file. This can take a while. You may see a zero byte file show up immediately if you check in the Azure Storage Explorer. This is the Import / Export Service checking that it has write access to the blob-store.

  6. Once that is done you can use the Azure Storage Explorer to download the BACPAC file and then in the SQL Server Management Studio right-click your local server's database folder and choose Import Data Tier Application that will start the wizard which reads in the BACPAC file to produce the copy of your Azure database. The wizard can also connect directly to the blob-store to obtain the BACPAC file if you would rather not copy it locally first.

The last step may only be available in the SQL Server 2012 edition of the SQL Server Management Studio (that's the version I am running). I do not have earlier ones on this machine to check. In the blog post the author uses the command line tool DacImportExportCli.exe for the import which I believe is available at http://sqldacexamples.codeplex.com/releases

View not attached to window manager crash

best solution. Check first context is activity context or application context if activity context then only check activity is finished or not then call dialog.show() or dialog.dismiss();

See sample code below... hope it will be helpful !

Display dialog

if (context instanceof Activity) {
   if (!((Activity) context).isFinishing())
     dialog.show();
}

Dismiss dialog

if (context instanceof Activity) {
       if (!((Activity) context).isFinishing())
         dialog.dismiss();
    }

If you want to add more checks then add dialog.isShowing() or dialog !-null using && condition.

wait() or sleep() function in jquery?

I found a function called sleep function on the internet and don't know who made it. Here it is.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(2000);

How to position two elements side by side using CSS

Like this

.block {
    display: inline-block;
    vertical-align:top;
}

JSFiddle Demo

Chmod recursively

Adding executable permissions, recursively, to all files (not folders) within the current folder with sh extension:

find . -name '*.sh' -type f | xargs chmod +x

* Notice the pipe (|)

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

Update: The world kept turning. Use a functional approach instead.

Here you go:

var arr = [{ key: "11", value: "1100" }, { key: "22", value: "2200" }];
var result = {};
for (var i=0, len=arr.length; i < len; i++) {
    result[arr[i].key] = arr[i].value;
}
console.log(result); // {11: "1000", 22: "2200"}

Comparing two hashmaps for equal values and same key sets?

public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {

    if (map1 == null || map2 == null)
        return false;

    for (String ch1 : map1.keySet()) {
        if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
            return false;

    }
    for (String ch2 : map2.keySet()) {
        if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
            return false;

    }

    return true;
}

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

Set min-width in HTML table's <td>

<table style="border:2px solid #ddedde">
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
</table>

Change Volley timeout duration

I ended up adding a method setCurrentTimeout(int timeout) to the RetryPolicy and it's implementation in DefaultRetryPolicy.

Then I added a setCurrentTimeout(int timeout) in the Request class and called it .

This seems to do the job.

Sorry for my laziness by the way and hooray for open source.

Filtering a spark dataframe based on date

I find the most readable way to express this is using a sql expression:

df.filter("my_date < date'2015-01-01'")

we can verify this works correctly by looking at the physical plan from .explain()

+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))

How to line-break from css, without using <br />?

Building on what has been said before, this is a pure CSS solution that works.

<style>
  span {
    display: inline;
  }
  span:before {
    content: "\a ";
    white-space: pre;
  }
</style>
<p>
  First line of text. <span>Next line.</span>
</p>

Javascript: How to check if a string is empty?

if (value == "") {
  // it is empty
}

Get escaped URL parameter

I created a simple function to get URL parameter in JavaScript from a URL like this:

.....58e/web/viewer.html?page=*17*&getinfo=33


function buildLinkb(param) {
    var val = document.URL;
    var url = val.substr(val.indexOf(param))  
    var n=parseInt(url.replace(param+"=",""));
    alert(n+1); 
}
buildLinkb("page");

OUTPUT: 18

How to Empty Caches and Clean All Targets Xcode 4 and later

I have been pulling out hair from my head because I thought that I had the same problem. When building the app I didn't get the same result on my iPhone as on the simulator.

The problem was that I had somehow made a localized version of the MainStoryboard.storyboard file. So when I ran the app on my phone it showed the danish version... and the simulator showed the english version.

Yeah I'm new! :)

Apply function to all elements of collection through LINQ

For collections that do not support ForEach you can use static ForEach method in Parallel class:

var options = new ParallelOptions() { MaxDegreeOfParallelism = 1 };
Parallel.ForEach(_your_collection_, options, x => x._Your_Method_());

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

How to reload .bashrc settings without logging out and back in again?

Or you could use:

exec bash

This does the same thing, and is easier to remember (at least for me).

The exec command completely replaces the shell process by running the specified command-line. In our example, it replaces whatever the current shell is with a fresh instance of bash (with the updated configuration files).

Black transparent overlay on image hover with only CSS?

I would give a min-height and min-width to your overlay div of the size of the image, and change the background color on hover

.overlay { position: absolute; top: 0; left: 0;  z-index: 200; min-height:200px; min-width:200px; background-color: none;}
.overlay:hover { background-color: red;}

Submit form after calling e.preventDefault()

Sorry for delay, but I will try to make perfect form :)

I will added Count validation steps and check every time not .val(). Check .length, because I think is better pattern in your case. Of course remove unbind function.

My jsFiddle

Of course source code:

// Prevent form submit if any entrees are missing
$('form').submit(function(e){

    e.preventDefault();

    var formIsValid = true;

    // Count validation steps
    var validationLoop = 0;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val().length > 0) {
            validationLoop++;

            // Find adjacent entree input
            var entree = $(el).next('input');

            var entreeValue = entree.val();

            // If entree is empty, don't submit form
            if (entreeValue.length === 0) {
                alert('Please select an entree');
                entree.focus();
                formIsValid = false;
                return false;
            }

        }

    });

    if (formIsValid && validationLoop > 0) {
        alert("Correct Form");
        return true;
    } else {
        return false;
    }

});

Error sending json in POST to web API service

  1. You have to must add header property Content-Type:application/json
  2. When you define any POST request method input parameter that should be annotated as [FromBody], e.g.:

    [HttpPost]
    public HttpResponseMessage Post([FromBody]ActivityResult ar)
    {
      return new HttpResponseMessage(HttpStatusCode.OK);
    }
    
  3. Any JSON input data must be raw data.

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Will #if RELEASE work like #if DEBUG does in C#?

Whilst M4N's answer (#if (!DEBUG)) makes most sense, another option could be to use the preprocessor to amend other flag's values; e.g.

bool isRelease = true;
#if DEBUG
    isRelease = false;
#endif

Or better, rather than referring to whether we're in release or debug mode, use flags that define the expected behavior and set them based on the mode:

bool sendEmails = true;
#if DEBUG
    sendEmails = false;
#endif

This is different to using preprocessor flags, in that the flags are still there in production, so you incur the overhead of if (sendEmails) {/* send mails */} each time that code's called, rather than the code existing in release but not existing in debug, but this can be advantageous; e.g. in your tests you may want to call your SendEmails() method but on a mock, whilst running in debug to get additional output.

"python" not recognized as a command

Make sure you click on Add python.exe to path during install, and select:

"Will be installed on local hard drive"

It fixed my problem, hope it helps...

Show just the current branch in Git

With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current.

See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis).
(Merged by Junio C Hamano -- gitster -- in commit 3710f60, 07 Mar 2019)

branch: introduce --show-current display option

When called with --show-current, git branch will print the current branch name and terminate.
Only the actual name gets printed, without refs/heads.
In detached HEAD state, nothing is output.

Intended both for scripting and interactive/informative use.
Unlike git branch --list, no filtering is needed to just get the branch name.

See the original discussion on the Git mailing list in Oct. 2018, and the actual pathc.

convert string to number node.js

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

See results of below test cases.

console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));

result:

CleanInt:  NaN  ParseInt:  NaN
CleanInt:  NaN  ParseInt:  123
CleanInt:  234  ParseInt:  234
CleanInt:  -679  ParseInt:  -679
CleanInt:  897  ParseInt:  897
CleanInt:  Infinity  ParseInt:  NaN

How to add external fonts to android application

You can use the custom TextView for whole app with custom font here is an example for that

public class MyTextView extends TextView {

   Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
   Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(),  Constants.FONT_BOLD);

   public MyTextView(Context context, AttributeSet attrs, int defStyle) {
       super(context, attrs, defStyle);
   }

   public MyTextView(Context context, AttributeSet attrs) {
       super(context, attrs);
   }

   public MyTextView(Context context) {
       super(context);
   }

   public void setTypeface(Typeface tf, int style) {
       if (style == Typeface.BOLD) {
           super.setTypeface(boldTypeface/*, -1*/);
       } else {
           super.setTypeface(normalTypeface/*, -1*/);
       }
   }
}

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

Here's the stuff I ran into:

1) RTFM and install the "Microsoft Visual C++ 2008 SP1 Redistributable Package" mentioned at top of the installation docs. I missed this at first because the Helios instructions are at the end.

2) Close all open editor tabs before opening a class file. Otherwise it's easy to get an outdated editor tab from a previous attempt.

3) Open the class file in the "Java Class File Editor" (not "Java Class File Viewer"). Use "Open With" in the context menu to get the right editor. If pleased with results, make it the default editor in the File Association settings, in Window/Preference General/Editors/File Associations select *.class to open with "Java Class File Editor".

4) This guy recommends installing the Equinox SDK from the Helios update site. I did, but I'm not sure if this was really necessary. Anyone know?

5) If the class files you are trying to view are in an Eclipse Java project, they need to be in the project's build path. Otherwise, an exception ("Not in the build path") will show up in the Eclipse error log, and decompile will fail. I added the class files as a library / class file folder to the build path.

6) Drag/dropping a class file from Windows Explorer or opening it with File/Open File... will not work. In my tests, I gives a "Could not open the editor: The Class File Viewer cannot handle the given input ('org.eclipse.ui.ide.FileStoreEditorInput')." error. That is probably the wrong editor anyways, see 3).

7) After getting the plugin basically running, some files would still not decompile for an unknown reason. This disappeared after closing all tabs, restarting Helios, and trying again.

Conditionally displaying JSF components

In addition to previous post you can have

<h:form rendered="#{!bean.boolvalue}" />
<h:form rendered="#{bean.textvalue == 'value'}" />

Jsf 2.0

Allow a div to cover the whole page instead of the area within the container

Add position:fixed. Then the cover is fixed over the whole screen, also when you scroll.
And add maybe also margin: 0; padding:0; so it wont have some space's around the cover.

#dimScreen
{
    position:fixed;
    padding:0;
    margin:0;

    top:0;
    left:0;

    width: 100%;
    height: 100%;
    background:rgba(255,255,255,0.5);
}

And if it shouldn't stick on the screen fixed, use position:absolute;

CSS Tricks have also an interesting article about fullscreen property.

Edit:
Just came across this answer, so I wanted to add some additional things.
Like Daniel Allen Langdon mentioned in the comment, add top:0; left:0; to be sure, the cover sticks on the very top and left of the screen.

If you some elements are at the top of the cover (so it doesn't cover everything), then add z-index. The higher the number, the more levels it covers.

HTML/CSS--Creating a banner/header

For the image that is not showing up. Open the image in the Image editor and check the type you are probably name it as "gif" but its saved in a different format that's one reason that the browser is unable to render it and it is not showing.
For the image stretching issue please specify the actual width and height dimensions in #banner instead of width: 100%; height: 200px that you have specified.

Check for file exists or not in sql server?

Try the following code to verify whether the file exist. You can create a user function and use it in your stored procedure. modify it as you need:

Set NOCOUNT ON

 DECLARE @Filename NVARCHAR(50)
 DECLARE @fileFullPath NVARCHAR(100)

 SELECT @Filename = N'LogiSetup.log'
 SELECT @fileFullPath = N'C:\LogiSetup.log'

create table #dir

(output varchar(2000))

 DECLARE @cmd NVARCHAR(100)
SELECT @cmd = 'dir ' + @fileFullPath     

insert into #dir    

exec master.dbo.xp_cmdshell @cmd

--Select * from #dir

-- This is risky, as the fle path itself might contain the filename
if exists (Select * from #dir where output like '%'+ @Filename +'%')

       begin    
              Print 'File found'    
              --Add code you want to run if file exists    
       end    
else    
       begin    
              Print 'No File Found'    
              --Add code you want to run if file does not exists    
       end

drop table #dir

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonResult()
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior,
            MaxJsonLength = Int32.MaxValue
        };
    }

Was the fix for me in MVC 4.

Select top 1 result using JPA

Use a native SQL query by specifying a @NamedNativeQuery annotation on the entity class, or by using the EntityManager.createNativeQuery method. You will need to specify the type of the ResultSet using an appropriate class, or use a ResultSet mapping.

How to add property to a class dynamically?

You can use the following code to update class attributes using a dictionary object:

class ExampleClass():
    def __init__(self, argv):
        for key, val in argv.items():
            self.__dict__[key] = val

if __name__ == '__main__':
    argv = {'intro': 'Hello World!'}
    instance = ExampleClass(argv)
    print instance.intro

Define an alias in fish shell

I found the prior answers and comments to be needlessly incomplete and/or confusing. The minimum that I needed to do was:

  1. Create ~/.config/fish/config.fish. This file can optionally be a softlink.
  2. Add to it the line alias myalias echo foo bar.
  3. Restart fish. To confirm the definition, try type myalias. Try the alias.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use directions service of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map.

Information and examples about rendering the directions route on the map can be found in rendering directions section of Google Maps API v3 documentation.

Using jQuery to build table rows from AJAX response(json)

Use .append instead of .html

var response = "[{
      "rank":"9",
      "content":"Alon",
      "UID":"5"
     },
     {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
    }]";

// convert string to JSON
response = $.parseJSON(response);

$(function() {
    $.each(response, function(i, item) {
        var $tr = $('<tr>').append(
            $('<td>').text(item.rank),
            $('<td>').text(item.content),
            $('<td>').text(item.UID)
        ); //.appendTo('#records_table');
        console.log($tr.wrap('<p>').html());
    });
});

How can I get the image url in a Wordpress theme?

I strongly recommend the following:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/img-folder/your_image.jpg">

It works for almost any file you want to add to your wordpress project, be it image or CSS.

Check, using jQuery, if an element is 'display:none' or block on click

You can use :visible for visible elements and :hidden to find out hidden elements. This hidden elements have display attribute set to none.

hiddenElements = $(':hidden');
visibleElements = $(':visible');

To check particular element.

if($('#yourID:visible').length == 0)
{

}

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero, Reference

You can also use is() with :visible

if(!$('#yourID').is(':visible'))
{

}

If you want to check value of display then you can use css()

if($('#yourID').css('display') == 'none')
{

}

If you are using display the following values display can have.

display: none

display: inline

display: block

display: list-item

display: inline-block

Check complete list of possible display values here.

To check the display property with JavaScript

var isVisible = document.getElementById("yourID").style.display == "block";
var isHidden = document.getElementById("yourID").style.display == "none"; 

Android view layout_width - how to change programmatically?

try using

View view_instance = (View)findViewById(R.id.nutrition_bar_filled);
view_instance.setWidth(10);

use Layoutparams to do so where you can set width and height like below.

LayoutParams lp = new LayoutParams(10,LayoutParams.wrap_content);
View_instance.setLayoutParams(lp);

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

Is there an API to get bank transaction and bank balance?

Just a helpful hint, there is a company called Yodlee.com who provides this data. They do charge for the API. Companies like Mint.com use this API to gather bank and financial account data.

Also, checkout https://plaid.com/, they are a similar company Yodlee.com and provide both authentication API for several banks and REST-based transaction fetching endpoints.

How can I change property names when serializing with Json.net?

If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.

For example, if you have a class called MyCustomObject, that has a property called LongPropertyName, you can use a custom resolver like this…

public class CustomDataContractResolver : DefaultContractResolver
{
  public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();

  protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
  {
    var property = base.CreateProperty(member, memberSerialization);
    if (property.DeclaringType == typeof(MyCustomObject))
    {
      if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
      {
        property.PropertyName = "Short";
      }
    }
    return property;
  }
}

Then call for serialization and supply the resolver:

 var result = JsonConvert.SerializeObject(myCustomObjectInstance,
                new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });

And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}

More info on custom resolvers here

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
_x000D_
_x000D_

ToggleButton in C# WinForms

I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well.

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">

You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools" and tools:ignore="GoogleAppIndexingWarning" to the <manifest> tag.

'Incorrect SET Options' Error When Building Database Project

For me, just setting the compatibility level to higher level works fine. To see C.Level :

select compatibility_level from sys.databases where name = [your_database]

html5 audio player - jquery toggle click play/pause?

Well, I'm not 100% sure, but I don't think jQuery extends/parses those functions and attributes (.paused, .pause(), .play()).

try to access those over the DOM element, like:

$('.player_audio').click(function() {
  if (this.paused == false) {
      this.pause();
      alert('music paused');
  } else {
      this.play();
      alert('music playing');
  }
});

Unique constraint on multiple columns

If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:

ALTER TABLE dbo.User
  ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)

Using Vim's tabs like buffers

Vim :help window explains the confusion "tabs vs buffers" pretty well.

A buffer is the in-memory text of a file.
A window is a viewport on a buffer.
A tab page is a collection of windows.

Opening multiple files is achieved in vim with buffers. In other editors (e.g. notepad++) this is done with tabs, so the name tab in vim maybe misleading.

Windows are for the purpose of splitting the workspace and displaying multiple files (buffers) together on one screen. In other editors this could be achieved by opening multiple GUI windows and rearranging them on the desktop.

Finally in this analogy vim's tab pages would correspond to multiple desktops, that is different rearrangements of windows.

As vim help: tab-page explains a tab page can be used, when one wants to temporarily edit a file, but does not want to change anything in the current layout of windows and buffers. In such a case another tab page can be used just for the purpose of editing that particular file.

Of course you have to remember that displaying the same file in many tab pages or windows would result in displaying the same working copy (buffer).

How can I get useful error messages in PHP?

For quick, hands-on troubleshooting I normally suggest here on SO:

error_reporting(~0); ini_set('display_errors', 1);

to be put at the beginning of the script that is under trouble-shooting. This is not perfect, the perfect variant is that you also enable that in the php.ini and that you log the errors in PHP to catch syntax and startup errors.

The settings outlined here display all errors, notices and warnings, including strict ones, regardless which PHP version.

Next things to consider:

  • Install Xdebug and enable remote-debugging with your IDE.

See as well:

Differences between MySQL and SQL Server

One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL syntax.

Here's a nice Comparison of Different SQL Implementations.

For example, take a look at the top-n section. In MySQL:

SELECT age
FROM person
ORDER BY age ASC
LIMIT 1 OFFSET 2

In SQL Server (T-SQL):

SELECT TOP 3 WITH TIES *
FROM person
ORDER BY age ASC

jQuery or CSS selector to select all IDs that start with some string

You can use meta characters like * (http://api.jquery.com/category/selectors/). So I think you just can use $('#player_*').

In your case you could also try the "Attribute starts with" selector: http://api.jquery.com/attribute-starts-with-selector/: $('div[id^="player_"]')

Does a favicon have to be 32x32 or 16x16?

As I learned, no one of those several solutions are perfects. Using a favicon generator is indeed a good solution but their number is overwhelming and it's hard to choose. I d'like to add that if you want your website to be PWA enabled, you need to provide also a 512x512 icon as stated by Google Devs :

icons including a 192px and a 512px version

I didn't met a lot of favicon generators enforcing that criteria (firebase does, but there is a lot of things it doesn't do). So the solution must be a mix of many other solutions.

I don't know, today at the begining of 2020 if providing a 16x16, 32x32 still relevant. I guess it still matters in certain context like, for example, if your users still use IE for some reason (this stills happen in some privates companies which doesn't migrate to a newer browser for some reasons)

use jQuery to get values of selected checkboxes

var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      

Order by descending date - month, day and year

Assuming that you have the power to make schema changes the only acceptable answer to this question IMO is to change the base data type to something more appropriate (e.g. date if SQL Server 2008).

Storing dates as mm/dd/yyyy strings is space inefficient, difficult to validate correctly and makes sorting and date calculations needlessly painful.

Is it possible to override / remove background: none!important with jQuery?

div { background: none !important }
div { background: red; }

Is transparent.

div { background: none !important }
div { background: red !important; }

Is red.

An !important can override another !important.

If you can't edit the CSS file you can still add another one, or a style tag in the head tag.

Storing Images in PostgreSQL

If your images are small, consider storing them as base64 in a plain text field.

The reason is that while base64 has an overhead of 33%, with compression that mostly goes away. (See What is the space overhead of Base64 encoding?) Your database will be bigger, but the packets your webserver sends to the client won't be. In html, you can inline base64 in an <img src=""> tag, which can possibly simplify your app because you won't have to serve up the images as binary in a separate browser fetch. Handling images as text also simplifies things when you have to send/receive json, which doesn't handle binary very well.

Yes, I understand you could store the binary in the database and convert it to/from text on the way in and out of the database, but sometimes ORMs make that a hassle. It can be simpler just to treat it as straight text just like all your other fields.

This is definitely the right way to handle thumbnails.

(OP's images are not small, so this is not really an answer to his question.)

Access a global variable in a PHP function

You need to pass the variable into the function:

$data = 'My data';

function menugen($data)
{
    echo $data;
}

python xlrd unsupported format, or corrupt file.

This will happen to some files while also open in Excel.

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

I also received this error (for several tables) along with constraint errors and MySQL connecting and disconnecting when attempting to import an entire database (~800 MB). My issue was the result of The MySQL server max allowed packets being too low. To resolve this (on a Mac):

  • Opened /private/etc/my.conf
  • Under # The MySQL server, changed max_allowed_packet from 1M to 4M (You may need to experiment with this value.)
  • Restarted MySQL

The database imported successfully after that.

Note I am running MySQL 5.5.12 for Mac OS X (x86 64 bit).

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.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

Goto Window->Preferences, search for Launching.

Select the "Terminate and Relaunch while launching" option.

Press Apply.

Passing structs to functions

It is possible to construct a struct inside the function arguments:

function({ .variable = PUT_DATA_HERE });

How to make child divs always fit inside parent div?

you could use display: inline-block;

hope it is useful.

How to convert a string or integer to binary in Ruby?

Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:

>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I know it's a bit of a late answer for this post, but for reference...

CSS

ul {
    color: red;
}

li {
    color: black;
}

The bullet colour is defined on the ul tag and then we switch the li colour back.

How to add text inside the doughnut chart using Chart.js?

Base on @rap-2-h answer,Here the code for using text on doughnut chart on Chart.js for using in dashboard like. It has dynamic font-size for responsive option.

HTML:

<div>text
<canvas id="chart-area" width="300" height="300" style="border:1px solid"/><div>

Script:

var doughnutData = [
            {
                value: 100,
                color:"#F7464A",
                highlight: "#FF5A5E",
                label: "Red"
            },
            {
                value: 50,
                color: "#CCCCCC",
                highlight: "#5AD3D1",
                label: "Green"
            }
        ];

$(document).ready(function(){
  var ctx = $('#chart-area').get(0).getContext("2d");

  var myDoughnut = new Chart(ctx).Doughnut(doughnutData,{
     animation:true,
     responsive: true,
     showTooltips: false,
     percentageInnerCutout : 70,
     segmentShowStroke : false,
     onAnimationComplete: function() {

     var canvasWidthvar = $('#chart-area').width();
     var canvasHeight = $('#chart-area').height();
     //this constant base on canvasHeight / 2.8em
     var constant = 114;
     var fontsize = (canvasHeight/constant).toFixed(2);
     ctx.font=fontsize +"em Verdana";
     ctx.textBaseline="middle"; 
     var total = 0;
     $.each(doughnutData,function() {
       total += parseInt(this.value,10);
   });
  var tpercentage = ((doughnutData[0].value/total)*100).toFixed(2)+"%";
  var textWidth = ctx.measureText(tpercentage).width;

   var txtPosx = Math.round((canvasWidthvar - textWidth)/2);
    ctx.fillText(tpercentage, txtPosx, canvasHeight/2);
  }
 });
});

Here the sample code.try to resize the window. http://jsbin.com/wapono/13/edit

HTML5 record audio to file

There is a fairly complete recording demo available at: http://webaudiodemos.appspot.com/AudioRecorder/index.html

It allows you to record audio in the browser, then gives you the option to export and download what you've recorded.

You can view the source of that page to find links to the javascript, but to summarize, there's a Recorder object that contains an exportWAV method, and a forceDownload method.

How to configure Eclipse build path to use Maven dependencies?

I had a slight variation that caused some issues - multiple sub projects within one project. In this case I needed to go into each individual folder that contained a POM, execute the mvn eclipse:eclipse command and then manually copy/merge the classpath entries into my project classpath file.

How to perform element-wise multiplication of two lists?

Fairly intuitive way of doing this:

a = [1,2,3,4]
b = [2,3,4,5]
ab = []                        #Create empty list
for i in range(0, len(a)):
     ab.append(a[i]*b[i])      #Adds each element to the list

Replacing H1 text with a logo image: best method for SEO and accessibility?

How W3C does?

Simply have a look a look at https://www.w3.org/. The image has a z-index:1, the text is here but behind because of the z-index:0 coupled to the position: absolute;

The original HTML:

<h1 class="logo">
    <a tabindex="2" accesskey="1" href="/">
        <img src="/2008/site/images/logo-w3c-mobile-lg" width="90" height="53" alt="W3C">
    </a>
    <span class="alt-logo">W3C</span>
</h1>

The original CSS:

#w3c_mast h1 a {
    display: block;
    float: left;
    background: url(../images/logo-w3c-screen-lg) no-repeat top left;
    width: 100%;
    height: 107px;
    position: relative;
    z-index: 1;
}
.alt-logo {
    display: block;
    position: absolute;
    left: 20px;
    z-index: 0;
    background-color: #fff;
}

How to mount a host directory in a Docker container

docker run -v /host/directory:/container/directory -t IMAGE-NAME /bin/bash

docker run -v /root/shareData:/home/shareData -t kylemanna/openvpn /bin/bash

In my system I've corrected the answer from nhjk, it works flawless when you add the -t flag.

In-place type conversion of a NumPy array

Use this:

In [105]: a
Out[105]: 
array([[15, 30, 88, 31, 33],
       [53, 38, 54, 47, 56],
       [67,  2, 74, 10, 16],
       [86, 33, 15, 51, 32],
       [32, 47, 76, 15, 81]], dtype=int32)

In [106]: float32(a)
Out[106]: 
array([[ 15.,  30.,  88.,  31.,  33.],
       [ 53.,  38.,  54.,  47.,  56.],
       [ 67.,   2.,  74.,  10.,  16.],
       [ 86.,  33.,  15.,  51.,  32.],
       [ 32.,  47.,  76.,  15.,  81.]], dtype=float32)

Easy way to password-protect php page

I would simply look for a $_GET variable and redirect the user if it's not correct.

<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
  header('Location: http://www.staggeringbeauty.com/');
}
?>

Now, if this page is located at say: http://example.com/secrets/files.php

You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

How to merge two arrays in JavaScript and de-duplicate items

The best solution...

You can check directly in the browser console by hitting...

Without duplicate

a = [1, 2, 3];
b = [3, 2, 1, "prince"];

a.concat(b.filter(function(el) {
    return a.indexOf(el) === -1;
}));

With duplicate

["prince", "asish", 5].concat(["ravi", 4])

If you want without duplicate you can try a better solution from here - Shouting Code.

[1, 2, 3].concat([3, 2, 1, "prince"].filter(function(el) {
    return [1, 2, 3].indexOf(el) === -1;
}));

Try on Chrome browser console

 f12 > console

Output:

["prince", "asish", 5, "ravi", 4]

[1, 2, 3, "prince"]

Permission to write to the SD card

The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.

However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).

The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).

For example:

[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
  protected override void OnCreate(Bundle bindle)
  {
    base.OnCreate(bindle);
  }
}

PostgreSQL: Modify OWNER on all tables simultaneously in PostgreSQL

This: http://archives.postgresql.org/pgsql-bugs/2007-10/msg00234.php is also a nice and fast solution, and works for multiple schemas in one database:

Tables

SELECT 'ALTER TABLE '|| schemaname || '."' || tablename ||'" OWNER TO my_new_owner;'
FROM pg_tables WHERE NOT schemaname IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename;

Sequences

SELECT 'ALTER SEQUENCE '|| sequence_schema || '."' || sequence_name ||'" OWNER TO my_new_owner;'
FROM information_schema.sequences WHERE NOT sequence_schema IN ('pg_catalog', 'information_schema')
ORDER BY sequence_schema, sequence_name;

Views

SELECT 'ALTER VIEW '|| table_schema || '."' || table_name ||'" OWNER TO my_new_owner;'
FROM information_schema.views WHERE NOT table_schema IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;

Materialized Views

Based on this answer

SELECT 'ALTER TABLE '|| oid::regclass::text ||' OWNER TO my_new_owner;'
FROM pg_class WHERE relkind = 'm'
ORDER BY oid;

This generates all the required ALTER TABLE / ALTER SEQUENCE / ALTER VIEW statements, copy these and paste them back into plsql to run them.

Check your work in psql by doing:

\dt *.*
\ds *.*
\dv *.*

Why am I getting a "401 Unauthorized" error in Maven?

This is the official explanation from sonatype nexus team about 401 - Unauthorized

I recommend you to read Troubleshooting Artifact Deployment Failures for more information.

Code 401 - Unauthorized

Either no login credentials were sent with the request, or login credentials which are invalid were sent. Checking the "authorization and authentication" system feed in the Nexus UI can help narrow this down. If credentials were sent there will be an entry in the feed.

If no credentials were sent this is likely due to a mis-match between the id in your pom's distributionManagement section and your settings.xml's server section that holds the login credentials.

How to load images dynamically (or lazily) when users scrolls them into view

The Swiss Army knife of image lazy loading is YUI's ImageLoader.

Because there is more to this problem than simply watching the scroll position.

Binary numbers in Python

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.

Current user in Magento?

I don't know this off the top of my head, but look in the file which shows the user's name, etc in the header of the page after the user has logged in. It might help if you turned on template hints (see this tutorial.

When you find the line such as "Hello <? //code for showing username?>", just copy that line and show it where you need to

How to detect a loop in a linked list?

Here's a refinement of the Fast/Slow solution, which correctly handles odd length lists and improves clarity.

boolean hasLoop(Node first) {
    Node slow = first;
    Node fast = first;

    while(fast != null && fast.next != null) {
        slow = slow.next;          // 1 hop
        fast = fast.next.next;     // 2 hops 

        if(slow == fast)  // fast caught up to slow, so there is a loop
            return true;
    }
    return false;  // fast reached null, so the list terminates
}

Div 100% height works on Firefox but not in IE

You might have to put one or both of:

html { height:100%; }

or

body { height:100%; }

EDIT: Whoops, didn't notice they were floated. You just need to float the container.

IIS: Idle Timeout vs Recycle

Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory

Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health

The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"

The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.

Getting an "ambiguous redirect" error

I got this error when trying to use brace expansion to write output to multiple files.

for example: echo "text" > {f1,f2}.txt results in -bash: {f1,f2}.txt: ambiguous redirect

In this case, use tee to output to multiple files:

echo "text" | tee {f1,f2,...,fn}.txt 1>/dev/null

the 1>/dev/null will prevent the text from being written to stdout

If you want to append to the file(s) use tee -a

How do I inject a controller into another controller in AngularJS

I'd suggest the question you should be asking is how to inject services into controllers. Fat services with skinny controllers is a good rule of thumb, aka just use controllers to glue your service/factory (with the business logic) into your views.

Controllers get garbage collected on route changes, so for example, if you use controllers to hold business logic that renders a value, your going to lose state on two pages if the app user clicks the browser back button.

var app = angular.module("testApp", ['']);

app.factory('methodFactory', function () {
    return { myMethod: function () {
            console.log("methodFactory - myMethod");
    };
};

app.controller('TestCtrl1', ['$scope', 'methodFactory', function ($scope,methodFactory) {  //Comma was missing here.Now it is corrected.
    $scope.mymethod1 = methodFactory.myMethod();
}]);

app.controller('TestCtrl2', ['$scope', 'methodFactory', function ($scope, methodFactory) {
    $scope.mymethod2 = methodFactory.myMethod();
}]);

Here is a working demo of factory injected into two controllers

Also, I'd suggest having a read of this tutorial on services/factories.

What is the purpose of using -pedantic in GCC/G++ compiler?

GCC compilers always try to compile your program if this is at all possible. However, in some cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers such as gcc or g++ must issue a diagnostic when these extensions are encountered. For example, the gcc compiler’s -pedantic option causes gcc to issue warnings in such cases. Using the stricter -pedantic-errors option converts such diagnostic warnings into errors that will cause compilation to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming compiler will generate warnings or errors.

What is the correct SQL type to store a .Net Timespan with values > 24:00:00?

To be consistent with what is probably the most likely source of generating a time span (computing the difference of 2 times or date-times), you may want to store a .NET TimeSpan as a SQL Server DateTime Type.

This is because in SQL Server, the difference of 2 DateTime's (Cast to Float's and then Cast back to a DateTime) is simply a DateTime relative to Jan. 1, 1900. Ex. A difference of +0.1 second would be January 1, 1900 00:00:00.100 and -0.1 second would be Dec. 31, 1899 23:59:59.900.

To convert a .NET TimeSpan to a SQL Server DateTime Type, you would first convert it to a .NET DateTime Type by adding it to a DateTime of Jan. 1, 1900. Of course, when you read it into .NET from SQL Server, you would first read it into a .NET DateTime and then subtract Jan. 1, 1900 from it to convert it to a .NET TimeSpan.

For use cases where the time spans are being generated from SQL Server DateTime's and within SQL Server (i.e. via T-SQL) and SQL Server is prior to 2016, depending on your range and precision needs, it may not be practical to store them as milliseconds (not to mention Ticks) because the Int Type returned by DateDiff (vs. the BigInt from SS 2016+'s DateDiff_Big) overflows after ~24 days worth of milliseconds and ~67 yrs. of seconds. Whereas, this solution will handle time spans with precision down to 0.1 seconds and from -147 to +8,099 yrs..

WARNINGS:

  1. This would only work if the difference relative to Jan. 1, 1900 would result in a value within the range of a SQL Server DateTime Type (Jan. 1, 1753 to Dec. 31, 9999 aka -147 to +8,099 yrs.). We don't have to worry near as much on the .NET TimeSpan side, since it can hold ~29 k to +29 k yrs. I didn't mention the SQL Server DateTime2 Type (whose range, on the negative side, is much greater than SQL Server DateTime's), because: a) it cannot be converted to a numeric via a simple Cast and b) DateTime's range should suffice for the vast majority of use cases.

  2. SQL Server DateTime differences computed via the Cast - to - Float - and - back method does not appear to be accurate beyond 0.1 seconds.

Links in <select> dropdown options

Add an onchange event handler and set the pages location to the value

<select id="foo">
    <option value="">Pick a site</option>
    <option value="http://www.google.com">x</option>
    <option value="http://www.yahoo.com">y</option>
</select>

<script>
    document.getElementById("foo").onchange = function() {
        if (this.selectedIndex!==0) {
            window.location.href = this.value;
        }        
    };
</script>

how to remove the first two columns in a file using shell (awk, sed, whatever)

Here's one way to do it with Awk that's relatively easy to understand:

awk '{print substr($0, index($0, $3))}'

This is a simple awk command with no pattern, so action inside {} is run for every input line.

The action is to simply prints the substring starting with the position of the 3rd field.

  • $0: the whole input line
  • $3: 3rd field
  • index(in, find): returns the position of find in string in
  • substr(string, start): return a substring starting at index start

If you want to use a different delimiter, such as comma, you can specify it with the -F option:

awk -F"," '{print substr($0, index($0, $3))}'

You can also operate this on a subset of the input lines by specifying a pattern before the action in {}. Only lines matching the pattern will have the action run.

awk 'pattern{print substr($0, index($0, $3))}'

Where pattern can be something such as:

  • /abcdef/: use regular expression, operates on $0 by default.
  • $1 ~ /abcdef/: operate on a specific field.
  • $1 == blabla: use string comparison
  • NR > 1: use record/line number
  • NF > 0: use field/column number

HashMap and int as key

If you are using Netty and want to use a map with primitive int type keys, you can use its IntObjectHashMap

Some of the reasons to use primitive type collections:

  • improve performance by having specialized code
  • reduce garbage that can put pressure on the GC

The question of specialized vs generalized collections can make or break programs with high throughput requirements.

Auto submit form on page load

Try this On window load submit your form.

window.onload = function(){
  document.forms['member_signup'].submit();
}

Python send UDP packet

Manoj answer above is correct, but another option is to use MESSAGE.encode() or encode('utf-8') to convert to bytes. bytes and encode are mostly the same, encode is compatible with python 2. see here for more

full code:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(), (UDP_IP, UDP_PORT))

java.net.URL read stream to byte[]

It's important to specify timeouts, especially when the server takes to respond. With pure Java, without using any dependency:

public static byte[] copyURLToByteArray(final String urlStr,
        final int connectionTimeout, final int readTimeout) 
                throws IOException {
    final URL url = new URL(urlStr);
    final URLConnection connection = url.openConnection();
    connection.setConnectTimeout(connectionTimeout);
    connection.setReadTimeout(readTimeout);
    try (InputStream input = connection.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream()) {
        final byte[] buffer = new byte[8192];
        for (int count; (count = input.read(buffer)) > 0;) {
            output.write(buffer, 0, count);
        }
        return output.toByteArray();
    }
}

Using dependencies, e.g., HC Fluent:

public byte[] copyURLToByteArray(final String urlStr,
        final int connectionTimeout, final int readTimeout)
                throws IOException {
    return Request.Get(urlStr)
            .connectTimeout(connectionTimeout)
            .socketTimeout(readTimeout)
            .execute()
            .returnContent()
            .asBytes();
}

Stop a youtube video with jquery?

Unfortunately, if id attribute of object tag don't exists, the play/stop/pauseVideo() don't work by IE.

<object style="display: block; margin-left: auto; margin-right: auto;" width="425" height="344" data="http://www.youtube.com/v/7scnebkm3r0&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" />
  <param name="allowscriptaccess" value="always" />
  <param name="allowfullscreen" value="true" />
  <param name="src" value="http://www.youtube.com/v/7scnebkm3r0&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" />
</object>
<object id="idexists" style="display: block; margin-left: auto; margin-right: auto;" width="425" height="344" data="http://www.youtube.com/v/pDW47HNaN84&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" type="application/x-shockwave-flash">
  <param name="allowscriptaccess" value="always" />
  <param name="allowFullScreen" value="true" />
  <param name="src" value="http://www.youtube.com/v/pDW47HNaN84&amp;fs=1&amp;border=1&amp;autoplay=1&amp;enablejsapi=1&amp;version=3" />
</object>
<script>
  function pauseVideo()
  {
    $("object").each
    (
      function(index)
      {
        obj = $(this).get(0);
        if (obj.pauseVideo) obj.pauseVideo();
      }
    );
  }
</script>
<button onClick="pauseVideo();">Pause</button>

Try it!

Set maxlength in Html Textarea

As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea has newline characters, at least on Windows.

I've change his answer slightly thus:

$(function() {
    $("textarea[maxlength]").bind('input propertychange', function() {
        var maxLength = $(this).attr('maxlength');
        //I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
        //Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
        var newlines = ($(this).val().match(/\n/g) || []).length
        if ($(this).val().length + newlines > maxLength) {
            $(this).val($(this).val().substring(0, maxLength - newlines));
        }
    })
});

Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie results in another call to poruszanie, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.

Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.

What is a regular expression for a MAC Address?

Maybe the shortest possible:

/([\da-f]{2}[:-]){5}[\da-f]{2}/i

Update: A better way exists to validate MAC addresses in PHP which supports for both hyphen-styled and colon-styled MAC addresses. Use filter_var():

// Returns $macAddress, if it's a valid MAC address
filter_var($macAddress, FILTER_VALIDATE_MAC);

As I know, it supports MAC addresses in these forms (x: a hexadecimal number):

xx:xx:xx:xx:xx:xx
xx-xx-xx-xx-xx-xx
xxxx.xxxx.xxxx

Flask SQLAlchemy query, specify column names

You can use the with_entities() method to restrict which columns you'd like to return in the result. (documentation)

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize

-XX:MaxPermSize=size

Sets the maximum permanent generation space size (in bytes). This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

-XX:PermSize=size

Sets the space (in bytes) allocated to the permanent generation that triggers a garbage collection if it is exceeded. This option was deprecated in JDK 8, and superseded by the -XX:MetaspaceSize option.

Efficient way to remove keys with empty strings from a dict

Some of Methods mentioned above ignores if there are any integers and float with values 0 & 0.0

If someone wants to avoid the above can use below code(removes empty strings and None values from nested dictionary and nested list):

def remove_empty_from_dict(d):
    if type(d) is dict:
        _temp = {}
        for k,v in d.items():
            if v == None or v == "":
                pass
            elif type(v) is int or type(v) is float:
                _temp[k] = remove_empty_from_dict(v)
            elif (v or remove_empty_from_dict(v)):
                _temp[k] = remove_empty_from_dict(v)
        return _temp
    elif type(d) is list:
        return [remove_empty_from_dict(v) for v in d if( (str(v).strip() or str(remove_empty_from_dict(v)).strip()) and (v != None or remove_empty_from_dict(v) != None))]
    else:
        return d

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

How to get the file path from HTML input form in Firefox 3

Simply you cannot do it with FF3.

The other option could be using applet or other controls to select and upload files.

Getting the current date in SQL Server?

SELECT CAST(GETDATE() AS DATE)

Returns the current date with the time part removed.

DATETIMEs are not "stored in the following format". They are stored in a binary format.

SELECT CAST(GETDATE() AS BINARY(8))

The display format in the question is independent of storage.

Formatting into a particular display format should be done by your application.

Decoding a Base64 string in Java

The following should work with the latest version of Apache common codec

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw==");
System.out.println(new String(decodedBytes));

and for encoding

byte[] encodedBytes = Base64.getEncoder().encode(decodedBytes);
System.out.println(new String(encodedBytes));

Best way to randomize an array with .NET

The following implementation uses the Fisher-Yates algorithm AKA the Knuth Shuffle. It runs in O(n) time and shuffles in place, so is better performing than the 'sort by random' technique, although it is more lines of code. See here for some comparative performance measurements. I have used System.Random, which is fine for non-cryptographic purposes.*

static class RandomExtensions
{
    public static void Shuffle<T> (this Random rng, T[] array)
    {
        int n = array.Length;
        while (n > 1) 
        {
            int k = rng.Next(n--);
            T temp = array[n];
            array[n] = array[k];
            array[k] = temp;
        }
    }
}

Usage:

var array = new int[] {1, 2, 3, 4};
var rng = new Random();
rng.Shuffle(array);
rng.Shuffle(array); // different order from first call to Shuffle

* For longer arrays, in order to make the (extremely large) number of permutations equally probable it would be necessary to run a pseudo-random number generator (PRNG) through many iterations for each swap to produce enough entropy. For a 500-element array only a very small fraction of the possible 500! permutations will be possible to obtain using a PRNG. Nevertheless, the Fisher-Yates algorithm is unbiased and therefore the shuffle will be as good as the RNG you use.

What is the best JavaScript code to create an img element

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Find files containing a given text

find them and grep for the string:

This will find all files of your 3 types in /starting/path and grep for the regular expression '(document\.cookie|setcookie)'. Split over 2 lines with the backslash just for readability...

find /starting/path -type f -name "*.php" -o -name "*.html" -o -name "*.js" | \
 xargs egrep -i '(document\.cookie|setcookie)'

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

You may try this, This list dynamic branch names in dropdown w.r.t inputted Git Repo.

Jenkins Plugins required:

  1. Validating String Parameter
  2. Active Choices

OPTION 1: Jenkins File:

    properties([
        [$class: 'JobRestrictionProperty'], parameters([validatingString(defaultValue: 'https://github.com/kubernetes/kubernetes.git', description: 'Input Git Repo (https) Url', failedValidationMessage: 'Invalid Git Url. Retry again', name: 'GIT_REPO', regex: 'https://.*'), [$class: 'CascadeChoiceParameter', choiceType: 'PT_SINGLE_SELECT', description: 'Select Git Branch Name', filterLength: 1, filterable: false, name: 'BRANCH_NAME', randomName: 'choice-parameter-8292706885056518', referencedParameters: 'GIT_REPO', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: false, script: 'return[\'Error - Unable to retrive Branch name\']'], script: [classpath: [], sandbox: false, script: ''
                            'def GIT_REPO_SRC = GIT_REPO.tokenize(\'/\')
                            GIT_REPO_FULL = GIT_REPO_SRC[-2] + \'/\' + GIT_REPO_SRC[-1]
                            def GET_LIST = ("git ls-remote --heads [email protected]:${GIT_REPO_FULL}").execute()
                            GET_LIST.waitFor()
                            BRANCH_LIST = GET_LIST.in.text.readLines().collect {
                                it.split()[1].replaceAll("refs/heads/", "").replaceAll("refs/tags/", "").replaceAll("\\\\^\\\\{\\\\}", "")
                            }
                            return BRANCH_LIST ''
                            ']]]]), throttleJobProperty(categories: [], limitOneJobWithMatchingParams: false, maxConcurrentPerNode: 0, maxConcurrentTotal: 0, paramsToUseForLimit: '
                            ', throttleEnabled: false, throttleOption: '
                            project '), [$class: '
                            JobLocalConfiguration ', changeReasonComment: '
                            ']])
    try {
        node('master') {
            stage('Print Variables') {
                echo "Branch Name: ${BRANCH_NAME}"
            }
    }
    catch (e) {
        currentBuild.result = "FAILURE"
        print e.getMessage();
        print e.getStackTrace();
    }



OPTION 2: Jenkins UI

enter image description here

enter image description here



Sample Output:

enter image description here

Downloading folders from aws s3, cp or sync?

Just used version 2 of the AWS CLI. For the s3 option, there is also a --dryrun option now to show you what will happen:

aws s3 --dryrun cp s3://bucket/filename /path/to/dest/folder --recursive

How to copy part of an array to another array in C#?

In case if you want to implement your own Array.Copy method.

Static method which is of generic type.

 static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
 {
  long totaltraversal = sourceIndex + copyNoOfElements;
  long sourceArrayLength = sourceArray.Length;

  //to check all array's length and its indices properties before copying
  CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
   for (long i = sourceIndex; i < totaltraversal; i++)
     {
      destinationArray[destinationIndex++] = sourceArray[i]; 
     } 
  }

Boundary method implementation.

private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
        {
            if (sourceIndex >= sourceArray.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (copyNoOfElements > sourceArrayLength)
            {
                throw new IndexOutOfRangeException();
            }
            if (destinationArray.Length < copyNoOfElements)
            {
                throw new IndexOutOfRangeException();
            }
        }

clear table jquery

Use .remove()

$("#yourtableid tr").remove();

If you want to keep the data for future use even after removing it then you can use .detach()

$("#yourtableid tr").detach();

If the rows are children of the table then you can use child selector instead of descendant selector, like

$("#yourtableid > tr").remove();

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Facebook provides two ways to login and logout from an account. One is to use LoginButton and the other is to use LoginManager. LoginButton is just a button which on clicked, the logging in is accomplished. On the other side LoginManager does this on its own. In your case you have use LoginManager to logout automatically.

LoginManager.getInstance().logout() does this work for you.

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

What is the default font of Sublime Text?

On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:

  1. go to View menu and select Show Console
  2. Then enter this command: view.settings().get('font_face')

You will find your default font.

How to log out user from web site using BASIC authentication?

An addition to the answer by bobince ...

With Ajax you can have your 'Logout' link/button wired to a Javascript function. Have this function send the XMLHttpRequest with a bad username and password. This should get back a 401. Then set document.location back to the pre-login page. This way, the user will never see the extra login dialog during logout, nor have to remember to put in bad credentials.

Richtextbox wpf binding

Create a UserControl which has a RichTextBox named RTB. Now add the following dependency property:

    public FlowDocument Document
    {
        get { return (FlowDocument)GetValue(DocumentProperty); }
        set { SetValue(DocumentProperty, value); }
    }

    public static readonly DependencyProperty DocumentProperty =
        DependencyProperty.Register("Document", typeof(FlowDocument), typeof(RichTextBoxControl), new PropertyMetadata(OnDocumentChanged));

    private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        RichTextBoxControl control = (RichTextBoxControl) d;
        FlowDocument document = e.NewValue as FlowDocument;
        if (document  == null)
        {
            control.RTB.Document = new FlowDocument(); //Document is not amused by null :)
        }
        else
        {
            control.RTB.Document = document;
        }
    }

This solution is probably that "proxy" solution you saw somewhere.. However.. RichTextBox simply does not have Document as DependencyProperty... So you have to do this in another way...

HTH

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

Reverse each individual word of "Hello World" string with Java

Using split(), you just have to change what you wish to split on.

public static String reverseString(String str)
{
    String[] rstr;
    String result = "";
    int count = 0;
    rstr = str.split(" ");
    String words[] = new String[rstr.length];
    for(int i = rstr.length-1; i >= 0; i--)
    {
        words[count] = rstr[i];
        count++;
    }

    for(int j = 0; j <= words.length-1; j++)
    {
        result += words[j] + " ";
    }

    return result;


}

Uncaught TypeError: Cannot read property 'top' of undefined

Your document does not contain any element with class content-nav, thus the method .offset() returns undefined which indeed has no top property.

You can see for yourself in this fiddle

alert($('.content-nav').offset());

(you will see "undefined")

To avoid crashing the whole code, you can have such code instead:

var top = ($('.content-nav').offset() || { "top": NaN }).top;
if (isNaN(top)) {
    alert("something is wrong, no top");
} else {
    alert(top);
}

Updated fiddle.

How to reverse a singly linked list using only two pointers?

Yes. I'm sure you can do this the same way you can swap two numbers without using a third. Simply cast the pointers to a int/long and perform the XOR operation a couple of times. This is one of those C tricks that makes for a fun question, but doesn't have any practical value.

Can you reduce the O(n) complexity? No, not really. Just use a doubly linked list if you think you are going to need the reverse order.

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

How to read and write into file using JavaScript?

here's the mozilla proposal

http://www-archive.mozilla.org/js/js-file-object.html

this is implemented with a compilation switch in spidermonkey, and also in adobe's extendscript. Additionally (I think) you get the File object in firefox extensions.

rhino has a (rather rudementary) readFile function https://developer.mozilla.org/en/Rhino_Shell

for more complex file operations in rhino, you can use java.io.File methods.

you won't get any of this stuff in the browser though. For similar functionality in a browser you can use the SQL database functions from HTML5, clientside persistence, cookies, and flash storage objects.

Can't Load URL: The domain of this URL isn't included in the app's domains

I had the same problem, and it came from a wrong client_id / Facebook App ID.

Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.

You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.

Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:

Valid OAuth redirect URIs : example.com/

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

just try this:

_x000D_
_x000D_
//don't call getActivity()
getActivity().startActivityForResult(intent, REQ_CODE);

//just call 
startActivityForResult(intent, REQ_CODE);
//directly from fragment
_x000D_
_x000D_
_x000D_

Reading from memory stream to string

string result = Encoding.UTF8.GetString((stream as MemoryStream).ToArray());

How do I pipe or redirect the output of curl -v?

Your URL probably has ampersands in it. I had this problem, too, and I realized that my URL was full of ampersands (from CGI variables being passed) and so everything was getting sent to background in a weird way and thus not redirecting properly. If you put quotes around the URL it will fix it.

How to check if another instance of the application is running

The Process static class has a method GetProcessesByName() which you can use to search through running processes. Just search for any other process with the same executable name.

Count number of objects in list

You can also use unlist(), which is often useful for handling lists:

> mylist <- list(A = c(1:3), B = c(4:6), C = c(7:9))

> mylist
$A
[1] 1 2 3

$B
[1] 4 5 6

$C
[1] 7 8 9

> unlist(mylist)
A1 A2 A3 B1 B2 B3 C1 C2 C3 
 1  2  3  4  5  6  7  8  9 

> length(unlist(mylist))
[1] 9

unlist() is a simple way of executing other functions on lists as well, such as:

> sum(mylist)
Error in sum(mylist) : invalid 'type' (list) of argument

> sum(unlist(mylist))
[1] 45

OAuth: how to test with local URLs?

For Mac users, edit the /etc/hosts file. You have to use sudo vi /etc/hosts if its read-only. After authorization, the oauth server sends the callback URL, and since that callback URL is rendered on your local browser, the local DNS setting will work:

127.0.0.1       mylocal.com

Read and write to binary files in C?

This is an example to read and write binary jjpg or wmv video file. FILE *fout; FILE *fin;

Int ch;
char *s;
fin=fopen("D:\\pic.jpg","rb");
if(fin==NULL)
     {  printf("\n Unable to open the file ");
         exit(1);
      }

 fout=fopen("D:\\ newpic.jpg","wb");
 ch=fgetc(fin);
       while (ch!=EOF)
             { 
                  s=(char *)ch;
                  printf("%c",s);
                 ch=fgetc (fin):
                 fputc(s,fout);
                 s++;
              }

        printf("data read and copied");
        fclose(fin);
        fclose(fout);

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

To add to @adilapapaya's answer. For ember-cli users specifically, install tether with

bower install --save tether

and then include it in your ember-cli-build.js file before bootstrap, like so:

// tether (bootstrap 4 requirement)
app.import('bower_components/tether/dist/js/tether.min.js');

// bootstrap
app.import('bower_components/bootstrap/scss/bootstrap-flex.scss');
app.import('bower_components/bootstrap/dist/js/bootstrap.js');

Getting Unexpected Token Export

There is no need to use Babel at this moment (JS has become very powerful) when you can simply use the default JavaScript module exports. Check full tutorial

Message.js

module.exports = 'Hello world';

app.js

var msg = require('./Messages.js');

console.log(msg); // Hello World

What is a reasonable code coverage % for unit tests (and why)?

It depends greatly on your application. For example, some applications consist mostly of GUI code that cannot be unit tested.

Start an external application from a Google Chrome Extension?

You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.

E.g. you have the users set things up so that some-app:// links start "SomeApp", and then in my-awesome-extension you open a tab pointing to some-app://some-data-the-app-wants, and you're good to go!

Determining the last row in a single column

After a while trying to build a function to get an integer with the last row in a single column, this worked fine:

    function lastRow() {
    var spreadsheet = SpreadsheetApp.getActiveSheet();
    spreadsheet.getRange('B1').activate();
    var columnB = spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
    var numRows = columnB.getLastRow();
    var nextRow = numRows + 1; 
    }

mySQL convert varchar to date

select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 

or

select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 

hard to tell from your example

afxwin.h file is missing in VC++ Express Edition

I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?

How to style a select tag's option element?

It's a choice (from browser devs or W3C, I can't find any W3C specification about styling select options though) not allowing to style select options.

I suspect this would be to keep consistency with native choice lists.
(think about mobile devices for example).

3 solutions come to my mind:

  • Use Select2 which actually converts your selects into uls (allowing many things)
  • Split your selects into multiple in order to group values
  • Split into optgroup

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

I check Query Log to see the exact query that was executed as prepared statement.

How to change color and font on ListView

use them in Java code like this:

 color = getResources().getColor(R.color.mycolor);

The getResources() method returns the ResourceManager class for the current activity, and getColor() asks the manager to look up a color given a resource ID

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I know this is an old post, but for anyone using Retrofit, this can be useful useful.

If you are using Retrofit + Jackson + Kotlin + Data classes, you need:

  1. add implement group: 'com.fasterxml.jackson.module', name: 'jackson-module-kotlin', version: '2.7.1-2' to your dependencies, so that Jackson can de-serialize into Data classes
  2. When building retrofit, pass the Kotlin Jackson Mapper, so that Retrofit uses the correct mapper, ex:
    val jsonMapper = com.fasterxml.jackson.module.kotlin.jacksonObjectMapper()

    val retrofit = Retrofit.Builder()
          ...
          .addConverterFactory(JacksonConverterFactory.create(jsonMapper))
          .build()

Note: If Retrofit is not being used, @Jayson Minard has a more general approach answer.

How to find distinct rows with field in list using JPA and Spring?

Can you not use like this?

@Query("SELECT DISTINCT name FROM people p (nolock) WHERE p.name NOT IN (:myparam)")
List<String> findNonReferencedNames(@Param("myparam")List<String> names);

P.S. I write queries in SQL Server 2012 a lot and using nolock in server is a good practice, you can ignore nolock if a local db is used.

Seems like your db name is not being mapped correctly (after you've updated your question)

Updating state on props change in React Form

componentWillReceiveProps is being deprecated because using it "often leads to bugs and inconsistencies".

If something changes from the outside, consider resetting the child component entirely with key.

Providing a key prop to the child component makes sure that whenever the value of key changes from the outside, this component is re-rendered. E.g.,

<EmailInput
  defaultEmail={this.props.user.email}
  key={this.props.user.id}
/>

On its performance:

While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.

Converting a generic list to a CSV string

As the code in the link given by @Frank Create a CSV File from a .NET Generic List there was a little issue of ending every line with a , I modified the code to get rid of it.Hope it helps someone.

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
    if (list == null || list.Count == 0) return;

    //get type from 0th member
    Type t = list[0].GetType();
    string newLine = Environment.NewLine;

    if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));

    if (!File.Exists(csvCompletePath)) File.Create(csvCompletePath);

    using (var sw = new StreamWriter(csvCompletePath))
    {
        //make a new instance of the class name we figured out to get its props
        object o = Activator.CreateInstance(t);
        //gets all properties
        PropertyInfo[] props = o.GetType().GetProperties();

        //foreach of the properties in class above, write out properties
        //this is the header row
        sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);

        //this acts as datarow
        foreach (T item in list)
        {
            //this acts as datacolumn
            var row = string.Join(",", props.Select(d => item.GetType()
                                                            .GetProperty(d.Name)
                                                            .GetValue(item, null)
                                                            .ToString())
                                                    .ToArray());
            sw.Write(row + newLine);

        }
    }
}

How to convert unsigned long to string

For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,

as a reference of available options see sprintf

#include <stdio.h>

    int main ()
    {
      unsigned long lval = 123;
      char buffer [50];
      sprintf (buffer, "%lu" , lval );
     }

How to read data From *.CSV file using javascript?

NOTE: I concocted this solution before I was reminded about all the "special cases" that can occur in a valid CSV file, like escaped quotes. I'm leaving my answer for those who want something quick and dirty, but I recommend Evan's answer for accuracy.


This code will work when your data.txt file is one long string of comma-separated entries, with no newlines:

data.txt:

 heading1,heading2,heading3,heading4,heading5,value1_1,...,value5_2

javascript:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "data.txt",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(allText) {
    var record_num = 5;  // or however many elements there are in each row
    var allTextLines = allText.split(/\r\n|\n/);
    var entries = allTextLines[0].split(',');
    var lines = [];

    var headings = entries.splice(0,record_num);
    while (entries.length>0) {
        var tarr = [];
        for (var j=0; j<record_num; j++) {
            tarr.push(headings[j]+":"+entries.shift());
        }
        lines.push(tarr);
    }
    // alert(lines);
}

The following code will work on a "true" CSV file with linebreaks between each set of records:

data.txt:

heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2

javascript:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "data.txt",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    var lines = [];

    for (var i=1; i<allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = [];
            for (var j=0; j<headers.length; j++) {
                tarr.push(headers[j]+":"+data[j]);
            }
            lines.push(tarr);
        }
    }
    // alert(lines);
}

http://jsfiddle.net/mblase75/dcqxr/

Angular 2 Checkbox Two Way Data Binding

A workaround to achieve the same specially if you want to use checkbox with for loop is to store the state of the checkbox inside an array and change it based on the index of the *ngFor loop. This way you can change the state of the checkbox in your component.

app.component.html

<div *ngFor="let item of items; index as i"> <input type="checkbox" [checked]="category[i]" (change)="checkChange(i)"> {{item.name}} </div>

app.component.ts

items = [
    {'name':'salad'},
    {'name':'juice'},
    {'name':'dessert'},
    {'name':'combo'}
  ];

  category= []

  checkChange(i){
    if (this.category[i]){  
      this.category[i] = !this.category[i];
    }
    else{
      this.category[i] = true;
    }
  }

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Abort Ajax requests using jQuery

You can abort any continuous ajax call by using this

<input id="searchbox" name="searchbox" type="text" />

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
     var request = null;
        $('#searchbox').keyup(function () {
            var id = $(this).val();
            request = $.ajax({
                type: "POST", //TODO: Must be changed to POST
                url: "index.php",
                data: {'id':id},
                success: function () {
    
                },
                beforeSend: function () {
                    if (request !== null) {
                        request.abort();
                    }
                }
            });
        });
</script>

Android Gradle Apache HttpClient does not exist?

Perfect Answer by Jinu and Daniel

Adding to this I solved the Issue by Using This, if your compileSdkVersion is 19(IN MY CASE)

compile ('org.apache.httpcomponents:httpmime:4.3'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile ('org.apache.httpcomponents:httpcore:4.4.1'){
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}
compile 'commons-io:commons-io:1.3.2'

else if your compileSdkVersion is 23 then use

android {
useLibrary 'org.apache.http.legacy'
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    }
}

Do I cast the result of malloc?

Just adding my experience, studying computer engineering I see that the two or three professors that I have seen writing in C always cast malloc, however the one I asked (with an immense CV and understanding of C) told me that it is absolutely unnecessary but only used to be absolutely specific, and to get the students into the mentality of being absolutely specific. Essentially casting will not change anything in how it works, it does exactly what it says, allocates memory, and casting does not effect it, you get the same memory, and even if you cast it to something else by mistake (and somehow evade compiler errors) C will access it the same way.

Edit: Casting has a certain point. When you use array notation, the code generated has to know how many memory places it has to advance to reach the beginning of the next element, this is achieved through casting. This way you know that for a double you go 8 bytes ahead while for an int you go 4, and so on. Thus it has no effect if you use pointer notation, in array notation it becomes necessary.

Dynamic tabs with user-click chosen components

I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.

'@angular/core': {
  main: 'bundles/core.umd.js',
  defaultExtension: 'js'
},
'@angular/compiler': {
  main: 'bundles/compiler.umd.js',
  defaultExtension: 'js'
},
'@angular/common': {
  main: 'bundles/common.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
  main: 'bundles/platform-browser-dynamic.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser': {
  main: 'bundles/platform-browser.umd.js',
  defaultExtension: 'js'
},

https://plnkr.co/edit/kVJvI1vkzrLZJeRFsZuv?p=preview

Easy way to use variables of enum types as string in C?

The technique from Making something both a C identifier and a string? can be used here.

As usual with such preprocessor stuff, writing and understanding the preprocessor part can be hard, and includes passing macros to other macros and involves using # and ## operators, but using it is real easy. I find this style very useful for long enums, where maintaining the same list twice can be really troublesome.

Factory code - typed only once, usually hidden in the header:

enumFactory.h:

// expansion macro for enum value definition
#define ENUM_VALUE(name,assign) name assign,

// expansion macro for enum to string conversion
#define ENUM_CASE(name,assign) case name: return #name;

// expansion macro for string to enum conversion
#define ENUM_STRCMP(name,assign) if (!strcmp(str,#name)) return name;

/// declare the access function and define enum values
#define DECLARE_ENUM(EnumType,ENUM_DEF) \
  enum EnumType { \
    ENUM_DEF(ENUM_VALUE) \
  }; \
  const char *GetString(EnumType dummy); \
  EnumType Get##EnumType##Value(const char *string); \

/// define the access function names
#define DEFINE_ENUM(EnumType,ENUM_DEF) \
  const char *GetString(EnumType value) \
  { \
    switch(value) \
    { \
      ENUM_DEF(ENUM_CASE) \
      default: return ""; /* handle input error */ \
    } \
  } \
  EnumType Get##EnumType##Value(const char *str) \
  { \
    ENUM_DEF(ENUM_STRCMP) \
    return (EnumType)0; /* handle input error */ \
  } \

Factory used

someEnum.h:

#include "enumFactory.h"
#define SOME_ENUM(XX) \
    XX(FirstValue,) \
    XX(SecondValue,) \
    XX(SomeOtherValue,=50) \
    XX(OneMoreValue,=100) \

DECLARE_ENUM(SomeEnum,SOME_ENUM)

someEnum.cpp:

#include "someEnum.h"
DEFINE_ENUM(SomeEnum,SOME_ENUM)

The technique can be easily extended so that XX macros accepts more arguments, and you can also have prepared more macros to substitute for XX for different needs, similar to the three I have provided in this sample.

Comparison to X-Macros using #include / #define / #undef

While this is similar to X-Macros others have mentioned, I think this solution is more elegant in that it does not require #undefing anything, which allows you to hide more of the complicated stuff is in the factory the header file - the header file is something you are not touching at all when you need to define a new enum, therefore new enum definition is a lot shorter and cleaner.

Return in Scala

It's not as simple as just omitting the return keyword. In Scala, if there is no return then the last expression is taken to be the return value. So, if the last expression is what you want to return, then you can omit the return keyword. But if what you want to return is not the last expression, then Scala will not know that you wanted to return it.

An example:

def f() = {
  if (something)
    "A"
  else
    "B"
}

Here the last expression of the function f is an if/else expression that evaluates to a String. Since there is no explicit return marked, Scala will infer that you wanted to return the result of this if/else expression: a String.

Now, if we add something after the if/else expression:

def f() = {
  if (something)
    "A"
  else
    "B"

  if (somethingElse)
    1
  else
    2
}

Now the last expression is an if/else expression that evaluates to an Int. So the return type of f will be Int. If we really wanted it to return the String, then we're in trouble because Scala has no idea that that's what we intended. Thus, we have to fix it by either storing the String to a variable and returning it after the second if/else expression, or by changing the order so that the String part happens last.

Finally, we can avoid the return keyword even with a nested if-else expression like yours:

def f() = {
  if(somethingFirst) {
    if (something)      // Last expression of `if` returns a String
     "A"
    else
     "B"
  }
  else {
    if (somethingElse)
      1
    else
      2

    "C"                // Last expression of `else` returns a String
  }

}

TypeScript error: Type 'void' is not assignable to type 'boolean'

Your code is passing a function as an argument to find. That function takes an element argument (of type Conversation) and returns void (meaning there is no return value). TypeScript describes this as (element: Conversation) => void'

What TypeScript is saying is that the find function doesn't expect to receive a function that takes a Conversation and returns void. It expects a function that takes a Conversations, a number and a Conversation array, and that this function should return a boolean.

So bottom line is that you either need to change your code to pass in the values to find correctly, or else you need to provide an overload to the definition of find in your definition file that accepts a Conversation and returns void.

WAMP 403 Forbidden message on Windows 7

My solution was to disable encoding for encoded files (these files are green in windows). Ive got these files from MAC computer and it was encrypted by default.

Ive select these files > right click > properities > general tab > andvanced > uncheck encrypt files...

And voila it works.

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.


You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.

In your settings.xml you would add something like this to set your internal repository as as mirror for central:

<mirrors>
  <mirror>
    <id>ibiblio.org</id>
    <name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
    <url>http://path/to/my/repository</url>
    <mirrorOf>central</mirrorOf>
  </mirror>
</mirrors>

If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.


A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.

You would configure the repository (in your pom or a profile in the settings.xml) as follows:

<repository>
  <id>central</id>
  <url>http://repo1.maven.org/maven2</url>
  <updatePolicy>never</updatePolicy>
</repository>

Command not found error in Bash variable assignment

In the interactive mode everything looks fine:

$ str="Hello World"
$ echo $str
Hello World

Obviously(!) as Johannes said, no space around =. In case there is any space around = then in the interactive mode it gives errors as

No command 'str' found

Difference between javacore, thread dump and heap dump in Websphere

A thread dump is a dump of the stacks of all live threads. Thus useful for analysing what an app is up to at some point in time, and if done at intervals handy in diagnosing some kinds of 'execution' problems (e.g. thread deadlock).

A heap dump is a dump of the state of the Java heap memory. Thus useful for analysing what use of memory an app is making at some point in time so handy in diagnosing some memory issues, and if done at intervals handy in diagnosing memory leaks.

This is what they are in 'raw' terms, and could be provided in many ways. In general used to describe dumped files from JVMs and app servers, and in this form they are a low level tool. Useful if for some reason you can't get anything else, but you will find life easier using decent profiling tool to get similar but easier to dissect info.

With respect to WebSphere a javacore file is a thread dump, albeit with a lot of other info such as locks and loaded classes and some limited memory usage info, and a PHD file is a heap dump.

If you want to read a javacore file you can do so by hand, but there is an IBM tool (BM Thread and Monitor Dump Analyzer) which makes it simpler. If you want to read a heap dump file you need one of many IBM tools: MDD4J or Heap Analyzer.

Python and pip, list all versions of a package that's available?

Simple bash script that relies only on python itself (I assume that in the context of the question it should be installed) and one of curl or wget. It has an assumption that you have setuptools package installed to sort versions (almost always installed). It doesn't rely on external dependencies such as:

  • jq which may not be present;
  • grep and awk that may behave differently on Linux and macOS.
curl --silent --location https://pypi.org/pypi/requests/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))"

A little bit longer version with comments.

Put the package name into a variable:

PACKAGE=requests

Get versions (using curl):

VERSIONS=$(curl --silent --location https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")

Get versions (using wget):

VERSIONS=$(wget -qO- https://pypi.org/pypi/$PACKAGE/json | python -c "import sys, json, pkg_resources; releases = json.load(sys.stdin)['releases']; print(' '.join(sorted(releases, key=pkg_resources.parse_version)))")

Print sorted versions:

echo $VERSIONS

How to initialize a struct in accordance with C programming language standards

I didn't like any of these answers so I made my own. I don't know if this is ANSI C or not, it's just GCC 4.2.1 in it's default mode. I never can remember the bracketing so I start with a subset of my data and do battle with compiler error messages until it shuts up. Readability is my first priority.

    // in a header:
    typedef unsigned char uchar;

    struct fields {
      uchar num;
      uchar lbl[35];
    };

    // in an actual c file (I have 2 in this case)
    struct fields labels[] = {
      {0,"Package"},
      {1,"Version"},
      {2,"Apport"},
      {3,"Architecture"},
      {4,"Bugs"},
      {5,"Description-md5"},
      {6,"Essential"},
      {7,"Filename"},
      {8,"Ghc-Package"},
      {9,"Gstreamer-Version"},
      {10,"Homepage"},
      {11,"Installed-Size"},
      {12,"MD5sum"},
      {13,"Maintainer"},
      {14,"Modaliases"},
      {15,"Multi-Arch"},
      {16,"Npp-Description"},
      {17,"Npp-File"},
      {18,"Npp-Name"},
      {19,"Origin"}
    };

The data may start life as a tab-delimited file that you search-replace to massage into something else. Yes, this is Debian stuff. So one outside pair of {} (indicating the array), then another pair for each struct inside. With commas between. Putting things in a header isn't strictly necessary, but I've got about 50 items in my struct so I want them in a separate file, both to keep the mess out of my code and so it's easier to replace.

Replacing some characters in a string with another character

read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter

^use as many of these as you need, and you can make your own BASIC encryption

How to import js-modules into TypeScript file?

2021 Solution

If you're still getting this error message:

TS7016: Could not find a declaration file for module './myjsfile'

Then you might need to add the following to tsconfig.json

{
  "compilerOptions": {
    ...
    "allowJs": true,
    "checkJs": false,
    ...
  }
}

This prevents typescript from trying to apply module types to the imported javascript.

flutter remove back button on appbar

The AppBar widget has a property called automaticallyImplyLeading. By default it's value is true. If you don't want flutter automatically build the back button for you then just make the property false.

appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"), 
  automaticallyImplyLeading: false,
),

To add your custom back button

appBar: AppBar(
  title: Text("YOUR_APPBAR_TITLE"), 
  automaticallyImplyLeading: false,
  leading: YOUR_CUSTOM_WIDGET(),
),

Looping through dictionary object

One way is to loop through the keys of the dictionary, which I recommend:

foreach(int key in sp.Keys)
    dynamic value = sp[key];

Another way, is to loop through the dictionary as a sequence of pairs:

foreach(KeyValuePair<int, dynamic> pair in sp)
{
    int key = pair.Key;
    dynamic value = pair.Value;
}

I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x) helps you retrieve the items in ascending order of the key. Note that Dictionary uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.

Update (01 Dec 2016): replaced vars with actual types to make the answer more clear.

What determines the monitor my app runs on?

Right click the shortcut and select properties. Make sure you are on the "Shortcut" Tab. Select the RUN drop down box and change it to Maximized.

This may assist in launching the program in full screen on the primary monitor.

How to reset Django admin password?

You can create a new superuser with createsuperuser command.

Prompt for user input in PowerShell

Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.

   Param(
     [Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
     [SecureString]$password
   )

   $pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

If you want to debug and see the value of the password you just read, use:

   write-host $pw

Name node is in safe mode. Not able to leave

Namenode enters into safemode when there is shortage of memory. As a result the HDFS becomes readable only. That means one can not create any additional directory or file in the HDFS. To come out of the safemode, the following command is used:

hadoop dfsadmin -safemode leave

If you are using cloudera manager:

go to >>Actions>>Leave Safemode

But it doesn't always solve the problem. The complete solution lies in making some space in the memory. Use the following command to check your memory usage.

free -m

If you are using cloudera, you can also check if the HDFS is showing some signs of bad health. It probably must be showing some memory issue related to the namenode. Allot more memory by following the options available. I am not sure what commands to use for the same if you are not using cloudera manager but there must be a way. Hope it helps! :)

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).