Programs & Examples On #Protobuf net

An independent implementation of Google's protobuf binary serialization format, protobuf-net approaches the problem-space with common .NET coding styles, but retaining the high performance, dense output and cross-platform interoperability.

Converting Stream to String and back...what are we missing?

Try this.

string output1 = Encoding.ASCII.GetString(byteArray, 0, byteArray.Length)

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

How to handle-escape both single and double quotes in an SQL-Update statement

Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:

SELECT 'How is my son''s school helping him learn?  "Not as good as Stack Overflow would!"'

Print:

How is my son's school helping him learn? "Not as good as Stack Overflow would!"

How to display 3 buttons on the same line in css

Do something like this,

HTML :

<div style="width:500px;">
    <button type="submit" class="msgBtn" onClick="return false;" >Save</button>
    <button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
    <button class="msgBtnBack">Back</button>
</div>

CSS :

div button{
    display:inline-block;
}

Fiddle Demo

Or

HTML :

<div style="width:500px;" id="container">
    <div><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
    <div><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
    <div><button class="msgBtnBack">Back</button></div>
</div>

CSS :

#container div{
    display:inline-block;
    width:130px;
}

Fiddle Demo

How to Call VBA Function from Excel Cells?

A Function will not work, nor is it necessary:

Sub OpenWorkbook()
    Dim r1 As Range, r2 As Range, o As Workbook
    Set r1 = ThisWorkbook.Sheets("Sheet1").Range("A1")
    Set o = Workbooks.Open(Filename:="C:\TestFolder\ABC.xlsx")
    Set r2 = ActiveWorkbook.Sheets("Sheet1").Range("B2")
    [r1] = [r2]
    o.Close
End Sub

Default Values to Stored Procedure in Oracle

Default-Values are only considered for parameters NOT given to the function.

So given a function

procedure foo( bar1 IN number DEFAULT 3,
     bar2 IN number DEFAULT 5,
     bar3 IN number DEFAULT 8 );

if you call this procedure with no arguments then it will behave as if called with

foo( bar1 => 3,
     bar2 => 5,
     bar3 => 8 );

but 'NULL' is still a parameter.

foo( 4,
     bar3 => NULL );

This will then act like

foo( bar1 => 4,
     bar2 => 5,
     bar3 => Null );

( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )

one way to treat NULL the same as a default value would be to default the value to NULL

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL );

and using a variable with the desired value then

procedure foo( bar1 IN number DEFAULT NULL,
     bar2 IN number DEFAULT NULL,
     bar3 IN number DEFAULT NULL )
AS
     v_bar1    number := NVL( bar1, 3);
     v_bar2    number := NVL( bar2, 5);
     v_bar3    number := NVL( bar3, 8);

Delete first character of a string in Javascript

var test = '0test';
test = test.replace(/0(.*)/, '$1');

How to compare only date components from DateTime in EF?

Just always compare the Date property of DateTime, instead of the full date time.

When you make your LINQ query, use date.Date in the query, ie:

var results = from c in collection
              where c.Date == myDateTime.Date
              select c;

How to overwrite files with Copy-Item in PowerShell

As I understand Copy-Item -Exclude then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item as in

Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item  -Path $copyAdmin -Destination $AdminPath -Recurse -force

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

setting global sql_mode in mysql

Check the documentation of sql_mode

Method 1:

Check default value of sql_mode:

SELECT @@sql_mode //check current value for sql_mode

SET GLOBAL sql_mode = "NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION";

Method 2:

Access phpmyadmin for editing your sql_mode

  • Login on phpmyadmin and open localhost
  • Top on Variables present on the top in menu items and search out for sql mode
  • Click on edit button to modify sql_mode based on your requirements
  • Save the changes

sql mode settings in phpmyadmin

Restart server after executing above things

Multiple condition in single IF statement

Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

How to refresh an access form

"Requery" is indeed what you what you want to run, but you could do that in Form A's "On Got Focus" event. If you have code in your Form_Load, perhaps you can move it to Form_Got_Focus.

What does the clearfix class do in css?

How floats work

When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.

float vs display:inline

Before the invention of display:inline-block, websites use float to set elements beside each other. float is preferred over display:inline since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.

Float problems

The main problem is that we're using float against its intended purpose.

Another is that while float allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>, the <div> will not impart 100px in height to the container.

Unlike position:absolute, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.

Clearfix to the rescue

What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear.

Examples

Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.

What you have

Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:

  • The first clearfix you have appends an invisible pseudo-element, which is styled clear:both, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.

  • The second one appends the style display:inline-block which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.

  • This was the reapplication of display:block due to IE-MAC rule above. This rule was "hidden" from IE-MAC.

All in all, these 3 rules keep the .clearfix working cross-browser, with old browsers in mind.

Replace multiple characters in one replace call

I don't know if how much this will help but I wanted to remove <b> and </b> from my string

so I used

mystring.replace('<b>',' ').replace('</b>','');

so basically if you want a limited number of character to be reduced and don't waste time this will be useful.

What is the default maximum heap size for Sun's JVM from Java SE 6?

With JDK, You can also use jinfo to connect to the JVM for the <PROCESS_ID> in question and get the value for MaxHeapSize:

jinfo -flag MaxHeapSize <PROCESS_ID>

Pandas How to filter a Series

From pandas version 0.18+ filtering a series can also be done as below

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

pd.Series(test).where(lambda x : x!=1).dropna()

Checkout: http://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements

jQuery Screen Resolution Height Adjustment

Another example for vertically and horizontally centered div or any object(s):

 var obj = $("#divID");
 var halfsc = $(window).height()/2;
 var halfh = $(obj).height() / 2; 

 var halfscrn = screen.width/2;
 var halfobj =$(obj).width() / 2; 

 var goRight =  halfscrn - halfobj ;
 var goBottom = halfsc - halfh;

 $(obj).css({marginLeft: goRight }).css({marginTop: goBottom });

JQuery / JavaScript - trigger button click from another button click event

jQuery("input.first").click(function(){
   jQuery("input.second").trigger("click");
   return false;
});

Launch Bootstrap Modal on page load

Heres a solution [without javascript initialization!]

I couldn't find an example without initializing your modal with javascript, $('#myModal').modal('show'), so heres a suggestion on how you could implement it without javascript delay on page load.

  1. Edit your modal container div with class and style:

<div class="modal in" id="MyModal" tabindex="-1" role="dialog" style="display: block; padding-right: 17px;">

  1. Edit your body with class and style:

    <body class="modal-open" style="padding-right:17px;">

  2. Add modal-backdrop div

    <div class="modal-backdrop in"></div>

  3. Add script

    $(document).ready(function() {
        $('body').css('padding-right', '0px');
        $('body').removeClass('modal-open');
        $('.modal-backdrop').remove();
    
        $('#MyModal').modal('show'); });
    

    What will happen is that the html for your modal will be loaded on page load without any javascript, (no delay). At this point you can't close the modal, so that is why we have the document.ready script, to load the modal properly when everything is loaded. We will actually remove the custom code and then initialize the modal, (again), with the .modal('show').

Parse (split) a string in C++ using string delimiter (standard C++)

strtok allows you to pass in multiple chars as delimiters. I bet if you passed in ">=" your example string would be split correctly (even though the > and = are counted as individual delimiters).

EDIT if you don't want to use c_str() to convert from string to char*, you can use substr and find_first_of to tokenize.

string token, mystring("scott>=tiger");
while(token != mystring){
  token = mystring.substr(0,mystring.find_first_of(">="));
  mystring = mystring.substr(mystring.find_first_of(">=") + 1);
  printf("%s ",token.c_str());
}

Equivalent of Math.Min & Math.Max for Dates?

// Two different dates
var date1 = new Date(2013, 05, 13); 
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate); 

http://jsfiddle.net/5CR37/

How to add button inside input

This is the cleanest way to do in bootstrap v3.

<div class="form-group">
    <div class="input-group">
        <input type="text" name="search" class="form-control" placeholder="Search">
        <span><button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button></span>
     </div>
</div>

A simple scenario using wait() and notify() in java

Example for wait() and notifyall() in Threading.

A synchronized static array list is used as resource and wait() method is called if the array list is empty. notify() method is invoked once a element is added for the array list.

public class PrinterResource extends Thread{

//resource
public static List<String> arrayList = new ArrayList<String>();

public void addElement(String a){
    //System.out.println("Add element method "+this.getName());
    synchronized (arrayList) {
        arrayList.add(a);
        arrayList.notifyAll();
    }
}

public void removeElement(){
    //System.out.println("Remove element method  "+this.getName());
    synchronized (arrayList) {
        if(arrayList.size() == 0){
            try {
                arrayList.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            arrayList.remove(0);
        }
    }
}

public void run(){
    System.out.println("Thread name -- "+this.getName());
    if(!this.getName().equalsIgnoreCase("p4")){
        this.removeElement();
    }
    this.addElement("threads");

}

public static void main(String[] args) {
    PrinterResource p1 = new PrinterResource();
    p1.setName("p1");
    p1.start();

    PrinterResource p2 = new PrinterResource();
    p2.setName("p2");
    p2.start();


    PrinterResource p3 = new PrinterResource();
    p3.setName("p3");
    p3.start();


    PrinterResource p4 = new PrinterResource();
    p4.setName("p4");
    p4.start();     

    try{
        p1.join();
        p2.join();
        p3.join();
        p4.join();
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    System.out.println("Final size of arraylist  "+arrayList.size());
   }
}

Sanitizing strings to make them URL and filename safe?

Solution #1: You have ability to install PHP extensions on server (hosting)

For transliteration of "almost every single language on the planet Earth" to ASCII characters.

  1. Install PHP Intl extension first. This is command for Debian (Ubuntu): sudo aptitude install php5-intl

  2. This is my fileName function (create test.php and paste there following code):

_x000D_
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<?php_x000D_
_x000D_
function pr($string) {_x000D_
  print '<hr>';_x000D_
  print '"' . fileName($string) . '"';_x000D_
  print '<br>';_x000D_
  print '"' . $string . '"';_x000D_
}_x000D_
_x000D_
function fileName($string) {_x000D_
  // remove html tags_x000D_
  $clean = strip_tags($string);_x000D_
  // transliterate_x000D_
  $clean = transliterator_transliterate('Any-Latin;Latin-ASCII;', $clean);_x000D_
  // remove non-number and non-letter characters_x000D_
  $clean = str_replace('--', '-', preg_replace('/[^a-z0-9-\_]/i', '', preg_replace(array(_x000D_
    '/\s/', _x000D_
    '/[^\w-\.\-]/'_x000D_
  ), array(_x000D_
    '_', _x000D_
    ''_x000D_
  ), $clean)));_x000D_
  // replace '-' for '_'_x000D_
  $clean = strtr($clean, array(_x000D_
    '-' => '_'_x000D_
  ));_x000D_
  // remove double '__'_x000D_
  $positionInString = stripos($clean, '__');_x000D_
  while ($positionInString !== false) {_x000D_
    $clean = str_replace('__', '_', $clean);_x000D_
    $positionInString = stripos($clean, '__');_x000D_
  }_x000D_
  // remove '_' from the end and beginning of the string_x000D_
  $clean = rtrim(ltrim($clean, '_'), '_');_x000D_
  // lowercase the string_x000D_
  return strtolower($clean);_x000D_
}_x000D_
pr('_replace(\'~&([a-z]{1,2})(ac134/56f4315981743 8765475[]lt7nl2ú5änú138yé73tž7ýlute|');_x000D_
pr(htmlspecialchars('<script>alert(\'hacked\')</script>'));_x000D_
pr('Álix----_Ãxel!?!?');_x000D_
pr('áéíóúÁÉÍÓÚ');_x000D_
pr('üÿÄËÏÖÜ.ŸåÅ');_x000D_
pr('nie4c a a§ônäääaš');_x000D_
pr('??? ??????');_x000D_
pr('???');_x000D_
pr('??? ??? ????');_x000D_
pr('???? ????????');_x000D_
pr('??? ???-????');_x000D_
pr('??? ??????');_x000D_
pr('Mao Tr?ch Ðông');_x000D_
pr('???');_x000D_
pr('???? ??????');_x000D_
?>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This line is core:

  // transliterate
  $clean = transliterator_transliterate('Any-Latin;Latin-ASCII;', $clean);

Answer based on this post.

Solution #2: You don't have ability to install PHP extensions on server (hosting)

enter image description here

Pretty good job is done in transliteration module for CMS Drupal. It supports almost every single language on the planet Earth. I suggest to check plugin repository if you want to have really complete solution sanitizing strings.

How to get Real IP from Visitor?

This is the most common technique I've seen:

function getUserIP() {
    if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
            $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($addr[0]);
        } else {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

Note that it does not guarantee it you will get always the correct user IP because there are many ways to hide it.

Get the last item in an array

You can add a last() function to the Array prototype.

Array.prototype.last = function () {
    return this[this.length - 1];
};

Javascript: How to pass a function with string parameters as a parameter to another function

One way would be to just escape the quotes properly:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
               'myfuncionOnOK(\'/myController2/myAction2\', 
                   \'myParameter2\');',
               'myfuncionOnCancel(\'/myController3/myAction3\', 
                   \'myParameter3\');');">

In this case, though, I think a better way to handle this would be to wrap the two handlers in anonymous functions:

<input type="button" value="click" id="mybtn"
       onclick="myfunction('/myController/myAction', 
                function() { myfuncionOnOK('/myController2/myAction2', 
                             'myParameter2'); },
                function() { myfuncionOnCancel('/myController3/myAction3', 
                             'myParameter3'); });">

And then, you could call them from within myfunction like this:

function myfunction(url, onOK, onCancel)
{
    // Do whatever myfunction would normally do...

    if (okClicked)
    {
        onOK();
    }

    if (cancelClicked)
    {
        onCancel();
    }
}

That's probably not what myfunction would actually look like, but you get the general idea. The point is, if you use anonymous functions, you have a lot more flexibility, and you keep your code a lot cleaner as well.

How to POST the data from a modal form of Bootstrap?

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action

Using jquery to get all checked checkboxes with a certain class name

If you need to get the value of all checked checkboxes as an array:

let myArray = (function() {
    let a = [];
    $(".checkboxes:checked").each(function() {
        a.push(this.value);
    });
    return a;
})()

iOS - Calling App Delegate method from ViewController

This is how I do it.

[[[UIApplication sharedApplication] delegate] performSelector:@selector(nameofMethod)];

Dont forget to import.

#import "AppDelegate.h"

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

Select 2 columns in one and combine them

if one of the column is number i have experienced the oracle will think '+' as sum operator instead concatenation.

eg:

select (id + name) as one from table 1; (id is numeric) 

throws invalid number exception

in such case you can || operator which is concatenation.

select (id || name) as one from table 1;

How do I find the location of my Python site-packages directory?

A side-note: The proposed solution (distutils.sysconfig.get_python_lib()) does not work when there is more than one site-packages directory (as recommended by this article). It will only return the main site-packages directory.

Alas, I have no better solution either. Python doesn't seem to keep track of site-packages directories, just the packages within them.

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

Please add a @Pipe/@Directive/@Component annotation. Error

Not a solution to the concrete example above, but there may be many reasons why you get this error message. I got it when I accidentally added a shared module to the module declarations list and not to imports.

In app.module.ts:

import { SharedModule } from './modules/shared/shared.module';

@NgModule({
  declarations: [
     // Should not have been added here...
  ],
  imports: [
     SharedModule
  ],

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

I got this error when unbeknownst to me, someone else was connected to the database in another SSMS session. After I signed them out the restore completed successfully.

"Press Any Key to Continue" function in C

Try this:-

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();

getch() is used to get a character from console but does not echo to the screen.

Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

Specify JDK for Maven to use

For Java 9 :

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <source>9</source>
                <target>9</target>
            </configuration>
        </plugin>
    </plugins>
</build>

How do I check for equality using Spark Dataframe without SQL Query?

Worked on Spark V2.*

import sqlContext.implicits._
df.filter($"state" === "TX")

if needs to be compared against a variable (e.g., var):

import sqlContext.implicits._
df.filter($"state" === var)

Note : import sqlContext.implicits._

Rename a dictionary key

You can use this OrderedDict recipe written by Raymond Hettinger and modify it to add a rename method, but this is going to be a O(N) in complexity:

def rename(self,key,new_key):
    ind = self._keys.index(key)  #get the index of old key, O(N) operation
    self._keys[ind] = new_key    #replace old key with new key in self._keys
    self[new_key] = self[key]    #add the new key, this is added at the end of self._keys
    self._keys.pop(-1)           #pop the last item in self._keys

Example:

dic = OrderedDict((("a",1),("b",2),("c",3)))
print dic
dic.rename("a","foo")
dic.rename("b","bar")
dic["d"] = 5
dic.rename("d","spam")
for k,v in  dic.items():
    print k,v

output:

OrderedDict({'a': 1, 'b': 2, 'c': 3})
foo 1
bar 2
c 3
spam 5

How do you change the text in the Titlebar in Windows Forms?

For changing the Title of a form at runtime we can code as below

public partial class FormMain : Form
{
    public FormMain()
    {
        InitializeComponent();
        this.Text = "This Is My Title";
    }
}

Multiplying Two Columns in SQL Server

select InitialPayment * MonthlyPayRate as SomeRandomCalculation from Payment

How do I automatically set the $DISPLAY variable for my current session?

Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.

What's causing my java.net.SocketException: Connection reset?

If you experience this trying to access Web services deployed on a Glassfish3 server, you might want to tune your http-thread-pool settings. That fixed SocketExceptions we had when many concurrent threads was calling the web service.

  1. Go to admin console
  2. Navigate to "Configurations"->"Server config"->"Thread pools"->"http-thread-pool".
  3. Change setting "Max Thread Pool Size" from 5 to 32
  4. Change setting "Min Thread Pool Size" from 2 to 16
  5. Restart Glassfish.

MySQL join with where clause

Try this

  SELECT *
    FROM categories
    LEFT JOIN user_category_subscriptions 
         ON user_category_subscriptions.category_id = categories.category_id 
   WHERE user_category_subscriptions.user_id = 1 
          or user_category_subscriptions.user_id is null

How do you remove Subversion control for a folder?

There's also a nice little open source tool called SVN Cleaner which adds three options to the Windows Explorer Context Menu:

  • Remove All .svn
  • Remove All But Root .svn
  • Remove Local Repo Files

TypeError: Cannot read property "0" from undefined

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.

What are the default color values for the Holo theme on Android 4.0?

If you want the default colors of Android ICS, you just have to go to your Android SDK and look for this path: platforms\android-15\data\res\values\colors.xml.

Here you go:

<!-- For holo theme -->
    <drawable name="screen_background_holo_light">#fff3f3f3</drawable>
    <drawable name="screen_background_holo_dark">#ff000000</drawable>
    <color name="background_holo_dark">#ff000000</color>
    <color name="background_holo_light">#fff3f3f3</color>
    <color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
    <color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
    <color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
    <color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
    <color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
    <color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
    <color name="dim_foreground_holo_dark">#bebebe</color>
    <color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
    <color name="dim_foreground_inverse_holo_dark">#323232</color>
    <color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
    <color name="hint_foreground_holo_dark">#808080</color>
    <color name="dim_foreground_holo_light">#323232</color>
    <color name="dim_foreground_disabled_holo_light">#80323232</color>
    <color name="dim_foreground_inverse_holo_light">#bebebe</color>
    <color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
    <color name="hint_foreground_holo_light">#808080</color>
    <color name="highlighted_text_holo_dark">#6633b5e5</color>
    <color name="highlighted_text_holo_light">#6633b5e5</color>
    <color name="link_text_holo_dark">#5c5cff</color>
    <color name="link_text_holo_light">#0000ee</color>

This for the Background:

<color name="background_holo_dark">#ff000000</color>
<color name="background_holo_light">#fff3f3f3</color>

You won't get the same colors if you look this up in Photoshop etc. because they are set up with Alpha values.

Update for API Level 19:

<resources>
    <drawable name="screen_background_light">#ffffffff</drawable>
    <drawable name="screen_background_dark">#ff000000</drawable>
    <drawable name="status_bar_closed_default_background">#ff000000</drawable>
    <drawable name="status_bar_opened_default_background">#ff000000</drawable>
    <drawable name="notification_item_background_color">#ff111111</drawable>
    <drawable name="notification_item_background_color_pressed">#ff454545</drawable>
    <drawable name="search_bar_default_color">#ff000000</drawable>
    <drawable name="safe_mode_background">#60000000</drawable>
    <!-- Background drawable that can be used for a transparent activity to
         be able to display a dark UI: this darkens its background to make
         a dark (default theme) UI more visible. -->
    <drawable name="screen_background_dark_transparent">#80000000</drawable>
    <!-- Background drawable that can be used for a transparent activity to
         be able to display a light UI: this lightens its background to make
         a light UI more visible. -->
    <drawable name="screen_background_light_transparent">#80ffffff</drawable>
    <color name="safe_mode_text">#80ffffff</color>
    <color name="white">#ffffffff</color>
    <color name="black">#ff000000</color>
    <color name="transparent">#00000000</color>
    <color name="background_dark">#ff000000</color>
    <color name="background_light">#ffffffff</color>
    <color name="bright_foreground_dark">@android:color/background_light</color>
    <color name="bright_foreground_light">@android:color/background_dark</color>
    <color name="bright_foreground_dark_disabled">#80ffffff</color>
    <color name="bright_foreground_light_disabled">#80000000</color>
    <color name="bright_foreground_dark_inverse">@android:color/bright_foreground_light</color>
    <color name="bright_foreground_light_inverse">@android:color/bright_foreground_dark</color>
    <color name="dim_foreground_dark">#bebebe</color>
    <color name="dim_foreground_dark_disabled">#80bebebe</color>
    <color name="dim_foreground_dark_inverse">#323232</color>
    <color name="dim_foreground_dark_inverse_disabled">#80323232</color>
    <color name="hint_foreground_dark">#808080</color>
    <color name="dim_foreground_light">#323232</color>
    <color name="dim_foreground_light_disabled">#80323232</color>
    <color name="dim_foreground_light_inverse">#bebebe</color>
    <color name="dim_foreground_light_inverse_disabled">#80bebebe</color>
    <color name="hint_foreground_light">#808080</color>
    <color name="highlighted_text_dark">#9983CC39</color>
    <color name="highlighted_text_light">#9983CC39</color>
    <color name="link_text_dark">#5c5cff</color>
    <color name="link_text_light">#0000ee</color>
    <color name="suggestion_highlight_text">#177bbd</color>

    <drawable name="stat_notify_sync_noanim">@drawable/stat_notify_sync_anim0</drawable>
    <drawable name="stat_sys_download_done">@drawable/stat_sys_download_done_static</drawable>
    <drawable name="stat_sys_upload_done">@drawable/stat_sys_upload_anim0</drawable>
    <drawable name="dialog_frame">@drawable/panel_background</drawable>
    <drawable name="alert_dark_frame">@drawable/popup_full_dark</drawable>
    <drawable name="alert_light_frame">@drawable/popup_full_bright</drawable>
    <drawable name="menu_frame">@drawable/menu_background</drawable>
    <drawable name="menu_full_frame">@drawable/menu_background_fill_parent_width</drawable>
    <drawable name="editbox_dropdown_dark_frame">@drawable/editbox_dropdown_background_dark</drawable>
    <drawable name="editbox_dropdown_light_frame">@drawable/editbox_dropdown_background</drawable>

    <drawable name="dialog_holo_dark_frame">@drawable/dialog_full_holo_dark</drawable>
    <drawable name="dialog_holo_light_frame">@drawable/dialog_full_holo_light</drawable>

    <drawable name="input_method_fullscreen_background">#fff9f9f9</drawable>
    <drawable name="input_method_fullscreen_background_holo">@drawable/screen_background_holo_dark</drawable>
    <color name="input_method_navigation_guard">#ff000000</color>

    <!-- For date picker widget -->
    <drawable name="selected_day_background">#ff0092f4</drawable>

    <!-- For settings framework -->
    <color name="lighter_gray">#ddd</color>
    <color name="darker_gray">#aaa</color>

    <!-- For security permissions -->
    <color name="perms_dangerous_grp_color">#33b5e5</color>
    <color name="perms_dangerous_perm_color">#33b5e5</color>
    <color name="shadow">#cc222222</color>
    <color name="perms_costs_money">#ffffbb33</color>

    <!-- For search-related UIs -->
    <color name="search_url_text_normal">#7fa87f</color>
    <color name="search_url_text_selected">@android:color/black</color>
    <color name="search_url_text_pressed">@android:color/black</color>
    <color name="search_widget_corpus_item_background">@android:color/lighter_gray</color>

    <!-- SlidingTab -->
    <color name="sliding_tab_text_color_active">@android:color/black</color>
    <color name="sliding_tab_text_color_shadow">@android:color/black</color>

    <!-- keyguard tab -->
    <color name="keyguard_text_color_normal">#ffffff</color>
    <color name="keyguard_text_color_unlock">#a7d84c</color>
    <color name="keyguard_text_color_soundoff">#ffffff</color>
    <color name="keyguard_text_color_soundon">#e69310</color>
    <color name="keyguard_text_color_decline">#fe0a5a</color>

    <!-- keyguard clock -->
    <color name="lockscreen_clock_background">#ffffffff</color>
    <color name="lockscreen_clock_foreground">#ffffffff</color>
    <color name="lockscreen_clock_am_pm">#ffffffff</color>
    <color name="lockscreen_owner_info">#ff9a9a9a</color>

    <!-- keyguard overscroll widget pager -->
    <color name="kg_multi_user_text_active">#ffffffff</color>
    <color name="kg_multi_user_text_inactive">#ff808080</color>
    <color name="kg_widget_pager_gradient">#ffffffff</color>

    <!-- FaceLock -->
    <color name="facelock_spotlight_mask">#CC000000</color>

    <!-- For holo theme -->
      <drawable name="screen_background_holo_light">#fff3f3f3</drawable>
      <drawable name="screen_background_holo_dark">#ff000000</drawable>
    <color name="background_holo_dark">#ff000000</color>
    <color name="background_holo_light">#fff3f3f3</color>
    <color name="bright_foreground_holo_dark">@android:color/background_holo_light</color>
    <color name="bright_foreground_holo_light">@android:color/background_holo_dark</color>
    <color name="bright_foreground_disabled_holo_dark">#ff4c4c4c</color>
    <color name="bright_foreground_disabled_holo_light">#ffb2b2b2</color>
    <color name="bright_foreground_inverse_holo_dark">@android:color/bright_foreground_holo_light</color>
    <color name="bright_foreground_inverse_holo_light">@android:color/bright_foreground_holo_dark</color>
    <color name="dim_foreground_holo_dark">#bebebe</color>
    <color name="dim_foreground_disabled_holo_dark">#80bebebe</color>
    <color name="dim_foreground_inverse_holo_dark">#323232</color>
    <color name="dim_foreground_inverse_disabled_holo_dark">#80323232</color>
    <color name="hint_foreground_holo_dark">#808080</color>
    <color name="dim_foreground_holo_light">#323232</color>
    <color name="dim_foreground_disabled_holo_light">#80323232</color>
    <color name="dim_foreground_inverse_holo_light">#bebebe</color>
    <color name="dim_foreground_inverse_disabled_holo_light">#80bebebe</color>
    <color name="hint_foreground_holo_light">#808080</color>
    <color name="highlighted_text_holo_dark">#6633b5e5</color>
    <color name="highlighted_text_holo_light">#6633b5e5</color>
    <color name="link_text_holo_dark">#5c5cff</color>
    <color name="link_text_holo_light">#0000ee</color>

    <!-- Group buttons -->
    <eat-comment />
    <color name="group_button_dialog_pressed_holo_dark">#46c5c1ff</color>
    <color name="group_button_dialog_focused_holo_dark">#2699cc00</color>

    <color name="group_button_dialog_pressed_holo_light">#ffffffff</color>
    <color name="group_button_dialog_focused_holo_light">#4699cc00</color>

    <!-- Highlight colors for the legacy themes -->
    <eat-comment />
    <color name="legacy_pressed_highlight">#fffeaa0c</color>
    <color name="legacy_selected_highlight">#fff17a0a</color>
    <color name="legacy_long_pressed_highlight">#ffffffff</color>

    <!-- General purpose colors for Holo-themed elements -->
    <eat-comment />

    <!-- A light Holo shade of blue -->
    <color name="holo_blue_light">#ff33b5e5</color>
    <!-- A light Holo shade of gray -->
    <color name="holo_gray_light">#33999999</color>
    <!-- A light Holo shade of green -->
    <color name="holo_green_light">#ff99cc00</color>
    <!-- A light Holo shade of red -->
    <color name="holo_red_light">#ffff4444</color>
    <!-- A dark Holo shade of blue -->
    <color name="holo_blue_dark">#ff0099cc</color>
    <!-- A dark Holo shade of green -->
    <color name="holo_green_dark">#ff669900</color>
    <!-- A dark Holo shade of red -->
    <color name="holo_red_dark">#ffcc0000</color>
    <!-- A Holo shade of purple -->
    <color name="holo_purple">#ffaa66cc</color>
    <!-- A light Holo shade of orange -->
    <color name="holo_orange_light">#ffffbb33</color>
    <!-- A dark Holo shade of orange -->
    <color name="holo_orange_dark">#ffff8800</color>
    <!-- A really bright Holo shade of blue -->
    <color name="holo_blue_bright">#ff00ddff</color>
    <!-- A really bright Holo shade of gray -->
    <color name="holo_gray_bright">#33CCCCCC</color>

    <drawable name="notification_template_icon_bg">#3333B5E5</drawable>
    <drawable name="notification_template_icon_low_bg">#0cffffff</drawable>

    <!-- Keyguard colors -->
    <color name="keyguard_avatar_frame_color">#ffffffff</color>
    <color name="keyguard_avatar_frame_shadow_color">#80000000</color>
    <color name="keyguard_avatar_nick_color">#ffffffff</color>
    <color name="keyguard_avatar_frame_pressed_color">#ff35b5e5</color>

    <color name="accessibility_focus_highlight">#80ffff00</color>
</resources>

Provide schema while reading csv file as a dataframe

Try the below code, you need not specify the schema. When you give inferSchema as true it should take it from your csv file.

val pagecount = sqlContext.read.format("csv")
  .option("delimiter"," ").option("quote","")
  .option("header", "true")
  .option("inferSchema", "true")
  .load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")

If you want to manually specify the schema, you can do it as below:

import org.apache.spark.sql.types._

val customSchema = StructType(Array(
  StructField("project", StringType, true),
  StructField("article", StringType, true),
  StructField("requests", IntegerType, true),
  StructField("bytes_served", DoubleType, true))
)

val pagecount = sqlContext.read.format("csv")
  .option("delimiter"," ").option("quote","")
  .option("header", "true")
  .schema(customSchema)
  .load("dbfs:/databricks-datasets/wikipedia-datasets/data-001/pagecounts/sample/pagecounts-20151124-170000")

Django datetime issues (default=datetime.now())

Instead of using datetime.now you should be really using from django.utils.timezone import now

Reference:

so go for something like this:

from django.utils.timezone import now


created_date = models.DateTimeField(default=now, editable=False)

Send File Attachment from Form Using phpMailer and PHP

This will work perfectly

    <form method='post' enctype="multipart/form-data">
    <input type='file' name='uploaded_file' id='uploaded_file' multiple='multiple' />
    <input type='submit' name='upload'/> 
    </form>

    <?php
           if(isset($_POST['upload']))
        {
             if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK)
                {
                     if (array_key_exists('uploaded_file', $_FILES))
                        { 
                            $mail->Subject = "My Subject";
                            $mail->Body = 'This is the body';
                            $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['uploaded_file']['name']));
                        if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $uploadfile))
                             $mail->addAttachment($uploadfile,$_FILES['uploaded_file']['name']); 
                            $mail->send();
                            echo 'Message has been sent';
                        }       
                else
                    echo "The file is not uploaded. please try again.";
                }
                else
                    echo "The file is not uploaded. please try again";
        }
    ?>

use localStorage across subdomains

this kind of solution causes many problems like this. for consistency and SEO considerations redirect on the main domain is the best solution.

do it redirection at the server level

How To Redirect www to Non-www with Nginx

https://www.digitalocean.com/community/tutorials/how-to-redirect-www-to-non-www-with-nginx-on-centos-7

or any other level like route 53 if are using

How do I execute .js files locally in my browser?

If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor

C# Remove object from list of objects

Simplest solution without using LINQ:

    Chunk toRemove = null;
    foreach (Chunk i in ChunkList)
    {
        if (i.UniqueID == ChunkID)
        {
            toRemove = i;
            break;
        }
    }
    if (toRemove != null) {
        ChunkList.Remove(toRemove);
    }

(If Chunk is a struct, then you can use Nullable<Chunk> to achieve this.)

The point of test %eax %eax

You are right, that test "and"s the two operands. But the result is discarded, the only thing that stays, and thats the important part, are the flags. They are set and thats the reason why the test instruction is used (and exist).

JE jumps not when equal (it has the meaning when the instruction before was a comparison), what it really does, it jumps when the ZF flag is set. And as it is one of the flags that is set by test, this instruction sequence (test x,x; je...) has the meaning that it is jumped when x is 0.

For questions like this (and for more details) I can just recommend a book about x86 instruction, e.g. even when it is really big, the Intel documentation is very good and precise.

How to apply filters to *ngFor?

I know its an old question, however, I thought it might be helpful to offer another solution.

equivalent of AngularJS of this

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

in Angular 2+ you cant use *ngFor and *ngIf on a same element, so it will be following:

<div *ngFor="let item of itemsList">
     <div *ngIf="conditon(item)">
     </div>
</div>

and if you can not use as internal container use ng-container instead. ng-container is useful when you want to conditionally append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

Left join only selected columns in R with the merge() function

Nothing elegant but this could be another satisfactory answer.

merge(x = DF1, y = DF2, by = "Client", all.x=TRUE)[,c("Client","LO","CON")]

This will be useful especially when you don't need the keys that were used to join the tables in your results.

How to create a GUID / UUID

let uniqueId = Date.now().toString(36) + Math.random().toString(36).substring(2);

_x000D_
_x000D_
document.getElementById("unique").innerHTML =
  Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
_x000D_
<div id="unique">
</div>
_x000D_
_x000D_
_x000D_

If ID's are generated more than 1 millisecond apart, they are 100% unique.

If two ID's are generated at shorter intervals, and assuming that the random method is truly random, this would generate ID's that are 99.99999999999999% likely to be globally unique (collision in 1 of 10^15)

You can increase this number by adding more digits, but to generate 100% unique ID's you will need to use a global counter.

if you need RFC compatibility, this formatting will pass as a valid version 4 GUID:

let u = Date.now().toString(16) + Math.random().toString(16) + '0'.repeat(16);
let guid = [u.substr(0,8), u.substr(8,4), '4000-8' + u.substr(13,3), u.substr(16,12)].join('-');

_x000D_
_x000D_
let u = Date.now().toString(16)+Math.random().toString(16)+'0'.repeat(16);
let guid = [u.substr(0,8), u.substr(8,4), '4000-8' + u.substr(13,3), u.substr(16,12)].join('-');
document.getElementById("unique").innerHTML = guid;
_x000D_
<div id="unique">
</div>
_x000D_
_x000D_
_x000D_

Edit: The above code follow the intention, but not the letter of the RFC. Among other discrepancies it's a few random digits short. (Add more random digits if you need it) The upside is that this it's really fast :) You can test validity of your GUID here

SQL-Server: The backup set holds a backup of a database other than the existing

instead of click on Restore Database click on Restore File and Filegroups..

thats work on my sql server

What is a callback URL in relation to an API?

I'll make this pretty simple for you. When a transaction is initiated, it goes under processing stage until it reaches the terminal stage. Once it reaches the terminal stage, the transaction status is posted by the payment gateway to the callback url which generally the merchants use as a reference to show the success/failure page to the user. Hope this helps?

Open a file with Notepad in C#

Use System.Diagnostics.Process to launch an instance of Notepad.exe.

req.body empty on posts

Make sure ["key" : "type", "value" : "json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"] is in your postman request headers

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

Correct your Code like this:

try
{ //method try starts  
  String sql = "INSERT into TblName (col1, col2) VALUES(?, ?)";
  pStmt = obj.getConnection().prepareStatement(sql);
  pStmt.setLong(1, subscriberID);
  for (String language : additionalLangs) {
    pStmt.setInt(2, Integer.parseInt(language));
    pStmt.execute();
  }
} //method/try ends
finally
{ //finally starts
   pStmt.close()
} 

Are you sure, that you're really closing your pStatements, connections and results?

To analyze open objects you can implment a delegator pattern, which wraps code around your statemant, connection and result objects. So you'll see, if an object will successfully closed.

An Example for: pStmt = obj.getConnection().prepareStatement(sql);

    class obj{ 

    public Connection getConnection(){
    return new ConnectionDelegator(...here create your connection object and put it into ...);

    } 
}


class ConnectionDelegator implements Connection{
    Connection delegates;

    public ConnectionDelegator(Connection con){
       this.delegates = con;
    }

    public Statement prepareStatement(String sql){
        return delegates.prepareStatement(sql);
    }

    public void close(){
        try{
           delegates.close();
        }finally{
           log.debug(delegates.toString() + " was closed");
        }
    }
}

How can I display a list view in an Android Alert Dialog?

This is too simple

final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};

AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);

builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int item) {
        if (items[item].equals("Take Photo")) {
            getCapturesProfilePicFromCamera();
        } else if (items[item].equals("Choose from Library")) {
            getProfilePicFromGallery();
        } else if (items[item].equals("Cancel")) {
            dialog.dismiss();
        }
    }
});
builder.show();

How can I join elements of an array in Bash?

Surprisingly my solution is not yet given :) This is the simplest way for me. It doesn't need a function:

IFS=, eval 'joined="${foo[*]}"'

Note: This solution was observed to work well in non-POSIX mode. In POSIX mode, the elements are still joined properly, but IFS=, becomes permanent.

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

How can I change IIS Express port for a site

Right click on your MVC Project. Go to Properties. Go to the Web tab.
Change the port number in the Project Url. Example. localhost:50645
Changing the bold number, 50645, to anything else will change the port the site runs under.
Press the Create Virtual Directory button to complete the process.

See also: http://msdn.microsoft.com/en-us/library/ms178109.ASPX

Image shows the web tab of an MVC Project enter image description here

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.

The finally implemented code started like this:

    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }

Listen to port via a Java socket

Try this piece of code, rather than ObjectInputStream.

BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ()));
while (true)
{
    String cominginText = "";
    try
    {
        cominginText = in.readLine ();
        System.out.println (cominginText);
    }
    catch (IOException e)
    {
        //error ("System: " + "Connection to server lost!");
        System.exit (1);
        break;
    }
}

Replace HTML page with contents retrieved via AJAX

I'm assuming you are using jQuery or something similar. If you are using jQuery, then the following should work:

<html>
<head>
   <script src="jquery.js" type="text/javascript"></script>
</head>
<body>
   content
</body>
<script type="text/javascript">
   $("body").load(url);
</script>
</html>

How to completely remove Python from a Windows machine?

Here's the steps (my non-computer-savvy girlfriend had to figure this one out for me, but unlike all the far more complicated processes one can find online, this one works)

  1. Open Control Panel
  2. Click "Uninstall a Program"
  3. Scroll down to Python and click uninstall for each version you don't want anymore.

This works on Windows 7 out of the box, no additional programs or scripts required.

OpenCV - DLL missing, but it's not?

This might be like resurrecting a dead horse. But just so it's out there, the reason why the answer to these types of questions to simply put dll's into the system32 folder is because that folder is in the os's system path.

It's actually best practice to provide the os with a path link.

With windows 10

  1. open up file explorer
  2. right click on "this pc" and select "properties"
  3. Now in the "Control Panel\System and Security\System" window that comes up, click on "Advanced System Settings" from the left hand panel.
  4. At the bottom of the next window, click on the "Environment Variables" button.
  5. On the next window, there are two panels, the top one is for modifying variables to the current user, and the bottom panel is for modifying variables to the system. On the bottom panel, find the variable "Path" and click it to select it, then click on the "edit" button.
  6. Here you can then create, edit, delete, or update the different paths for the system. For example, to add mingw32-make to the system so you can access that command via command prompt, click new, then paste in the path to the bin. Example path, "D:\Qt\Tools\mingw730_64\bin", no quotation marks nor additional whitespaces.
  7. Click ok on all the windows so that the changes are saved, then reboot your computer for the changes to be loaded.

Python constructors and __init__

There is no function overloading in Python, meaning that you can't have multiple functions with the same name but different arguments.

In your code example, you're not overloading __init__(). What happens is that the second definition rebinds the name __init__ to the new method, rendering the first method inaccessible.

As to your general question about constructors, Wikipedia is a good starting point. For Python-specific stuff, I highly recommend the Python docs.

Java Class that implements Map and keeps insertion order?

I don't know if it is opensource, but after a little googling, I found this implementation of Map using ArrayList. It seems to be pre-1.5 Java, so you might want to genericize it, which should be easy. Note that this implementation has O(N) access, but this shouldn't be a problem if you don't add hundreds of widgets to your JPanel, which you shouldn't anyway.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

Since there's no mention of how to compile a .c file together with a bunch of .o files, and this comment asks for it:

where's the main.c in this answer? :/ if file1.c is the main, how do you link it with other already compiled .o files? – Tom Brito Oct 12 '14 at 19:45

$ gcc main.c lib_obj1.o lib_obj2.o lib_objN.o -o x0rbin

Here, main.c is the C file with the main() function and the object files (*.o) are precompiled. GCC knows how to handle these together, and invokes the linker accordingly and results in a final executable, which in our case is x0rbin.

You will be able to use functions not defined in the main.c but using an extern reference to functions defined in the object files (*.o).

You can also link with .obj or other extensions if the object files have the correct format (such as COFF).

Find character position and update file name

If you're working with actual files (as opposed to some sort of string data), how about the following?

$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }

(or use _.+$ if you want to cut everything from the first underscore.)

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

Entity Framework Queryable async

Long story short,
IQueryable is designed to postpone RUN process and firstly build the expression in conjunction with other IQueryable expressions, and then interprets and runs the expression as a whole.
But ToList() method (or a few sort of methods like that), are ment to run the expression instantly "as is".
Your first method (GetAllUrlsAsync), will run imediately, because it is IQueryable followed by ToListAsync() method. hence it runs instantly (asynchronous), and returns a bunch of IEnumerables.
Meanwhile your second method (GetAllUrls), won't get run. Instead, it returns an expression and CALLER of this method is responsible to run the expression.

Round up value to nearest whole number in SQL UPDATE

Combine round and ceiling to get a proper round up.

select ceiling(round(984.375000), 0)) => 984

while

select round(984.375000, 0) => 984.000000

and

select ceil (984.375000) => 985

Pair/tuple data type in Go

There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

Nick's answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

These techniques have some properties of tuples, but no, they are not tuples.

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

Recently had the issue on Xcode 11 beta 2:

  1. Select your project on the left side panel
  2. Find the "Signing & Capabilities" tab for your target

If your target doesn't have the "Signing & Capabilities" tab (in my case only the test target had it), open the build settings for your project and click "All" instead of "Basic"/"Customised". Find signing under the settings and make sure you've got a Development team set up.

  1. Repeat the same step for your test target if needed

AngularJS : When to use service instead of factory

allernhwkim originally posted an answer on this question linking to his blog, however a moderator deleted it. It's the only post I've found which doesn't just tell you how to do the same thing with service, provider and factory, but also tells you what you can do with a provider that you can't with a factory, and with a factory that you can't with a service.

Directly from his blog:

app.service('CarService', function() {
   this.dealer="Bad";
    this.numCylinder = 4;
});

app.factory('CarFactory', function() {
    return function(numCylinder) {
      this.dealer="Bad";
        this.numCylinder = numCylinder
    };
});

app.provider('CarProvider', function() {
    this.dealerName = 'Bad';
    this.$get = function() {
        return function(numCylinder) {
            this.numCylinder = numCylinder;
            this.dealer = this.dealerName;
        }
    };
    this.setDealerName = function(str) {
      this.dealerName = str;
    }      
});

This shows how the CarService will always a produce a car with 4 cylinders, you can't change it for individual cars. Whereas CarFactory returns a function so you can do new CarFactory in your controller, passing in a number of cylinders specific to that car. You can't do new CarService because CarService is an object not a function.

The reason factories don't work like this:

app.factory('CarFactory', function(numCylinder) {
      this.dealer="Bad";
      this.numCylinder = numCylinder
});

And automatically return a function for you to instantiate, is because then you can't do this (add things to the prototype/etc):

app.factory('CarFactory', function() {
    function Car(numCylinder) {
        this.dealer="Bad";
        this.numCylinder = numCylinder
    };
    Car.prototype.breakCylinder = function() {
        this.numCylinder -= 1;
    };
    return Car;
});

See how it is literally a factory producing a car.

The conclusion from his blog is pretty good:

In conclusion,

---------------------------------------------------  
| Provider| Singleton| Instantiable | Configurable|
---------------------------------------------------  
| Factory | Yes      | Yes          | No          |
---------------------------------------------------  
| Service | Yes      | No           | No          |
---------------------------------------------------  
| Provider| Yes      | Yes          | Yes         |       
---------------------------------------------------  
  1. Use Service when you need just a simple object such as a Hash, for example {foo;1, bar:2} It’s easy to code, but you cannot instantiate it.

  2. Use Factory when you need to instantiate an object, i.e new Customer(), new Comment(), etc.

  3. Use Provider when you need to configure it. i.e. test url, QA url, production url.

If you find you're just returning an object in factory you should probably use service.

Don't do this:

app.factory('CarFactory', function() {
    return {
        numCylinder: 4
    };
});

Use service instead:

app.service('CarService', function() {
    this.numCylinder = 4;
});

count (non-blank) lines-of-code in bash

This command count number of non-blank lines.
cat fileName | grep -v ^$ | wc -l
grep -v ^$ regular expression function is ignore blank lines.

How to center the content inside a linear layout?

android:gravity handles the alignment of its children,

android:layout_gravity handles the alignment of itself.

So use one of these.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:gravity="center"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

or

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:baselineAligned="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_speak" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

        <ImageView
            android:id="@+id/imageButton_readtext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/image_bg"
            android:src="@drawable/ic_readtext" />
    </LinearLayout>

    ...
</LinearLayout>

How do I programmatically set device orientation in iOS 7?

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft]; [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

does work but you have to return shouldAutorotate with YES in your view controller

- (BOOL)shouldAutorotate
{
    return self.shouldAutoRotate;
}

But if you do that, your VC will autorotate if the user rotates the device... so I changed it to:

@property (nonatomic, assign) BOOL shouldAutoRotate;

- (BOOL)shouldAutorotate
{
    return self.shouldAutoRotate;
}

and I call

- (void)swithInterfaceOrientation:(UIInterfaceOrientation)orientation
{
    self.rootVC.shouldAutoRotate = YES;

    NSNumber *value = [NSNumber numberWithInt: orientation];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
}

to force a new orientation with a button-click. To set back shouldAutoRotate to NO, I added to my rootVC

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    self.shouldAutoRotate = NO;
}

PS: This workaround does work in all simulators too.

Git workflow and rebase vs merge questions

From what I have observed, git merge tends to keep the branches separate even after merging, whereas rebase then merge combines it into one single branch. The latter comes out much cleaner, whereas in the former, it would be easier to find out which commits belong to which branch even after merging.

Check if a string is palindrome

bool IsPalindrome(const char* psz)
{
    int i = 0;
    int j;

    if ((psz == NULL) || (psz[0] == '\0'))
    {
        return false;
    }

    j = strlen(psz) - 1;
    while (i < j)
    {
        if (psz[i] != psz[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;

}

// STL string version:

bool IsPalindrome(const string& str)
{
    if (str.empty())
        return false;

    int i = 0;                // first characters
    int j = str.length() - 1; // last character

    while (i < j)
    {
        if (str[i] != str[j])
        {
            return false;
        }
        i++;
        j--;
    }
    return true;
}

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

How to get All input of POST in Laravel

You can use it

$params = request()->all();

without

import Illuminate\Http\Request OR

use Illuminate\Support\Facades\Request OR other.

How to write a Unit Test?

Like @CoolBeans mentioned, take a look at jUnit. Here is a short tutorial to get you started as well with jUnit 4.x

Finally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: Test-Driven Development By Example.

C++ create string of text and variables

In C++11 you can use std::to_string:

std::string var = "sometext" + std::to_string(somevar) + "sometext" + std::to_string(somevar);  

Ruby: kind_of? vs. instance_of? vs. is_a?

I also wouldn't call two many (is_a? and kind_of? are aliases of the same method), but if you want to see more possibilities, turn your attention to #class method:

A = Class.new
B = Class.new A

a, b = A.new, B.new
b.class < A # true - means that b.class is a subclass of A
a.class < B # false - means that a.class is not a subclass of A
# Another possibility: Use #ancestors
b.class.ancestors.include? A # true - means that b.class has A among its ancestors
a.class.ancestors.include? B # false - means that B is not an ancestor of a.class

How do I check in JavaScript if a value exists at a certain array index?

Short and universal approach

If you want to check any array if it has falsy values (like false, undefined, null or empty strings) you can just use every() method like this:

array.every(function(element) {return !!element;}); // returns true or false

For example:

['23', null, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false

['23', '', 2, {key: 'value'}].every(function(element) {return !!element;}); // returns false

['23', true, 2, {key: 'value'}].every(function(element) {return !!element;}); // returns true

If you need to get a first index of falsy value, you can do it like this:

let falsyIndex; 

if(!['23', true, 2, null, {key: 'value'}].every(function(element, index) {falsyIndex = index; return !!element;})) {
  console.log(falsyIndex);
} // logs 3

If you just need to check a falsy value of an array for a given index you can just do it like this:

if (!!array[index]) {
  // array[index] is a correct value
}
else {
  // array[index] is a falsy value
}

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

pixels = np.array(pixels) in this line you reassign pixels. So, it may not a list anyhow. Though pixels is not a list it has no attributes append. Does it make sense?

How to fix "unable to write 'random state' " in openssl

The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:

set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024

More explanations: OpenSSL on Windows tries to save the 'random state' file in the following order:

  1. Path taken from RANDFILE environment variable
  2. If HOME environment variable is set then : ${HOME}\.rnd
  3. C:\.rnd

I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.

How to check if array element exists or not in javascript?

var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(ArrayIndexValue in demoArray){
   //Array index exists
}else{
   //Array Index does not Exists
}

fatal: could not read Username for 'https://github.com': No such file or directory

This is an issue with your stored credentials in the system credential cache. You probably have the config variable 'credential.helper' set to either wincred or winstore and it is failing to clear it. If you start the Control Panel and launch the Credential Manager applet then look for items in the generic credentials section labelled "git:https://github.com". If you delete these, then the will be recreated next time but the credential helper utility will ask you for your new credentials.

How to implement onBackPressed() in Fragments?

onBackPressed() cause Fragment to be detach from Activity.

According to @Sterling Diaz answer I think he is right. BUT some situation will be wrong. (ex. Rotate Screen)

So, I think we could detect whether isRemoving() to achieve goals.

You can write it at onDetach() or onDestroyView(). It is work.

@Override
public void onDetach() {
    super.onDetach();
    if(isRemoving()){
        // onBackPressed()
    }
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    if(isRemoving()){
        // onBackPressed()
    }
}

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Here a temporary workaround, If you are using room just upgrade to 1.1.0 or higher

implementation "android.arch.persistence.room:runtime:1.1.0"

it removes this warning for me.

Insert current date/time using now() in a field using MySQL/PHP

Just go to the column whenadded and change the default value to CURRENT_TIMESTAMP

Setting Margin Properties in code

Margin = new Thickness(0, 0, 0, 0);

how to set value of a input hidden field through javascript?

Your code for setting value for hidden input is correct. Here is the example. Maybe you have some conditions in your if statements that are not allowing your scripts to execute.

What's the difference between commit() and apply() in SharedPreferences

From javadoc:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself

How to prevent Browser cache for php site

try this

<?php

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

Enter

git log .

from the specific directory, it also gives commits in that directory.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

There is a very easy to use package available in PyPI that handles exactly that: django-related-admin. You can also see the code in GitHub.

Using this, what you want to achieve is as simple as:

class PersonAdmin(RelatedFieldAdmin):
    list_display = ['book__author',]

Both links contain full details of installation and usage so I won't paste them here in case they change.

Just as a side note, if you're already using something other than model.Admin (e.g. I was using SimpleHistoryAdmin instead), you can do this: class MyAdmin(SimpleHistoryAdmin, RelatedFieldAdmin).

How to POST JSON request using Apache HttpClient?

For Apache HttpClient 4.5 or newer version:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://targethost/login");
    String JSON_STRING="";
    HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

Note:

1 in order to make the code compile, both httpclient package and httpcore package should be imported.

2 try-catch block has been ommitted.

Reference: appache official guide

the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules

how to set image from url for imageView

if you are making a RecyclerView and using an adapter, what worked for me was:

@Override
public void onBindViewHolder(ADAPTERVIEWHOLDER holder, int position) {
    MODEL model = LIST.get(position);
    holder.TEXTVIEW.setText(service.getTitle());
    holder.TEXTVIEW.setText(service.getDesc());

    Context context = holder.IMAGEVIEW.getContext();
    Picasso.with(context).load(model.getImage()).into(holder.IMAGEVIEW);
}

Truncate with condition

No, TRUNCATE is all or nothing. You can do a DELETE FROM <table> WHERE <conditions> but this loses the speed advantages of TRUNCATE.

Why Is `Export Default Const` invalid?

You can also do something like this if you want to export default a const/let, instead of

const MyComponent = ({ attr1, attr2 }) => (<p>Now Export On other Line</p>);
export default MyComponent

You can do something like this, which I do not like personally.

let MyComponent;
export default MyComponent = ({ }) => (<p>Now Export On SameLine</p>);

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

Is it possible to convert char[] to char* in C?

Well, I'm not sure to understand your question...

In C, Char[] and Char* are the same thing.

Edit : thanks for this interesting link.

Put content in HttpResponseMessage object?

Apparently the new way to do it is detailed here:

http://aspnetwebstack.codeplex.com/discussions/350492

To quote Henrik,

HttpResponseMessage response = new HttpResponseMessage();

response.Content = new ObjectContent<T>(T, myFormatter, "application/some-format");

So basically, one has to create a ObjectContent type, which apparently can be returned as an HttpContent object.

How do I terminate a thread in C++11?

Tips of using OS-dependent function to terminate C++ thread:

  1. std::thread::native_handle() only can get the thread’s valid native handle type before calling join() or detach(). After that, native_handle() returns 0 - pthread_cancel() will coredump.

  2. To effectively call native thread termination function(e.g. pthread_cancel()), you need to save the native handle before calling std::thread::join() or std::thread::detach(). So that your native terminator always has a valid native handle to use.

More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I've gotten this error when running a scalar function using a table value, but the Select statement in my scalar function RETURN clause was missing the "FROM table" portion. :facepalms:

How to delete a record in Django models?

MyModel.objects.get(pk=1).delete()

this will raise exception if the object with specified primary key doesn't exist because at first it tries to retrieve the specified object.

MyModel.objects.filter(pk=1).delete()

this wont raise exception if the object with specified primary key doesn't exist and it directly produces the query

DELETE FROM my_models where id=1

How can I get a resource "Folder" from inside my jar File?

Try the following.
Make the resource path "<PathRelativeToThisClassFile>/<ResourceDirectory>" E.g. if your class path is com.abc.package.MyClass and your resoure files are within src/com/abc/package/resources/:

URL url = MyClass.class.getResource("resources/");
if (url == null) {
     // error - missing folder
} else {
    File dir = new File(url.toURI());
    for (File nextFile : dir.listFiles()) {
        // Do something with nextFile
    }
}

You can also use

URL url = MyClass.class.getResource("/com/abc/package/resources/");

What is a race condition?

A sort-of-canonical definition is "when two threads access the same location in memory at the same time, and at least one of the accesses is a write." In the situation the "reader" thread may get the old value or the new value, depending on which thread "wins the race." This is not always a bug—in fact, some really hairy low-level algorithms do this on purpose—but it should generally be avoided. @Steve Gury give's a good example of when it might be a problem.

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

How are echo and print different in PHP?

I think print() is slower than echo.

I like to use print() only for situations like:

 echo 'Doing some stuff... ';
 foo() and print("ok.\n") or print("error: " . getError() . ".\n");

How to count how many values per level in a given factor?

Or using the dplyr library:

library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>% 
  group_by(ID) %>%
  summarise(no_rows = length(ID))

Note the use of %>%, which is similar to the use of pipes in bash. Effectively, the code above pipes dat into group_by, and the result of that operation is piped into summarise.

The result is:

Source: local data frame [26 x 2]

   ID no_rows
1   a       2
2   b       3
3   c       3
4   d       3
5   e       2
6   f       4
7   g       6
8   h       1
9   i       6
10  j       5
11  k       6
12  l       4
13  m       7
14  n       2
15  o       2
16  p       2
17  q       5
18  r       4
19  s       5
20  t       3
21  u       8
22  v       4
23  w       5
24  x       4
25  y       3
26  z       1

See the dplyr introduction for some more context, and the documentation for details regarding the individual functions.

How to select option in drop down protractorjs e2e tests

I've improved a bit the solution written by PaulL. First of all I fixed the code to be compatible with the last Protractor API. And then I declare the function in 'onPrepare' section of a Protractor config file as a member of the browser instance, so it can be referenced form any e2e spec.

  onPrepare: function() {
    browser._selectDropdownbyNum = function (element, optionNum) {
      /* A helper function to select in a dropdown control an option
      * with specified number.
      */
      return element.all(by.tagName('option')).then(
        function(options) {
          options[optionNum].click();
        });
    };
  },

How can I check if string contains characters & whitespace, not just whitespace?

Just check the string against this regex:

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}

Load CSV data into MySQL in Python

If you do not have the pandas and sqlalchemy libraries, import using pip

pip install pandas
pip install sqlalchemy

We can use pandas and sqlalchemy to directly insert into the database

import csv
import pandas as pd
from sqlalchemy import create_engine, types

engine = create_engine('mysql://root:*Enter password here*@localhost/*Enter Databse name here*') # enter your password and database names here

df = pd.read_csv("Excel_file_name.csv",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('Table_name',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name

How can I convert uppercase letters to lowercase in Notepad++

I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.

Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.

Then I realized, that you can create macros easily, so I recorded one doing:

  • mark all
  • paste from clipboard
  • convert to upppercase
  • copy to clipboard

That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)

How do I migrate an SVN repository with history to a new Git repository?

Cleanly Migrate Your Subversion Repository To a Git Repository. First you have to create a file that maps your Subversion commit author names to Git commiters, say ~/authors.txt:

jmaddox = Jon Maddox <[email protected]>
bigpappa = Brian Biggs <[email protected]>

Then you can download the Subversion data into a Git repository:

mkdir repo && cd repo
git svn init http://subversion/repo --no-metadata
git config svn.authorsfile ~/authors.txt
git svn fetch

If you’re on a Mac, you can get git-svn from MacPorts by installing git-core +svn.

If your subversion repository is on the same machine as your desired git repository, then you can use this syntax for the init step, otherwise all the same:

git svn init file:///home/user/repoName --no-metadata

Ruby on Rails: how to render a string as HTML?

since you are translating, and picking out your wanted code from a person's crappy coded file, could you use content_tag, in combo with your regex's.

Stealing from the api docs, you could interpolate this translated code into a content_tag like:

<%= content_tag translated_tag_type.to_sym, :class => "#{translated_class}" do -%>
<%= translated_text %>
<% end -%>
# => <div class="strong">Hello world!</div>

Not knowing your code, this kind of thinking will make sure your translated code is too compliant.

Getting "Cannot call a class as a function" in my React Project

Two things you can check is,

class Slider extends React.Component {
    // Your React Code
}

Slider.propTypes = {
    // accessibility: PropTypes.bool,
}
  • Make sure that you extends React.Component
  • Use propTypes instead of prototype (as per IDE intellisense)

Displaying a Table in Django from Database

If you want to table do following steps:-

views.py:

def view_info(request):
    objs=Model_name.objects.all()
    ............
    return render(request,'template_name',{'objs':obj})

.html page

 {% for item in objs %}
    <tr> 
         <td>{{ item.field1 }}</td>
         <td>{{ item.field2 }}</td>
         <td>{{ item.field3 }}</td>
         <td>{{ item.field4 }}</td>
    </tr>
       {% endfor %}

jQuery: Change button text on click

try this, this javascript code to change text all time to click button.http://jsfiddle.net/V4u5X/2/

html code

<button class="SeeMore2">See More</button>

javascript

$('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
    });

Better way to call javascript function in a tag

I’m tempted to say that both are bad practices.

The use of onclick or javascript: should be dismissed in favor of listening to events from outside scripts, allowing for a better separation between markup and logic and thus leading to less repeated code.

Note also that external scripts get cached by the browser.

Have a look at this answer.

Some good ways of implementing cross-browser event listeners here.

Find CRLF in Notepad++

It appears that this is a FAQ, and the resolution offered is:

Simple search (Ctrl+H) without regexp

You can turn on View/Show End of Line or view/Show All, and select the now visible newline characters. Then when you start the command some characters matching the newline character will be pasted into the search field. Matches will be replaced by the replace string, unlike in regex mode.

Note 1: If you select them with the mouse, start just before them and drag to the start of the next line. Dragging to the end of the line won't work.

Note 2: You can't copy and paste them into the field yourself.

Advanced search (Ctrl+R) without regexp

Ctrl+M will insert something that matches newlines. They will be replaced by the replace string.

Storing money in a decimal column - what precision and scale?

If you are looking for a one-size-fits-all, I'd suggest DECIMAL(19, 4) is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; Decimal only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0.

The rule of thumb for storage of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old Currency type in the front end to DECIMAL(19, 4) type in the back end was that Currency exhibited bankers' rounding by nature, whereas DECIMAL(p, s) rounded by truncation.

An extra decimal place in storage for DECIMAL allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero).

Yes, DECIMAL(24, 8) sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) is required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :)

However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using DECIMAL(p, 6) for storage. Accountants generally seem to favour four decimal places.


PS Avoid SQL Server's MONEY data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See Aaron Bertrand's blog.


Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See Wikipedia; to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).

End of File (EOF) in C

That's a lot of questions.

  1. Why EOF is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"

  2. any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF is 0 when it's FALSE, meaning getchar() returned EOF.

  3. in order to emulate EOF when reading from stdin press Ctrl+D

Python-Requests close http connection

I think a more reliable way of closing a connection is to tell the sever explicitly to close it in a way compliant with HTTP specification:

HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example,

   Connection: close

in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent' (section 8.1) after the current request/response is complete.

The Connection: close header is added to the actual request:

r = requests.post(url=url, data=body, headers={'Connection':'close'})

Include an SVG (hosted on GitHub) in MarkDown

rawgit.com solves this problem nicely. For each request, it retrieves the appropriate document from GitHub and, crucially, serves it with the correct Content-Type header.

What is the best way to merge mp3 files?

I would use Winamp to do this. Create a playlist of files you want to merge into one, select Disk Writer output plugin, choose filename and you're done. The file you will get will be correct MP3 file and you can set bitrate etc.

Uncaught TypeError: Cannot assign to read only property

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

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

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

Is it possible to animate scrollTop with jQuery?

Like Kita mentioned there is a problem with multiple callbacks firing when you animate on both 'html' and 'body'. Instead of animating both and blocking subsequent callbacks I prefer to use some basic feature detection and only animate the scrollTop property of a single object.

The accepted answer on this other thread gives some insight as to which object's scrollTop property we should try to animate: pageYOffset Scrolling and Animation in IE8

// UPDATE: don't use this... see below
// only use 'body' for IE8 and below
var scrollTopElement = (window.pageYOffset != null) ? 'html' : 'body';

// only animate on one element so our callback only fires once!
$(scrollTopElement).animate({ 
        scrollTop: '400px' // vertical position on the page
    },
    500, // the duration of the animation 
    function() {       
        // callback goes here...
    })
});

UPDATE - - -

The above attempt at feature detection fails. Seems like there's not a one-line way of doing it as webkit type browsers pageYOffset property always returns zero when there's a doctype. Instead, I found a way to use a promise to do a single callback for every time the animation executes.

$('html, body')
    .animate({ scrollTop: 100 })
    .promise()
    .then(function(){
        // callback code here
    })
});

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

How to stop an app on Heroku?

If you are using eclipse plugin, double click on the app-name in My Heroku Applications. In Processes tab, press Scale Button. A small window will pop-up. Increase/decrease the count and just say OK.

Angular - POST uploaded file

First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:

var data : {
  name: string;
  file: File;
} = {
  name: "Name",
  file: inputValue.files[0]
  };

Then you send it to the Server with JSON.stringify(data)

let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);

How can I check if given int exists in array?

You almost never have to write your own loops in C++. Here, you can use std::find.

const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
  std::cout << "Found.\n"
}
else
{
  std::cout << "Not found.\n";
}

std::end requires C++11. Without it, you can find the number of elements in the array with:

const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);

...and the end with:

int* end = myArray + numElements;

Change div width live with jQuery

It is indeed possible to change a div elements' width in jQuery:

$("#div").css("width", "300px");

However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:

#div {
    width: 75%;
    /* You can also specify min/max widths */
    min-width: 300px;
    max-width: 960px;
}

This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.

Foreign Key to multiple tables

The first option in @Nathan Skerl's list is what was implemented in a project I once worked with, where a similar relationship was established between three tables. (One of them referenced two others, one at a time.)

So, the referencing table had two foreign key columns, and also it had a constraint to guarantee that exactly one table (not both, not neither) was referenced by a single row.

Here's how it could look when applied to your tables:

CREATE TABLE dbo.[Group]
(
    ID int NOT NULL CONSTRAINT PK_Group PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.[User]
(
    ID int NOT NULL CONSTRAINT PK_User PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL CONSTRAINT PK_Ticket PRIMARY KEY,
    OwnerGroup int NULL
      CONSTRAINT FK_Ticket_Group FOREIGN KEY REFERENCES dbo.[Group] (ID),
    OwnerUser int NULL
      CONSTRAINT FK_Ticket_User  FOREIGN KEY REFERENCES dbo.[User]  (ID),
    Subject varchar(50) NULL,
    CONSTRAINT CK_Ticket_GroupUser CHECK (
      CASE WHEN OwnerGroup IS NULL THEN 0 ELSE 1 END +
      CASE WHEN OwnerUser  IS NULL THEN 0 ELSE 1 END = 1
    )
);

As you can see, the Ticket table has two columns, OwnerGroup and OwnerUser, both of which are nullable foreign keys. (The respective columns in the other two tables are made primary keys accordingly.) The CK_Ticket_GroupUser check constraint ensures that only one of the two foreign key columns contains a reference (the other being NULL, that's why both have to be nullable).

(The primary key on Ticket.ID is not necessary for this particular implementation, but it definitely wouldn't harm to have one in a table like this.)

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

If you are using lodash, it could be as simple as this:

var arr = _.values(obj);

Sending mass email using PHP

Do not send email to 5,000 people using standard PHP tools. You'll get banned by most ISPs in seconds and never even know it. You should either use some mailing lists software or an Email Service Provider do to this.

The simplest way to resize an UIImage?

Here's a Swift version of Paul Lynch's answer

func imageWithImage(image:UIImage, scaledToSize newSize:CGSize) -> UIImage{
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
    let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

And as an extension:

public extension UIImage {
    func copy(newSize: CGSize, retina: Bool = true) -> UIImage? {
        // In next line, pass 0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
        // Pass 1 to force exact pixel size.
        UIGraphicsBeginImageContextWithOptions(
            /* size: */ newSize,
            /* opaque: */ false,
            /* scale: */ retina ? 0 : 1
        )
        defer { UIGraphicsEndImageContext() }

        self.draw(in: CGRect(origin: .zero, size: newSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

remove item from array using its name / value

You can delete by 1 or more properties:

//Delets an json object from array by given object properties. 
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); -> 
//removes all items        with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
    var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
    var deleted = 0;
    for (var i = 0, count = indexes.length; i < count; i++) {
        this.splice(indexes[i], 1);
        deleted++;
    }
    return deleted;
}

How can I convert String[] to ArrayList<String>

You can do the following:

String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList

Rebase feature branch onto another feature branch

Note: if you were on Branch1, you will with Git 2.0 (Q2 2014) be able to type:

git checkout Branch2
git rebase -

See commit 4f40740 by Brian Gesiak modocache:

rebase: allow "-" short-hand for the previous branch

Teach rebase the same shorthand as checkout and merge to name the branch to rebase the current branch on; that is, that "-" means "the branch we were previously on".

Avoid printStackTrace(); use a logger call instead

The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.

Filtering a list based on a list of booleans

With python 3 you can use list_a[filter] to get True values. To get False values use list_a[~filter]

Display XML content in HTML page

If you treat the content as text, not HTML, then DOM operations should cause the data to be properly encoded. Here's how you'd do it in jQuery:

$('#container').text(xmlString);

Here's how you'd do it with standard DOM methods:

document.getElementById('container')
        .appendChild(document.createTextNode(xmlString));

If you're placing the XML inside of HTML through server-side scripting, there are bound to be encoding functions to allow you to do that (if you add what your server-side technology is, we can give you specific examples of how you'd do it).

How can I upload files asynchronously?

Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload from root of your website, this code should work for you:

_x000D_
_x000D_
const asyncFileUpload = () => {
  const fileInput = document.getElementById("file");
  const file = fileInput.files[0];
  const uri = "/upload";
  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = e => {
    const percentage = e.loaded / e.total;
    console.log(percentage);
  };
  xhr.onreadystatechange = e => {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log("file uploaded");
    }
  };
  xhr.open("POST", uri, true);
  xhr.setRequestHeader("X-FileName", file.name);
  xhr.send(file);
}
_x000D_
<form>
  <span>File</span>
  <input type="file" id="file" name="file" size="10" />
  <input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
_x000D_
_x000D_
_x000D_

Also some further information about XMLHttpReques:

The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object. The XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();


Access Across Domains

For security reasons, modern browsers do not allow access across domains.

This means that both the web page and the XML file it tries to load, must be located on the same server.

The examples on W3Schools all open XML files located on the W3Schools domain.

If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.

For more details, you can continue reading here...

What's the difference between ng-model and ng-bind

tosh's answer gets to the heart of the question nicely. Here's some additional information....

Filters & Formatters

ng-bind and ng-model both have the concept of transforming data before outputting it for the user. To that end, ng-bind uses filters, while ng-model uses formatters.

filter (ng-bind)

With ng-bind, you can use a filter to transform your data. For example,

<div ng-bind="mystring | uppercase"></div>,

or more simply:

<div>{{mystring | uppercase}}</div>

Note that uppercase is a built-in angular filter, although you can also build your own filter.

formatter (ng-model)

To create an ng-model formatter, you create a directive that does require: 'ngModel', which allows that directive to gain access to ngModel's controller. For example:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

Then in your partial:

<input ngModel="mystring" my-model-formatter />

This is essentially the ng-model equivalent of what the uppercase filter is doing in the ng-bind example above.


Parsers

Now, what if you plan to allow the user to change the value of mystring? ng-bind only has one way binding, from model-->view. However, ng-model can bind from view-->model which means that you may allow the user to change the model's data, and using a parser you can format the user's data in a streamlined manner. Here's what that looks like:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

Play with a live plunker of the ng-model formatter/parser examples


What Else?

ng-model also has built-in validation. Simply modify your $parsers or $formatters function to call ngModel's controller.$setValidity(validationErrorKey, isValid) function.

Angular 1.3 has a new $validators array which you can use for validation instead of $parsers or $formatters.

Angular 1.3 also has getter/setter support for ngModel

How to avoid .pyc files?

You can set sys.dont_write_bytecode = True in your source, but that would have to be in the first python file loaded. If you execute python somefile.py then you will not get somefile.pyc.

When you install a utility using setup.py and entry_points= you will have set sys.dont_write_bytecode in the startup script. So you cannot rely on the "default" startup script generated by setuptools.

If you start Python with python file as argument yourself you can specify -B:

python -B somefile.py

somefile.pyc would not be generated anyway, but no .pyc files for other files imported too.

If you have some utility myutil and you cannot change that, it will not pass -B to the python interpreter. Just start it by setting the environment variable PYTHONDONTWRITEBYTECODE:

PYTHONDONTWRITEBYTECODE=x myutil

Replace a character at a specific index in a string?

As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.

There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).

public static void main(String[] args) {
    String text = "This is a test";
    try {
        //String.value is the array of char (char[])
        //that contains the text of the String
        Field valueField = String.class.getDeclaredField("value");
        //String.value is a private variable so it must be set as accessible 
        //to read and/or to modify its value
        valueField.setAccessible(true);
        //now we get the array the String instance is actually using
        char[] value = (char[])valueField.get(text);
        //The 13rd character is the "s" of the word "Test"
        value[12]='x';
        //We display the string which should be "This is a text"
        System.out.println(text);
    } catch (NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

Inserting a text where cursor is using Javascript/jquery

This jQuery plugin gives you a pre-made way of selection/caret manipulation.

Standardize data columns in R

I have to assume you meant to say that you wanted a mean of 0 and a standard deviation of 1. If your data is in a dataframe and all the columns are numeric you can simply call the scale function on the data to do what you want.

dat <- data.frame(x = rnorm(10, 30, .2), y = runif(10, 3, 5))
scaled.dat <- scale(dat)

# check that we get mean of 0 and sd of 1
colMeans(scaled.dat)  # faster version of apply(scaled.dat, 2, mean)
apply(scaled.dat, 2, sd)

Using built in functions is classy. Like this cat:

enter image description here

Plot different DataFrames in the same figure

If you a running Jupyter/Ipython notebook and having problems using;

ax = df1.plot()

df2.plot(ax=ax)

Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.

How to edit nginx.conf to increase file size upload

First Navigate the Path of php.ini

sudo vi /etc/php/7.2/fpm/php.ini

then, next change

upload_max_filesize = 999M
post_max_size = 999M

then ESC-->:wq

Now Lastly Paste this command,

sudo systemctl restart php7.2-fpm.service

you are done.

How can I override the OnBeforeUnload dialog and replace it with my own?

You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.

function onunload = (){
    window.open('logout.php');
}

This code called when user leave the page or close the active window and user logged out by 'logout.php'. The new window close immediately when logout php consist of code:

window.close();

Maven error :Perhaps you are running on a JRE rather than a JDK?

I faced the issue even though JAVA_HOME was pointing to JDK. It took time to figure out why it was throwing the exception.

The issue was I set JAVA_HOME as admin user on my window machine. You need to add JAVA_HOME environment variable pointing to right JDK to your user profile environment variable settings.

jQuery Ajax File Upload

If you want to upload file using AJAX here is code which you can use for file uploading.

$(document).ready(function() {
    var options = { 
                beforeSubmit:  showRequest,
        success:       showResponse,
        dataType: 'json' 
        }; 
    $('body').delegate('#image','change', function(){
        $('#upload').ajaxForm(options).submit();        
    }); 
});     
function showRequest(formData, jqForm, options) { 
    $("#validation-errors").hide().empty();
    $("#output").css('display','none');
    return true; 
} 
function showResponse(response, statusText, xhr, $form)  { 
    if(response.success == false)
    {
        var arr = response.errors;
        $.each(arr, function(index, value)
        {
            if (value.length != 0)
            {
                $("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
            }
        });
        $("#validation-errors").show();
    } else {
         $("#output").html("<img src='"+response.file+"' />");
         $("#output").css('display','block');
    }
}

Here is the HTML for Upload the file

<form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
    <input type="file" name="image" id="image" /> 
</form>

Firefox 'Cross-Origin Request Blocked' despite headers

I faced similar problem, and I think is valid to be registered how I fixed it:

I have a system built basically over Symfony 3. For self learn and performance purposes I decided to write few scripts using GoLang, also, an API with public access.

My Go API expects Json format params, and also return Json format response

To call those GoApi's I am using, most, $.ajax ( jQuery ) The first test was a deception: the (un)famous "Cross-Origin Request Blocked" pop up ! Then, I tried to set the "Access-Control-Allow-Origin: *" On apache conf, htaccess, php, javascript and anywhere I could find on google !

But, even, same frustrating error !!!

The Solution was simple : I had to make "POST" requests instead "GET" .

To achieve that I had to adjust both, GoLang and JavaScript to use GET ! Once it done, no more Cross-Origin Request Blocked for me !!!

Hope it Helps

PS:

I am using apache and Vhost, on Directory Block I have

  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

Remember : "*" means that you will accept requests from anyone !!! (Which may be a security lack ) In my case it is ok, because it will be an public API

PS2: My Headers

Response headers

Access-Control-Allow-Credentials    true
Access-Control-Allow-Headers    Authorization
Access-Control-Allow-Methods    GET, POST, PUT
Access-Control-Allow-Origin http://localhost
Content-Length  164
Content-Type    application/json; charset=UTF-8
Date    Tue, 07 May 2019 20:33:52 GMT

Request headers (469 B)

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Content-Length  81
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    localhost:9003
Origin  http://localhost
Referer http://localhost/fibootkt/MY_app_dev.php/MyTest/GoAPI
User-Agent  Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/66.0

IllegalArgumentException or NullPointerException for a null parameter?

You should throw an IllegalArgumentException, as it will make it obvious to the programmer that he has done something invalid. Developers are so used to seeing NPE thrown by the VM, that any programmer would not immediately realize his error, and would start looking around randomly, or worse, blame your code for being 'buggy'.

Android Studio cannot resolve R in imported project?

just clean project and then sync your project with gradle file.

form confirm before submit

var r = confirm('Want to delete ?'); 

if (r == true) { 
    $('#admin-category-destroy').submit(); 
}

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

Setting multiple attributes for an element at once with JavaScript

You might be able to use Object.assign(...) to apply your properties to the created element. See comments for additional details.

Keep in mind that height and width attributes are defined in pixels, not percents. You'll have to use CSS to make it fluid.

_x000D_
_x000D_
var elem = document.createElement('img')_x000D_
Object.assign(elem, {_x000D_
  className: 'my-image-class',_x000D_
  src: 'https://dummyimage.com/320x240/ccc/fff.jpg',_x000D_
  height: 120, // pixels_x000D_
  width: 160, // pixels_x000D_
  onclick: function () {_x000D_
    alert('Clicked!')_x000D_
  }_x000D_
})_x000D_
document.body.appendChild(elem)_x000D_
_x000D_
// One-liner:_x000D_
// document.body.appendChild(Object.assign(document.createElement(...), {...}))
_x000D_
.my-image-class {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  border: solid 5px transparent;_x000D_
  box-sizing: border-box_x000D_
}_x000D_
_x000D_
.my-image-class:hover {_x000D_
  cursor: pointer;_x000D_
  border-color: red_x000D_
}_x000D_
_x000D_
body { margin:0 }
_x000D_
_x000D_
_x000D_

Verify host key with pysftp

I've implemented auto_add_key in my pysftp github fork.

auto_add_key will add the key to known_hosts if auto_add_key=True
Once a key is present for a host in known_hosts this key will be checked.

Please reffer Martin Prikryl -> answer about security concerns.

Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

import pysftp as sftp

def push_file_to_server():
    s = sftp.Connection(host='138.99.99.129', username='root', password='pass', auto_add_key=True)
    local_path = "testme.txt"
    remote_path = "/home/testme.txt"

    s.put(local_path, remote_path)
    s.close()

push_file_to_server()

Note: Why using context manager

import pysftp
with pysftp.Connection(host, username="whatever", password="whatever", auto_add_key=True) as sftp:
    #do your stuff here
#connection closed

Redirect from an HTML page

I use a script which redirects the user from index.html to relative url of Login Page

<html>
  <head>
    <title>index.html</title>
  </head>
  <body onload="document.getElementById('lnkhome').click();">
    <a href="/Pages/Login.aspx" id="lnkhome">Go to Login Page<a>
  </body>
</html>

How to call loading function with React useEffect only once

TL;DR

useEffect(yourCallback, []) - will trigger the callback only after the first render.

Detailed explanation

useEffect runs by default after every render of the component (thus causing an effect).

When placing useEffect in your component you tell React you want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.

If you pass only a callback - the callback will run after each render.

If passing a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. for example when placing useEffect(() => console.log('hello'), [someVar, someOtherVar]) - the callback will run after the first render and after any render that one of someVar or someOtherVar are changed.

By passing the second argument an empty array, React will compare after each render the array and will see nothing was changed, thus calling the callback only after the first render.

HTML Agility pack - parsing tables

In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:

    List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
                                       from row in table?.SelectNodes(HtmlBody.TR)
                                       let rows = row.SelectSingleNode(HtmlBody.TR)
                                       where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
                                       select new TableRow
                                       {
                                           Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
                                           Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
                                       }  

TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:

_x000D_
_x000D_
<tr>_x000D_
    <td width="28%">&nbsp;</td>_x000D_
</tr>
_x000D_
_x000D_
_x000D_

which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.

How can I find matching values in two arrays?

Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.

?Array.prototype.diff = function(arr2) {
    var ret = [];
    for(var i in this) {   
        if(arr2.indexOf(this[i]) > -1){
            ret.push(this[i]);
        }
    }
    return ret;
};

? My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:

Array.prototype.diff = function(arr2) {
    var ret = [];
    this.sort();
    arr2.sort();
    for(var i = 0; i < this.length; i += 1) {
        if(arr2.indexOf(this[i]) > -1){
            ret.push(this[i]);
        }
    }
    return ret;
};

Usage would look like:

var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

console.log(array1.diff(array2));

If you have an issue/problem with extending the Array prototype, you could easily change this to a function.

var diff = function(arr, arr2) {

And you'd change anywhere where the func originally said this to arr2.

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

You need to handle two scenarios:

  1. When you're pushing a new view onto the stack
  2. When you're showing the root view controller

If you just need a base class you can use, here's a Swift 3 version:

import UIKit

final class SwipeNavigationController: UINavigationController {
    
    // MARK: - Lifecycle
    
    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)

         delegate = self
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) { 
        super.init(coder: aDecoder) 

        delegate = self 
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // This needs to be in here, not in init
        interactivePopGestureRecognizer?.delegate = self
    }
    
    deinit {
        delegate = nil
        interactivePopGestureRecognizer?.delegate = nil
    }
    
    // MARK: - Overrides
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        duringPushAnimation = true
        
        super.pushViewController(viewController, animated: animated)
    }
    
    // MARK: - Private Properties
    
    fileprivate var duringPushAnimation = false

}

// MARK: - UINavigationControllerDelegate

extension SwipeNavigationController: UINavigationControllerDelegate {
    
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        guard let swipeNavigationController = navigationController as? SwipeNavigationController else { return }
        
        swipeNavigationController.duringPushAnimation = false
    }
    
}

// MARK: - UIGestureRecognizerDelegate

extension SwipeNavigationController: UIGestureRecognizerDelegate {
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        guard gestureRecognizer == interactivePopGestureRecognizer else {
            return true // default value
        }
        
        // Disable pop gesture in two situations:
        // 1) when the pop animation is in progress
        // 2) when user swipes quickly a couple of times and animations don't have time to be performed
        return viewControllers.count > 1 && duringPushAnimation == false
    }
}

If you end up needing to act as a UINavigationControllerDelegate in another class, you can write a delegate forwarder similar to this answer.

Adapted from source in Objective-C: https://github.com/fastred/AHKNavigationController

Git push error pre-receive hook declined

In my case, my team lead to created a repo(repo was empty) and assign me as developer so when I pushed to the code directly to master the error I was facing ! [remote rejected] master -> master (pre-receive hook declined) So how it was fixed that he assigned to me as maintainer so I was able to push the code directly to the master.

GCC dump preprocessor defines

Late answer - I found the other answers useful - and wanted to add a bit extra.


How do I dump preprocessor macros coming from a particular header file?

echo "#include <sys/socket.h>" | gcc -E -dM -

or (thanks to @mymedia for the suggestion):

gcc -E -dM -include sys/socket.h - < /dev/null

In particular, I wanted to see what SOMAXCONN was defined to on my system. I know I could just open up the standard header file, but sometimes I have to search around a bit to find the header file locations. Instead I can just use this one-liner:

$ gcc -E -dM -include sys/socket.h - < /dev/null | grep SOMAXCONN
#define SOMAXCONN 128
$ 

Fragment MyFragment not attached to Activity

I've faced two different scenarios here:

1) When I want the asynchronous task to finish anyway: imagine my onPostExecute does store data received and then call a listener to update views so, to be more efficient, I want the task to finish anyway so I have the data ready when user cames back. In this case I usually do this:

@Override
protected void onPostExecute(void result) {
    // do whatever you do to save data
    if (this.getView() != null) {
        // update views
    }
}

2) When I want the asynchronous task only to finish when views can be updated: the case you're proposing here, the task only updates the views, no data storage needed, so it has no clue for the task to finish if views are not longer being showed. I do this:

@Override
protected void onStop() {
    // notice here that I keep a reference to the task being executed as a class member:
    if (this.myTask != null && this.myTask.getStatus() == Status.RUNNING) this.myTask.cancel(true);
    super.onStop();
}

I've found no problem with this, although I also use a (maybe) more complex way that includes launching tasks from the activity instead of the fragments.

Wish this helps someone! :)

Get the last three chars from any string - Java

public String getLastThree(String myString) {
    if(myString.length() > 3)
        return myString.substring(myString.length()-3);
    else
        return myString;
}

Insert picture/table in R Markdown

When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png) can be problematic if PDF output is required.

The knitr function include_graphics knitr::include_graphics('/path/to/image.png') is a more portable alternative that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.

Should URL be case sensitive?

The case sensitivity of URLs, in general (along with whether they are same or not if they are in different case), needs to be looked at from the following perspectives:

  • Resource Equivalence
  • URL Comparison

From the perspective of resource equivalence it is generally not possible to say two URLs differing by any case (lower case, upper case, sentence case, camel case ... any combination of case) are different from each other unless the resource is retrieved from both the URLs, which in many cases is not practical (RFC 3986, section 6.1, para 1). Therefore where the resource cannot be retrieved, the comparison perspective is used.

However, in case where it is possible to retrieve the resource, the matter gets more (as expected) complicated. By the provisions of RFC 3986, Section 3.3, para 5, as highlighted below

Aside from dot-segments in hierarchical paths, a path segment is considered opaque by the generic syntax

it would appear that no assumption can be made for the rest of a URI/URL beyond it's scheme and authority from generic syntax (inclusive of the sensitivity question).

For scheme and host part of the authority, however, the specification does (charitably) state them to be case insensitive. Refer RFC 3986, section 3.1, para 1 and RFC 3986, section 6.2.2.1, para 2.

Having exhausted this line of inquiry one should look at the comparison perspective to determine whether URI/URLs are to be case sensitive or not.

The first hint to that direction emerges through perusal of the section 6.2.2.1 (above)

The other generic syntax components are assumed to be case-sensitive unless specifically defined otherwise by the scheme

Which is further buoyed by considering RFC 2616, section 3.2.3

When comparing two URIs to decide if they match or not, a client SHOULD use a case-sensitive octet-by-octet comparison of the entire URIs

Then, finally, is the enquiry settled and URLs are case sensitive ... (heh!), not quite, the operative words are 'opaque', 'client' and 'comparing'.

Beyond it's syntax, The above RFC don't mention anything about the actual interpretation of the path and query except that it is 'opaque' and it only specifies how (with a SHOULD and not a MUST) a 'client' may 'compare' the URL. It mentions nothing regarding how a server (SHOULD, let alone MUST) interpret the rest of the URL beyond scheme/authority.

Therefore the server has all the latitude to interpret an URL as they please, which they do as highlighted by earlier posts by others.

String representation of an Enum

Very simple solution to this with .Net 4.0 and above. No other code is needed.

public enum MyStatus
{
    Active = 1,
    Archived = 2
}

To get the string about just use:

MyStatus.Active.ToString("f");

or

MyStatus.Archived.ToString("f");`

The value will be "Active" or "Archived".

To see the different string formats (the "f" from above) when calling Enum.ToString see this Enumeration Format Strings page

Passing data between different controller action methods

If you need to pass data from one controller to another you must pass data by route values.Because both are different request.if you send data from one page to another then you have to user query string(same as route values).

But you can do one trick :

In your calling action call the called action as a simple method :

public class ServerController : Controller
{
 [HttpPost]
 public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
 {
      XDocument updatedResultsDocument = myService.UpdateApplicationPools();
      ApplicationPoolController pool=new ApplicationPoolController(); //make an object of ApplicationPoolController class.

      return pool.UpdateConfirmation(updatedResultsDocument); // call the ActionMethod you want as a simple method and pass the model as an argument.
      // Redirect to ApplicationPool controller and pass
      // updatedResultsDocument to be used in UpdateConfirmation action method
 }
}

How can a query multiply 2 cell for each row MySQL?

I'm assuming this should work. This will actually put it in the column in your database

UPDATE yourTable yt SET yt.Total = (yt.Pieces * yt.Price)

If you want to retrieve the 2 values from the database and put your multiplication in the third column of the result only, then

SELECT yt.Pieces, yt.Price, (yt.Pieces * yt.Price) as 'Total' FROM yourTable yt

will be your friend

How to run C program on Mac OS X using Terminal?

Working in 2019 By default, you can compile your name.c using the terminal

 cc name.c

and if you need to run just write

 ./name.out

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

How to remove item from a python list in a loop?

hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:

x[:] = [value for value in x if len(value)==2]

However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).

glglgl's answer suffers from O(n²) complexity, because list.remove is O(n).

Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del keywork to remove by index:

to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
    del x[index]

Now del x[i] is also O(n) because you need to copy all elements after index i (a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.

[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress which was introduced in python 2.7:

from itertools import compress

selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
    x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:]  # trim the end of the list

Automatic prune with Git fetch or pull

Since git 1.8.5 (Q4 2013):

"git fetch" (hence "git pull" as well) learned to check "fetch.prune" and "remote.*.prune" configuration variables and to behave as if the "--prune" command line option was given.

That means that, if you set remote.origin.prune to true:

git config remote.origin.prune true

Any git fetch or git pull will automatically prune.

Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename misbehave.
See "How do I rename a git remote?".


See more at commit 737c5a9:

Without "git fetch --prune", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune".

To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "fetch.prune" and "remote.<name>.prune":

  • "fetch.prune" allows to enable prune for all fetch operations.
  • "remote.<name>.prune" allows to change the behaviour per remote.

The latter will naturally override the former, and the --[no-]prune option from the command line will override the configured default.

Since --prune is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.

Vuejs: Event on route change

Just incase if anyone is looking for how to do it in typescript here is the solution

   @Watch('$route', { immediate: true, deep: true })
   onUrlChange(newVal: Route) {
      // Some action
    }

And yes as mentioned by @Coops below, please do not forget to include

import { Watch } from 'vue-property-decorator';

Edit: Alcalyn made a very good point of using Route type instead of using any

import { Watch } from 'vue-property-decorator';    
import { Route } from 'vue-router';

SyntaxError: cannot assign to operator

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)

Where are include files stored - Ubuntu Linux, GCC

The \#include files of gcc are stored in /usr/include . The standard include files of g++ are stored in /usr/include/c++.

Spring Data JPA findOne() change to Optional how to use this?

I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.

@Repository 
public interface RequestRepository extends CrudRepository<Request, Integer> {

    default Request findByIdOrError(Integer id) {
        return findById(id).orElseThrow(EntityNotFoundException::new);
    } 
}

Create list of single item repeated N times

Create List of Single Item Repeated n Times in Python

Depending on your use-case, you want to use different techniques with different semantics.

Multiply a list for Immutable items

For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:

[e] * 4

Note that this is usually only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.

schema = ['string'] * len(columns)

Multiply the list where we want the same item repeated

Multiplying a list gives us the same elements over and over. The need for this is rare:

[iter(iterable)] * 4

This is sometimes used to map an iterable into a list of lists:

>>> iterable = range(12)
>>> a_list = [iter(iterable)] * 4
>>> [[next(l) for l in a_list] for i in range(3)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

We can see that a_list contains the same range iterator four times:

>>> a_list
[<range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>]

Mutable items

I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.

Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:

list_of_lists = [[] for _ in columns]

The underscore is simply a throwaway variable name in this context.

If you only have the number, that would be:

list_of_lists = [[] for _ in range(4)]

The _ is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.


Caveats for using the immutable method with mutable items:

Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:

foo = [[]] * 4
foo[0].append('x')

foo now returns:

[['x'], ['x'], ['x'], ['x']]

But with immutable objects, you can make it work because you change the reference, not the object:

>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]

>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]

But again, mutable objects are no good for this, because in-place operations change the object, not the reference:

l = [set()] * 4
>>> l[0] |= set('abc')    
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]

How to solve a pair of nonlinear equations using Python?

Short answer: use fsolve

As mentioned in other answers the simplest solution to the particular problem you have posed is to use something like fsolve:

from scipy.optimize import fsolve
from math import exp

def equations(vars):
    x, y = vars
    eq1 = x+y**2-4
    eq2 = exp(x) + x*y - 3
    return [eq1, eq2]

x, y =  fsolve(equations, (1, 1))

print(x, y)

Output:

0.6203445234801195 1.8383839306750887

Analytic solutions?

You say how to "solve" but there are different kinds of solution. Since you mention SymPy I should point out the biggest difference between what this could mean which is between analytic and numeric solutions. The particular example you have given is one that does not have an (easy) analytic solution but other systems of nonlinear equations do. When there are readily available analytic solutions SymPY can often find them for you:

from sympy import *

x, y = symbols('x, y')
eq1 = Eq(x+y**2, 4)
eq2 = Eq(x**2 + y, 4)

sol = solve([eq1, eq2], [x, y])

Output:

?? ?  5   v17? ?3   v17?    v17   1?  ? ?  5   v17? ?3   v17?    1   v17?  ? ?  3   v13? ?v13   5?  1   v13?  ? ?5   v13? ?  v13   3?  1   v13??
??-?- - - ---?·?- - ---?, - --- - -?, ?-?- - + ---?·?- + ---?, - - + ---?, ?-?- - + ---?·?--- + -?, - + ---?, ?-?- - ---?·?- --- - -?, - - ---??
?? ?  2    2 ? ?2    2 ?     2    2?  ? ?  2    2 ? ?2    2 ?    2    2 ?  ? ?  2    2 ? ? 2    2?  2    2 ?  ? ?2    2 ? ?   2    2?  2    2 ??

Note that in this example SymPy finds all solutions and does not need to be given an initial estimate.

You can evaluate these solutions numerically with evalf:

soln = [tuple(v.evalf() for v in s) for s in sol]
[(-2.56155281280883, -2.56155281280883), (1.56155281280883, 1.56155281280883), (-1.30277563773199, 2.30277563773199), (2.30277563773199, -1.30277563773199)]

Precision of numeric solutions

However most systems of nonlinear equations will not have a suitable analytic solution so using SymPy as above is great when it works but not generally applicable. That is why we end up looking for numeric solutions even though with numeric solutions: 1) We have no guarantee that we have found all solutions or the "right" solution when there are many. 2) We have to provide an initial guess which isn't always easy.

Having accepted that we want numeric solutions something like fsolve will normally do all you need. For this kind of problem SymPy will probably be much slower but it can offer something else which is finding the (numeric) solutions more precisely:

from sympy import *

x, y = symbols('x, y')
nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1])
?0.620344523485226?
?                 ?
?1.83838393066159 ?

With greater precision:

nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1], prec=50)
?0.62034452348522585617392716579154399314071550594401?
?                                                    ?
? 1.838383930661594459049793153371142549403114879699 ?