Programs & Examples On #Invokeandwait

A method provided by the SwingUtilities class in Java that executes synchronously code on the AWT event dispatching thread in order to correctly manipulate UI elements.

Java Error: "Your security settings have blocked a local application from running"

I faced the same issue today, and I was able to fix the issue by changing the security settings on the Java Control Panel from HIGH to MEDIUM.

Well, setting the Java Security Setting to MEDIUM permanently is not really recommended as this will allow potentialy malicious software to run on your system and not be blocked. So I suggest after running your applet you may want to change back the setting to HIGH.

Location of the Java Control Panel

Change the setting of the Control Panel

How can I find a specific file from a Linux terminal?

Solution: Use unix command find

The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.

  • You can make the find action be more efficient and smart by controlling it with regular expressions queries, file types, size thresholds, depths dimensions in subtree, groups, ownership, timestamps , modification/creation date and more.
  • In addition you can use operators and combine find requests such as or/not/and etc...

The Traditional Formula would be :

find <path> -flag <valueOfFlag>

Easy Examples

1.Find by Name - Find all package.json from my current location subtree hierarchy.

find . -name "package.json"

2.Find by Name and Type - find all node_modules directories from ALL file system (starting from root hierarchy )

sudo find / -name "node_modules" -type d

Complex Examples:

More Useful examples which can demonstrate the power of flag options and operators:

3.Regex and File Type - Find all javascript controllers variation names (using regex) javascript Files only in my app location.

find /user/dev/app -name "*contoller-*\.js" -type f

-type f means file -name related to regular expression to any variation of controller string and dash with .js at the end

4.Depth - Find all routes patterns directories in app directory no more than 3 dimensions ( app/../../.. only and no more deeper)

find app -name "*route*" -type d  -maxdepth 3

-type d means directory -name related to regular expression to any variation of route string -maxdepth making the finder focusing on 3 subtree depth and no more <yourSearchlocation>/depth1/depth2/depth3)

5.File Size , Ownership and OR Operator - Find all files with names 'sample' or 'test' under ownership of root user that greater than 1 Mega and less than 5 Mega.

find . \( -name "test" -or -name "sample" \)  -user root -size +1M -size -5M

-size threshold representing the range between more than (+) and less than (-) -user representing the file owner -or operator filters query for both regex matches

6.Empty Files - find all empty directories in file system

find / -type d -empty

7.Time Access, Modification and creation of files - find all files that were created/modified/access in directory in 10 days

# creation (c)
find /test -name "*.groovy" -ctime -10d
# modification (m)
find /test -name "*.java" -mtime -10d
# access (a)
find /test -name "*.js" -atime -10d

8.Modification Size Filter - find all files that were modified exactly between a week ago to 3 weeks ago and less than 500kb and present their sizes as a list

find /test -name "*.java" -mtime -3w -mtime +1w -size -500k | xargs du -h

How do I add images in laravel view?

If Image folder location is public/assets/img/default.jpg. You can try in view

   <img src="{{ URL::to('/assets/img/default.jpg') }}">

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

You need to create an user "ODBC" for MySql with no password. Do that in PHPMyAdmin. That will solve your problem.

But remember, if it's only your local development environment, no problem. It'll create a serious security hole in your production environment.

User ODBC with no password

Problem Solved

Response Content type as CSV

Just Use like that

Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + filename + ".csv\"");
Response.Write(t.ToString());
Response.End();

How do I disable orientation change on Android?

In OnCreate method of your activity use this code:

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Now your orientation will be set to portrait and will never change.

Reading entire html file to String?

You can use JSoup.
It's a very strong HTML parser for java

Git - How to close commit editor?

Note that if you're using Sublime as your commit editor, you need the -n -w flags, otherwise git keeps thinking your commit message is empty and aborting.

display: inline-block extra margin

After struggling with this issue too many times I found a very elegant solution in HTML 5. In HTML 5 you should not close several (li,p,etc) tags; the ambition to become XML is forever gone. For example, the preferred way to do a list is:

<ul>
   <li>
       <a ...>...</a>
   <li>
       <a ...>...</a>
</ul>

Browsers MUST close the LI and they must do this without introducing whitespace, solving this problem. If you still have the XML mindset it feels wrong but once you get over that it saves many a nightmare. And this is not a hack since it relies on the wording of the HTML 5 spec. Better, since not closing tags is pervasive I expect no compatibility issues (not tested though). Bonus is that HTML formatters handle this well.

A little worked out example: http://cssdesk.com/Ls7fK

Multiple queries executed in java in single statement

Why dont you try and write a Stored Procedure for this?

You can get the Result Set out and in the same Stored Procedure you can Insert what you want.

The only thing is you might not get the newly inserted rows in the Result Set if you Insert after the Select.

Create an array with random values

Even shorter ES6 approach:

Array(40).fill().map(() => Math.round(Math.random() * 40))

Also, you could have a function with arguments:

const randomArray = (length, max) => 
  Array(length).fill().map(() => Math.round(Math.random() * max))

How to store .pdf files into MySQL as BLOBs using PHP?

//Pour inserer :
            $pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
            $filetype = addslashes($_FILES['inputname']['type']);//pour le test 
            $namepdf = addslashes($_FILES['inputname']['name']);            
            if (substr($filetype, 0, 11) == 'application'){
            $mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
            }
//Pour afficher :
            $row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
            foreach($row as $result){
                 $file=$result['pdf'];
            }
            header('Content-type: application/pdf');
            echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));

how do I insert a column at a specific column index in pandas?

If you want a single value for all rows:

df.insert(0,'name_of_column','')
df['name_of_column'] = value

Edit:

You can also:

df.insert(0,'name_of_column',value)

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

$out.='<option value="'.$key.'">'.$value["name"];

me funciono con esta

"<a  href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";

Disable elastic scrolling in Safari

None of the above solutions worked for me, however instead I wrapped my content in a div (#outer-wrap) and then used the following CSS:

body {
   overflow: hidden;
}
#outer-wrap {
    -webkit-overflow-scrolling: touch;
     height: 100vh;
     overflow: auto;
}

Obviously only works in browsers that support viewport widths/heights of course.

how to remove "," from a string in javascript

Use String.replace(), e.g.

var str = "a,d,k";
str = str.replace( /,/g, "" );

Note the g (global) flag on the regular expression, which matches all instances of ",".

Making a button invisible by clicking another button in HTML

write this

To hide

{document.getElementById("p2").style.display="none";}

to show

{document.getElementById("p2").style.display="block";}

How to get index of an item in java.util.Set

After creating Set just convert it to List and get by index from List:

Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");

List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";

Check file uploaded is in csv format

Mime type option is not best option for validating CSV file. I used this code this worked well in all browser

$type = explode(".",$_FILES['file']['name']);
if(strtolower(end($type)) == 'csv'){

}
else
{

}

HRESULT: 0x800A03EC on Worksheet.range

Seems like this i s a pretty generic error for "something went wrong" with the operation you attempted. I have observed that will also occur if you have a formula error and are assigning that formula into a cell. E.g. "=fubar()"

Java Code for calculating Leap Year

this answer is great but it won't work for years before Christ (using a proleptic Gregorian calendar). If you want it to work for B.C. years, then use the following adaptation:

public static boolean isLeapYear(final int year) {
    final Calendar cal = Calendar.getInstance();
    if (year<0) {
        cal.set(Calendar.ERA, GregorianCalendar.BC);
        cal.set(Calendar.YEAR, -year);
    } else
        cal.set(Calendar.YEAR, year);
    return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}

You can verify that for yourself by considering that year -5 (i.e. 4 BC) should be pronounced as a leap year assuming a proleptic Gregorian calendar. Same with year -1 (the year before 1 AD). The linked to answer does not handle that case whereas the above adapted code does.

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

jQuery validate: How to add a rule for regular expression validation?

You may use pattern defined in the additional-methods.js file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use

_x000D_
_x000D_
$("#frm").validate({_x000D_
    rules: {_x000D_
        Textbox: {_x000D_
            pattern: /^[a-zA-Z'.\s]{1,40}$/_x000D_
        },_x000D_
    },_x000D_
    messages: {_x000D_
        Textbox: {_x000D_
            pattern: 'The Textbox string format is invalid'_x000D_
        }_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>_x000D_
<form id="frm" method="get" action="">_x000D_
    <fieldset>_x000D_
        <p>_x000D_
            <label for="fullname">Textbox</label>_x000D_
            <input id="Textbox" name="Textbox" type="text">_x000D_
        </p>_x000D_
    </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How can I convert a .py to .exe for Python?

There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

GUI:

Auto Py to Exe

Output:

Output

Style input element to fill remaining width of its container

you can try this :

_x000D_
_x000D_
div#panel {_x000D_
    border:solid;_x000D_
    width:500px;_x000D_
    height:300px;_x000D_
}_x000D_
div#content {_x000D_
 height:90%;_x000D_
 background-color:#1ea8d1; /*light blue*/_x000D_
}_x000D_
div#panel input {_x000D_
 width:100%;_x000D_
 height:10%;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
 -webkit-box-sizing: border-box;_x000D_
       -moz-box-sizing: border-box;_x000D_
            box-sizing: border-box;_x000D_
 /*make input doesnt overflow inside div*/_x000D_
}
_x000D_
<div id="panel">_x000D_
  <div id="content"></div>_x000D_
  <input type="text" placeholder="write here..."/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Make A List Item Clickable (HTML/CSS)

HTML and CSS only.

_x000D_
_x000D_
#leftsideMenu ul li {_x000D_
  border-bottom: 1px dashed lightgray;_x000D_
  background-color: cadetblue;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a {_x000D_
  padding: 8px 20px 8px 20px;_x000D_
  color: white;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a:hover {_x000D_
  background-color: lightgreen;_x000D_
  transition: 0.5s;_x000D_
  padding-left: 30px;_x000D_
  padding-right: 10px;_x000D_
}
_x000D_
<div id="leftsideMenu">_x000D_
  <ul style="list-style-type:none">_x000D_
    <li><a href="#">India</a></li>_x000D_
    <li><a href="#">USA</a></li>_x000D_
    <li><a href="#">Russia</a></li>_x000D_
    <li><a href="#">China</a></li>_x000D_
    <li><a href="#">Afganistan</a></li>_x000D_
    <li><a href="#">Landon</a></li>_x000D_
    <li><a href="#">Scotland</a></li>_x000D_
    <li><a href="#">Ireland</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Adding content to a linear layout dynamically?

In your onCreate(), write the following

LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);

view1, view2 and view3 are your TextViews. They're easily created programmatically.

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

How do I compile a .cpp file on Linux?

The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.

Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

What should my Objective-C singleton look like?

Another option is to use the +(void)initialize method. From the documentation:

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

So you could do something akin to this:

static MySingleton *sharedSingleton;

+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        sharedSingleton = [[MySingleton alloc] init];
    }
}

Centering text in a table in Twitter Bootstrap

One of the main feature of Bootstrap is that it alleviates the use of !important tag. Using the above answer would defeat the purpose. You can easily customise bootstrap by modifying the classes in your own css file and linking it after including the boostrap css.

Refresh or force redraw the fragment

To solve the problem, I use this:

Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("Feedback");
final android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

is there a function in lodash to replace matched item

In your case all you need to do is to find object in array and use Array.prototype.splice() method, read more details here:

_x000D_
_x000D_
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];_x000D_
_x000D_
// Find item index using _.findIndex (thanks @AJ Richardson for comment)_x000D_
var index = _.findIndex(arr, {id: 1});_x000D_
_x000D_
// Replace item at index using native splice_x000D_
arr.splice(index, 1, {id: 100, name: 'New object.'});_x000D_
_x000D_
// "console.log" result_x000D_
document.write(JSON.stringify( arr ));
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

Newline in markdown table?

Just for those that are trying to do this on Jira. Just add \\ at the end of each line and a new line will be created:

|Something|Something else \\ that's rather long|Something else|

Will render this:

enter image description here

Source: Text breaks on Jira

Where's the DateTime 'Z' format specifier?

This page on MSDN lists standard DateTime format strings, uncluding strings using the 'Z'.

Update: you will need to make sure that the rest of the date string follows the correct pattern as well (you have not supplied an example of what you send it, so it's hard to say whether you did or not). For the UTC format to work it should look like this:

// yyyy'-'MM'-'dd HH':'mm':'ss'Z'
DateTime utcTime = DateTime.Parse("2009-05-07 08:17:25Z");

How to create a byte array in C++?

Byte is not a standard type in C/C++, so it is represented by char.

An advantage of this is that you can treat a basic_string as a byte array allowing for safe storage and function passing. This will help you avoid the memory leaks and segmentation faults you might encounter when using the various forms of char[] and char*.

For example, this creates a string as a byte array of null values:

typedef basic_string<unsigned char> u_string;

u_string bytes = u_string(16,'\0');

This allows for standard bitwise operations with other char values, including those stored in other string variables. For example, to XOR the char values of another u_string across bytes:

u_string otherBytes = "some more chars, which are just bytes";
for(int i = 0; i < otherBytes.length(); i++)
    bytes[i%16] ^= (int)otherBytes[i];

Unexpected token ILLEGAL in webkit

Also for the Google-fodder: check in your text editor whether the .js file is saved as Unicode and consider setting it to ANSI; also check if the linefeeds are set to DOS and consider switching them to Unix (depending on your server, of course).

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Clearing NSUserDefaults

Here is the answer in Swift:

let appDomain = NSBundle.mainBundle().bundleIdentifier!
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)

How to set the java.library.path from Eclipse

Sometime we dont get Java Build Path by directly right click on project. then go to properties.... Right Click and go to properties

Then Click on java build pathProperties Scrren

Click on add external jar

Click on tab add external jars and give path of your computer file where u have stored jars.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How can I convert an image into Base64 string using JavaScript?

Basically, if your image is

<img id='Img1' src='someurl'>

then you can convert it like

var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');

ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();

Determine Whether Integer Is Between Two Other Integers?

The condition should be,

if number == 10000 and number <= 30000:
     print("5% tax payable")

reason for using number == 10000 is that if number's value is 50000 and if we use number >= 10000 the condition will pass, which is not what you want.

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.

CSS - center two images in css side by side

I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:

in html code:

<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>

The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.

in css code:

/* h6: set presentation of images */
h6
  {
  font-family: "Franklin Gothic Demi", serif;
  font-size: 1.0em;
  font-weight: normal;
  line-height: 1.25em;
  text-align: center;
  }

The text items set the look of the caption text, and the text-align property centers both the images and the caption text.

Is a view faster than a simple query?

There should be some trivial gain in having the execution plan stored, but it will be negligible.

Can I do Android Programming in C++, C?

You should use Android NDK to develop performance-critical portions of your apps in native code. See Android NDK.

Anyway i don't think it is the right way to develop an entire application.

Not connecting to SQL Server over VPN

This is what fixed my connection problem of accessing the SQL Server 2012 Database via VPN

With the SQL Server 2012 Configuration Manager,

I went to the SQL Server Network configuration

Then clicked on the NEW server instance and double-clicked the TCP/IP protocol [I had also previously enabled this option and rebooted the server but that did still not fix it]

now that the TCP/IP was enabled, I noted that all of the IP port slots in the 'IP Addresses' tab of the TCP/IP Properties advanced dialog were set to Enabled=No.

I was curious to why my new installation set all of these IP slots to NO rather than Yes, so I just changed them to YES.

Now the connection to the sever via VPN works great, I did not change any port numbers.

Note: I also had SQL Server 2008 default from the Visual studio 2010 uninstalled, but I do not think that had a direct effect to the TCP/IP situation. A coworker told me that the 2008 and 2005 installations which come with visual studio may interfere with SQL 2012.

Dynamically fill in form values with jQuery

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

C# compiler error: "not all code paths return a value"

Or Simply Do this Stuff:

public static bool isTwenty(int num)
{
   for(int j = 1; j <= 20; j++)
   {
      if(num % j != 0)
      {
          return false;
      }
      else if(num % j == 0 && num == 20)
      {
          return true;
      }
      else
          return false; 
      }

}

How to perform OR condition in django queryset?

Just adding this for multiple filters attaching to Q object, if someone might be looking to it. If a Q object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.

an example would be

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')

Here the OR condition and a filter with category of income is taken into account

Mapping composite keys using EF code first

You definitely need to put in the column order, otherwise how is SQL Server supposed to know which one goes first? Here's what you would need to do in your code:

public class MyTable
{
  [Key, Column(Order = 0)]
  public string SomeId { get; set; }

  [Key, Column(Order = 1)]
  public int OtherId { get; set; }
}

You can also look at this SO question. If you want official documentation, I would recommend looking at the official EF website. Hope this helps.

EDIT: I just found a blog post from Julie Lerman with links to all kinds of EF 6 goodness. You can find whatever you need here.

Convert wchar_t to char

An easy way is :

        wstring your_wchar_in_ws(<your wchar>);
        string your_wchar_in_str(your_wchar_in_ws.begin(), your_wchar_in_ws.end());
        char* your_wchar_in_char =  your_wchar_in_str.c_str();

I'm using this method for years :)

Python check if website exists

It's better to check that status code is < 400, like it was done here. Here is what do status codes mean (taken from wikipedia):

  • 1xx - informational
  • 2xx - success
  • 3xx - redirection
  • 4xx - client error
  • 5xx - server error

If you want to check if page exists and don't want to download the whole page, you should use Head Request:

import httplib2
h = httplib2.Http()
resp = h.request("http://www.google.com", 'HEAD')
assert int(resp[0]['status']) < 400

taken from this answer.

If you want to download the whole page, just make a normal request and check the status code. Example using requests:

import requests

response = requests.get('http://google.com')
assert response.status_code < 400

See also similar topics:

Hope that helps.

How to recover corrupted Eclipse workspace?

deleting below file helped me solve my eclipse start up issue. Perforce plugin has always troubled me especially when my machine reboots, next time eclipse tries to recover workspace and craps out.

workspace/.metadata/.plugins/org.eclipse.core.resources/.snap

For your reference, Error I was getting: org.eclipse.core.runtime.CoreException: Plug-in com.perforce.team.ui was unable to load class com.perforce.team.ui.UITeamProvider.

Git will not init/sync/update new submodules

According to the answer from Dave James Miller I can confirm that it worked for me. The important thing here was to commit the subprojects commit ID. Just to have the entry in .gitmodules was not enough.

Here is an appropriate commit:

https://github.com/dirkaholic/vagrant-php-dev-box/commit/d5f4c40bdbd80eefbb5ac6029823733f591435ae

HEAD and ORIG_HEAD in Git

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.

And @ alone is a shortcut for HEAD, since Git 1.8.5

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary

How do I center an SVG in a div?

For me, the fix was to add margin: 0 auto; onto the element containing the <svg>.

Like this:

<div style="margin: 0 auto">
   <svg ...</svg>
</div>

Get the client's IP address in socket.io

If you use an other server as reverse proxy all of the mentioned fields will contain localhost. The easiest workaround is to add headers for ip/port in the proxy server.

Example for nginx: add this after your proxy_pass:

proxy_set_header  X-Real-IP $remote_addr;
proxy_set_header  X-Real-Port $remote_port;

This will make the headers available in the socket.io node server:

var ip = socket.handshake.headers["x-real-ip"];
var port = socket.handshake.headers["x-real-port"];

Note that the header is internally converted to lower case.

If you are connecting the node server directly to the client,

var ip = socket.conn.remoteAddress;

works with socket.io version 1.4.6 for me.

Pressed <button> selector

Maybe :active over :focus with :hover will help! Try

button {
background:lime;
}

button:hover {
background:green;
}

button:focus {
background:gray;
}

button:active {
background:red;
}

Then:

<button onkeydown="alerted_of_key_pressed()" id="button" title="Test button" href="#button">Demo</button>

Then:

<!--JAVASCRIPT-->
<script>
function alerted_of_key_pressed() { alert("You pressed a key when hovering over this button.") }
</script>
 Sorry about that last one. :) I was just showing you a cool function! 
Wait... did I just emphasize a code block? This is cool!!!

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Future readers.

I have had the best luck figuring out these issues....using this method:

private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MyDaoObject.class);

@Transactional
public void save(MyObject item) {


    try {
         /* this is whatever code you have already...this is just an example */
        entityManager.persist(item);
        entityManager.flush();
    }
    catch(Exception ex)
    {
        /* below works in conjunction with concrete logging framework */
        logger.error(ex.getMessage(), ex);
        throw ex;
    }
}

Now, slf4j is just a fascade (interfaces, adapter)..... you need a concrete.

When picking log4j2, you want to persist the

%throwable

So you are not flying blind, you can see %throwable at the below URL (on how you defined %throwable so it shows up in the logging. If you're not using log4j2 as the concrete, you'll have to figure out your logging framework's version of %throwable)

https://www.baeldung.com/log4j2-appenders-layouts-filters

That %throwable, when logged, will have the actual SQL exception in it.

if throwable is giving you a fuss, you can do this (the below is NOT great since it does recursive log calls)

@Transactional
public void save(MyObject item) {


    try {
         /* this is whatever code you have already...this is just an example */
        entityManager.persist(item);
        entityManager.flush();
    catch(Exception ex)
    {
        logger.error(ex.getMessage(), ex);
        //throw ex;
        Throwable thr = ex;
        /* recursive logging warning !!! could perform very poorly, not for production....alternate idea is to use Stringbuilder and log the stringbuilder result */
        while (null != thr) {
            logger.error(thr.getMessage(), thr);
            thr = thr.getCause();
        }
    }
}

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

How can I submit a POST form using the <a href="..."> tag?

I use a jQuery script to create "shadow" forms for my POSTable links.

Instead of <a href="/some/action?foo=bar">, I write <a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">. The script makes a hidden form with hidden inputs, and submits it when the link is clicked.

_x000D_
_x000D_
$("a[data-post]")
    .each(function() {
        let href = $(this).data("post"); if (!href) return;
        let $form = $("<form></form>").attr({ method:"POST",action:href }).css("display","none")
        let data = $(this).data()
        for (let dat in data) {
            if (dat.startsWith("postVar")) {
                let varname = dat.substring(7).toLowerCase()  // postVarId -> id
                let varval = data[dat]
                $form.append($("<input/>").attr({ type:"hidden",name:varname,value:varval }))
            }
        }
        $("body").append($form)
        $(this).data("postform",$form)
    })
    .click(function(ev) {
        ev.preventDefault()
        if ($(this).data("postform")) $(this).data("postform").submit(); else console.error("No .postform set in <a data-post>")
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">click me</a>
_x000D_
_x000D_
_x000D_

How to sort a collection by date in MongoDB?

Additional Square [ ] Bracket is required for sorting parameter to work.

collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {});

How can I loop through a C++ map of maps?

As einpoklum mentioned in their answer, since C++17 you can also use structured binding declarations. I want to extend on that by providing a full solution for iterating over a map of maps in a comfortable way:

int main() {
    std::map<std::string, std::map<std::string, std::string>> m {
        {"name1", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name2", {{"value1", "data1"}, {"value2", "data2"}}},
        {"name3", {{"value1", "data1"}, {"value2", "data2"}}}
    };

    for (const auto& [k1, v1] : m)
        for (const auto& [k2, v2] : v1)
            std::cout << "m[" << k1 << "][" << k2 << "]=" << v2 << std::endl;

    return 0;
}

Note 1: For filling the map, I used an initializer list (which is a C++11 feature). This can sometimes be handy to keep fixed initializations compact.

Note 2: If you want to modify the map m within the loops, you have to remove the const keywords.

Code on Coliru

Reverse Y-Axis in PyPlot

If you're in ipython in pylab mode, then

plt.gca().invert_yaxis()
show()

the show() is required to make it update the current figure.

How to turn off gcc compiler optimization to enable buffer overflow

I won't quote the entire page but the whole manual on optimisation is available here: http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Optimize-Options.html#Optimize-Options

From the sounds of it you want at least -O0, the default, and:

-fmudflap -fmudflapth -fmudflapir

For front-ends that support it (C and C++), instrument all risky pointer/array dereferencing operations, some standard library string/heap functions, and some other associated constructs with range/validity tests. Modules so instrumented should be immune to buffer overflows, invalid heap use, and some other classes of C/C++ programming errors. The instrumentation relies on a separate runtime library (libmudflap), which will be linked into a program if -fmudflap is given at link time. Run-time behavior of the instrumented program is controlled by the MUDFLAP_OPTIONS environment variable. See env MUDFLAP_OPTIONS=-help a.out for its options.

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Instead of Windows PowerShell, find the item in the Start Menu called SharePoint 2013 Management Shell:

enter image description here

Exit a Script On Error

Here is the way to do it:

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE *** 
************
'

Can I force a page break in HTML printing?

_x000D_
_x000D_
First page (scroll down to see the second page)_x000D_
<div style="break-after:page"></div>_x000D_
Second page_x000D_
<br>_x000D_
<br>_x000D_
<button onclick="window.print();return false;" />Print (to see the result) </button>
_x000D_
_x000D_
_x000D_

Just add this where you need the page to go to the next one (the text "page 1" will be on page 1 and the text "page 2" will be on the second page).

Page 1
<div style='page-break-after:always'></div>
Page 2

This works too:

First page (there is a break after this)
<div style="break-after:page"></div>
Second page (This will be printed in the second page)

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

Oracle 12c Installation failed to access the temporary location

I ran into this error when attempting to install 12c 32x client on Windows 10. "net use \\localhost\c$" worked, but when I substituted "localhost" the computer's "name" (e.g., \\my-computer\c$), I got the "System error 53 ...". Oracle seems to prefer the computer's name.

What fixed it: we temporarily disabled the IPv6 protocol for the computer (our network uses IPv4). How to do this: Control Panel --> Network and Sharing Center --> Change adapter settings --> right click on Ethernet Connection --> Properties --> uncheck "Internet Protocol Version 6 (TCP/IPv6) --> OK. That should disable it. After that, \\my-computer\c$ ran successfully in the command prompt. Then the Oracle installer finally completed and we were able to tnsping the database server.

Just to test it out, we re-enabled IPv6 and restarted the computer. \\my-computer\c$ failed in the cmd prompt, but tnsping still functioned correctly.

I hope this helps somebody in the future.

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

File changed listener in Java

I run this snippet of code every time I go to read the properties file, only actually reading the file if it has been modified since the last time I read it. Hope this helps someone.

private long timeStamp;
private File file;

private boolean isFileUpdated( File file ) {
  this.file = file;
  this.timeStamp = file.lastModified();

  if( this.timeStamp != timeStamp ) {
    this.timeStamp = timeStamp;
    //Yes, file is updated
    return true;
  }
  //No, file is not updated
  return false;
}

Similar approach is used in Log4J FileWatchdog.

Create a HTML table where each TR is a FORM

You may have issues with column width, but you can set those explicitly.

<table>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  </table>

You may want to also consider making it a single form, and then using jQuery to select the form elements from the row you want, serialize them, and submit them as the form.

See: http://api.jquery.com/serialize/

Also, there are a number of very nice grid plugins: http://www.google.com/search?q=jquery+grid&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Importing a GitHub project into Eclipse

I encountered the same problem, and finally found a way:

  1. Add or create git repository in git view.
  2. Click new java project menu, uncheck "use default location", select the git repo location, click finish.

Ecplise Version: Mars.2 Release (4.5.2)

How to run a python script from IDLE interactive shell?

execFile('helloworld.py') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)

For example, execFile('C:/helloworld.py')

The transaction manager has disabled its support for remote/network transactions

In my scenario, the exception was being thrown because I was trying to create a new connection instance within a TransactionScope on an already existing connection:

Example:

void someFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
        {
            someOtherFunction(); // This function opens a new connection within this transaction, causing the exception.
        }
    }
}

void someOtherFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        db.Whatever // <- Exception.
    }
}

Kotlin unresolved reference in IntelliJ

Had the same with IDEA 14.1.5, Kotlin v.1.0.0-beta-1038-IJ141-17.
Kotlin gets its own list entry (like Java) when creating new project, but the only working config was:

New | Project | Java | "Kotlin (Java)" (make sure you have Project SDK configured, too)
use library: Create, "Copy to: lib".

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

For me better this:

var uA = window.navigator.userAgent,
    onlyIEorEdge = /msie\s|trident\/|edge\//i.test(uA) && !!( document.uniqueID || window.MSInputMethodContext),
    checkVersion = (onlyIEorEdge && +(/(edge\/|rv:|msie\s)([\d.]+)/i.exec(uA)[2])) || NaN;

Go run: http://output.jsbin.com/solicul/1/ o http://jsfiddle.net/Webnewbie/apa1nvu8/

Rotate an image in image source in html

If your rotation angles are fairly uniform, you can use CSS:

<img id="image_canv" src="/image.png" class="rotate90">

CSS:

.rotate90 {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:

<img id="image_canv" src="/image.png" data-rotate="90">

Sample jQuery:

$('img').each(function() {
    var deg = $(this).data('rotate') || 0;
    var rotate = 'rotate(' + deg + 'deg)';
    $(this).css({ 
        '-webkit-transform': rotate,
        '-moz-transform': rotate,
        '-o-transform': rotate,
        '-ms-transform': rotate,
        'transform': rotate 
    });
});

Demo:

http://jsfiddle.net/verashn/6rRnd/5/

How to set a timer in android

Probably Timerconcept

new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval

 public void onTick(long millisUntilFinished) {
  }
  public void onFinish() {
 }
}.start();

or

Method 2 ::

Program the timer

Add a new variable of int named time. Set it to 0. Add the following code to onCreate function in MainActivity.java.

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

Go into the run method and add the following code.

//We must use this function in order to change the text view text
runOnUiThread(new Runnable() {

    @Override
    public void run() {
        TextView tv = (TextView) findViewById(R.id.main_timer_text);
        tv.setText(String.valueOf(time));
        time += 1;
    }

});

HTTP Error 503. The service is unavailable. App pool stops on accessing website

For anyone coming here with Windows 10 and after updating them to Anniversary update, please check this link, it helped me:

https://orcharddojo.net/blog/troubleshooting-iis-apppool-crashes-status-503-after-windows-10-anniversary-update

In case link goes down: If your Event log shows that aspnetcore.dll, rewrite.dll (most often, but could be others as well) failed to load, you have to repair the missing items.

Here are two specific issues we've experienced so far and how to fix them, but you may bump into completely different ones:

"C:\WINDOWS\system32\inetsrv\rewrite.dll" (reference)
    Go to "Programs and Features" (Win+X, F) and repair "IIS URL Rewrite Module 2".
"C:\WINDOWS\system32\inetsrv\aspnetcore.dll" (reference)
    Go to "Programs and Features" (Win+X, F) and repair "Microsoft .NET Core 1.0.0 - VS 2015 Tooling ...".

Call method when home button pressed

It took me almost a month to get through this. Just now I solved this issue. In your activity's onPause() you have to include the following if condition:

    if (this.isFinishing()){
        //Insert your finishing code here
    }

The function isFinishing() returns a boolean. True if your App is actually closing, False if your app is still running but for example the screen turns off.

Hope it helps!

Django set field value after a form is initialized

Another way to do this, if you have already initialised a form (with or without data), and you need to add further data before displaying it:

form = Form(request.POST.form)
form.data['Email'] = GetEmailString()

How to generate keyboard events?

For both python3 and python2 you can use pyautogui (pip install pyautogui)

from pyautogui import press, typewrite, hotkey

press('a')
typewrite('quick brown fox')
hotkey('ctrl', 'w')

It's also crossplatform with Windows, OSX, and Ubuntu LTS.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

I got this issue solved in the 'Windows' way. After checking all my settings, cleaning the solution and rebuilding it, I simply close the solution and reopened it. Then it worked, so VS probably didn't get rid of some stuff during cleaning. When logical solutions don't work, I usually turn to illogical (or seemingly illogical) ones. Windows doesn't let me down. :)

Creating a recursive method for Palindrome

Simple Solution 2 Scenario --(Odd or Even length String)

Base condition& Algo recursive(ch, i, j)

  1. i==j //even len

  2. if i< j recurve call (ch, i +1,j-1)

  3. else return ch[i] ==ch[j]// Extra base condition for old length

public class HelloWorld {


 static boolean ispalindrome(char ch[], int i, int j) {
  if (i == j) return true;

  if (i < j) {
   if (ch[i] != ch[j])
    return false;
   else
    return ispalindrome(ch, i + 1, j - 1);
  }
  if (ch[i] != ch[j])
   return false;
  else
   return true;

 }
 public static void main(String[] args) {
  System.out.println(ispalindrome("jatin".toCharArray(), 0, 4));
  System.out.println(ispalindrome("nitin".toCharArray(), 0, 4));
  System.out.println(ispalindrome("jatinn".toCharArray(), 0, 5));
  System.out.println(ispalindrome("nittin".toCharArray(), 0, 5));

 }
}

Regular expression to search multiple strings (Textpad)

I suggest much better solution. Task in my case: add http://google.com/ path before each record and import multiple fields.

CSV single field value (all images just have filenames, separate by |):
"123.jpg|345.jpg|567.jpg"

Tamper 1st plugin: find and replace by REGEXP: pattern: /([a-zA-Z0-9]*)./ replacement: http://google.com/$1

Tamper 2nd plugin: explode setting: explode by |

In this case you don't need any additinal fields mappings and can use 1 field in CSV

What are the various "Build action" settings in Visual Studio project properties and what do they do?

  • Fakes: Part of the Microsoft Fakes (Unit Test Isolation) Framework. Not available on all Visual Studio versions. Fakes are used to support unit testing in your project, helping you isolate the code you are testing by replacing other parts of the application with stubs or shims. More here: https://msdn.microsoft.com/en-us/library/hh549175.aspx

Should composer.lock be committed to version control?

  1. You shouldn't update your dependencies directly on Production.
  2. You should version control your composer.lock file.
  3. You shouldn't version control your actual dependencies.

1. You shouldn't update your dependencies directly on Production, because you don't know how this will affect the stability of your code. There could be bugs introduced with the new dependencies, it might change the way the code behaves affecting your own, it could be incompatible with other dependencies, etc. You should do this in a dev environment, following by proper QA and regression testing, etc.

2. You should version control your composer.lock file, because this stores information about your dependencies and about the dependencies of your dependencies that will allow you to replicate the current state of the code. This is important, because, all your testing and development has been done against specific code. Not caring about the actual version of the code that you have is similar to uploading code changes to your application and not testing them. If you are upgrading your dependencies versions, this should be a willingly act, and you should take the necessary care to make sure everything still works. Losing one or two hours of up time reverting to a previous release version might cost you a lot of money.

One of the arguments that you will see about not needing the composer.lock is that you can set the exact version that you need in your composer.json file, and that in this way, every time someone runs composer install, it will install them the same code. This is not true, because, your dependencies have their own dependencies, and their configuration might be specified in a format that it allows updates to subversions, or maybe even entire versions.

This means that even when you specify that you want Laravel 4.1.31 in your composer.json, Laravel in its composer.json file might have its own dependencies required as Symfony event-dispatcher: 2.*. With this kind of config, you could end up with Laravel 4.1.31 with Symfony event-dispatcher 2.4.1, and someone else on your team could have Laravel 4.1.31 with event-dispatcher 2.6.5, it would all depend on when was the last time you ran the composer install.

So, having your composer.lock file in the version system will store the exact version of this sub-dependencies, so, when you and your teammate does a composer install (this is the way that you will install your dependencies based on a composer.lock) you both will get the same versions.

What if you wanna update? Then in your dev environment run: composer update, this will generate a new composer.lock file (if there is something new) and after you test it, and QA test and regression test it and stuff. You can push it for everyone else to download the new composer.lock, since its safe to upgrade.

3. You shouldn't version control your actual dependencies, because it makes no sense. With the composer.lock you can install the exact version of the dependencies and you wouldn't need to commit them. Why would you add to your repo 10000 files of dependencies, when you are not supposed to be updating them. If you require to change one of this, you should fork it and make your changes there. And if you are worried about having to fetch the actual dependencies each time of a build or release, composer has different ways to alleviate this issue, cache, zip files, etc.

Can the Android layout folder contain subfolders?

Now we can easily do with JetBrains plugin called "Android File Grouping"

check out this link

Android File Grouping

enter image description here

How can I initialize a MySQL database with schema in a Docker container?

After to struggle a little bit with that, take a look the Dockerfile using named volumes (db-data). It's important declare a plus at final part, where I mentioned that volume is [external]

All worked great this way!

version: "3"

services:

  database:
    image: mysql:5.7
    container_name: mysql
    ports:
      - "3306:3306"
    volumes:
      - db-data:/docker-entrypoint-initdb.d
    environment:
      - MYSQL_DATABASE=sample
      - MYSQL_ROOT_PASSWORD=root

volumes:
  db-data:
    external: true

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Is there a "do ... while" loop in Ruby?

How about this?

people = []

until (info = gets.chomp).empty?
  people += [Person.new(info)]
end

Decreasing height of bootstrap 3.0 navbar

if you are using the less source, there should be a variable for the navbar height in the variables.less file. If you are not using the source, then you can customize it using the customize utilty that bootstrap's site provides. And then you can downloaded it and include it in your project. The variable you are looking for is: @navbar-height

C# ASP.NET MVC Return to Previous Page

For ASP.NET Core You can use asp-route-* attribute:

<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">

An example: Imagine that you have a Vehicle Controller with actions

Index

Details

Edit

and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
     ..............
     ..............
     public string ReturnUrl {get;set;}
}



Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>

Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>

Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
        <div class="box-footer">
            <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
            <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
        </div>
    </form>

In your controller:

// GET: Vehicle/Edit/5
    public ActionResult Edit(int id,string previous)
    {
            var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
            var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
    //or by this code if you are not use automapper
    var viewModel = new VehicleViewModel();

    if (!string.IsNullOrWhiteSpace(previous)
                viewModel.ReturnUrl = previous;
            else
                viewModel.ReturnUrl = "Index";
            return View(viewModel);
        }



[HttpPost]
    public IActionResult Edit(VehicleViewModel model, string previous)
    {
            if (!string.IsNullOrWhiteSpace(previous))
                model.ReturnUrl = previous;
            else
                model.ReturnUrl = "Index";
            ............. 
            .............
            return RedirectToAction(model.ReturnUrl);
    }

How to get a float result by dividing two integer values using T-SQL?

I understand that CASTing to FLOAT is not allowed in MySQL and will raise an error when you attempt to CAST(1 AS float) as stated at MySQL dev.

The workaround to this is a simple one. Just do

(1 + 0.0)

Then use ROUND to achieve a specific number of decimal places like

ROUND((1+0.0)/(2+0.0), 3)

The above SQL divides 1 by 2 and returns a float to 3 decimal places, as in it would be 0.500.

One can CAST to the following types: binary, char, date, datetime, decimal, json, nchar, signed, time, and unsigned.

How to call a method function from another class?

You need to understand the difference between classes and objects. From the Java tutorial:

An object is a software bundle of related state and behavior

A class is a blueprint or prototype from which objects are created

You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new keyword.

new Date();

You will need to assign the object to a variable of the same type as the class the object was created from.

Date d = new Date();

Once you have a reference to the object you can interact with it

d.date("01", "12", "14");

The exception to this is static methods that belong to the class and are referenced through it

public class MyDate{
  public static date(){ ... }
}

...
MyDate.date();

In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.

Javascript .querySelector find <div> by innerTEXT

If you don't want to use jquery or something like that then you can try this:

function findByText(rootElement, text){
    var filter = {
        acceptNode: function(node){
            // look for nodes that are text_nodes and include the following string.
            if(node.nodeType === document.TEXT_NODE && node.nodeValue.includes(text)){
                 return NodeFilter.FILTER_ACCEPT;
            }
            return NodeFilter.FILTER_REJECT;
        }
    }
    var nodes = [];
    var walker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT, filter, false);
    while(walker.nextNode()){
       //give me the element containing the node
       nodes.push(walker.currentNode.parentNode);
    }
    return nodes;
}

//call it like
var nodes = findByText(document.body,'SomeText');
//then do what you will with nodes[];
for(var i = 0; i < nodes.length; i++){ 
    //do something with nodes[i]
} 

Once you have the nodes in an array that contain the text you can do something with them. Like alert each one or print to console. One caveat is that this may not necessarily grab divs per se, this will grab the parent of the textnode that has the text you are looking for.

How do I close an Android alertdialog

I would try putting a

Log.e("SOMETAG", "dialog button was clicked");

before the dialog.dismiss() line in your code to see if it actually reaches that section.

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
{
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;
}

Generate random array of floats between a range

The for loop in list comprehension takes time and makes it slow. It is better to use numpy parameters (low, high, size, ..etc)

import numpy as np
import time
rang = 10000
tic = time.time()
for i in range(rang):
    sampl = np.random.uniform(low=0, high=2, size=(182))
print("it took: ", time.time() - tic)

tic = time.time()
for i in range(rang):
    ran_floats = [np.random.uniform(0,2) for _ in range(182)]
print("it took: ", time.time() - tic)

sample output:

('it took: ', 0.06406784057617188)

('it took: ', 1.7253198623657227)

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

I'm not entirely sure if you want it, but I had a similar task and needed to remove a field if it is zero. For example, 86401 seconds would show "1 days, 1 seconds" instead of "1 days, 0 hours, 0 minutes, 1 seconds". THe following code does that.

def secondsToText(secs):
    days = secs//86400
    hours = (secs - days*86400)//3600
    minutes = (secs - days*86400 - hours*3600)//60
    seconds = secs - days*86400 - hours*3600 - minutes*60
    result = ("{} days, ".format(days) if days else "") + \
    ("{} hours, ".format(hours) if hours else "") + \
    ("{} minutes, ".format(minutes) if minutes else "") + \
    ("{} seconds, ".format(seconds) if seconds else "")
    return result

EDIT: a slightly better version that handles pluralization of words.

def secondsToText(secs):
    days = secs//86400
    hours = (secs - days*86400)//3600
    minutes = (secs - days*86400 - hours*3600)//60
    seconds = secs - days*86400 - hours*3600 - minutes*60
    result = ("{0} day{1}, ".format(days, "s" if days!=1 else "") if days else "") + \
    ("{0} hour{1}, ".format(hours, "s" if hours!=1 else "") if hours else "") + \
    ("{0} minute{1}, ".format(minutes, "s" if minutes!=1 else "") if minutes else "") + \
    ("{0} second{1}, ".format(seconds, "s" if seconds!=1 else "") if seconds else "")
    return result

EDIT2: created a gist that does that in several languages

How do you configure an OpenFileDialog to select folders?

I assume you're on Vista using VS2008? In that case I think that the FOS_PICKFOLDERS option is being used when calling the Vista file dialog IFileDialog. I'm afraid that in .NET code this would involve plenty of gnarly P/Invoke interop code to get working.

Bootstrap Accordion button toggle "data-parent" not working

Bootstrap 4

Use the data-parent="" attribute on the collapse element (instead of the trigger element)

<div id="accordion">
  <div class="card">
    <div class="card-header">
      <h5>
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
          Collapsible #1 trigger
        </button>
      </h5>
    </div>
    <div id="collapseOne" class="collapse show" data-parent="#accordion">
      <div class="card-body">
        Collapsible #1 element
      </div>
    </div>
  </div>
  ... (more cards/collapsibles inside #accordion parent)
</div>

Bootstrap 3

See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966

There is a "bug" that makes the accordion dependent on the .panel class when using the data-parent attribute. To workaround it, you can wrap each accordion group in a 'panel' div..

http://bootply.com/88288

<div class="accordion" id="myAccordion">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
        <div id="collapsible-1" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
        <div id="collapsible-2" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
        <div id="collapsible-3" class="collapse">
           ...
        </div>
    </div>
</div>

Edit

As mentioned in the comments, each section doesn't have to be a .panel. However...

  • .panel must be a direct child of the element used as data-parent=
  • each accordion section (data-toggle=) must be a direct child of the .panel (http://www.bootply.com/AbiRW7BdD6#)

ImportError: No module named six

On Ubuntu and Debian

apt-get install python-six

does the trick.

Use sudo apt-get install python-six if you get an error saying "permission denied".

Android ListView Divider

The android docs warn about things dissappearing due to round-off error... Perhaps try dp instead of px, and perhaps also try > 1 first to see if it is the round-off problem.

see http://developer.android.com/guide/practices/screens_support.html#testing

for the section "Images with 1 pixel height/width"

How to install Anaconda on RaspBerry Pi 3 Model B

If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m in with backticks like so:

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh

jQuery click function doesn't work after ajax call?

Since the class is added dynamically, you need to use event delegation to register the event handler like:

$('#LangTable').on('click', '.deletelanguage', function(event) {
    event.preventDefault();
    alert("success");
});

This will attach your event to any anchors within the #LangTable element, reducing the scope of having to check the whole document element tree and increasing efficiency.

FIDDLE DEMO

How do you perform a left outer join using linq extension methods

Group Join method is unnecessary to achieve joining of two data sets.

Inner Join:

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

For Left Join just add DefaultIfEmpty()

var qry = Foos.SelectMany
            (
                foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id).DefaultIfEmpty(),
                (foo, bar) => new
                    {
                    Foo = foo,
                    Bar = bar
                    }
            );

EF and LINQ to SQL correctly transform to SQL. For LINQ to Objects it is beter to join using GroupJoin as it internally uses Lookup. But if you are querying DB then skipping of GroupJoin is AFAIK as performant.

Personlay for me this way is more readable compared to GroupJoin().SelectMany()

How to set radio button selected value using jquery

You can try this also

function SetRadiobuttonValue(selectedValue)
{
  $(':radio[value="' + selectedValue + '"]').attr('checked', 'checked');
}

How to read HDF5 files in Python

To read the content of .hdf5 file as an array, you can do something as follow

> import numpy as np 
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)

How to set an image's width and height without stretching it?

Load the image as a background for a div.

Instead of:

<img id='logo' src='picture.jpg'>

do

<div id='logo' style='background:url(picture.jpg)'></div>

All browsers will crop the part of the image that doesn't fit.
This has several advantages over wrapping it an element whose overflow is hidden:

  1. No extra markup. The div simply replaces the img.
  2. Easily center or set the image to another offset. eg. url(pic) center top;
  3. Repeat the image when small enough. (Ok, I don't know, why you would want that)
  4. Set a bg color in the same statement, easily apply the same image to multiple elements, and everything that applies to bg images.

Update: This answer is from before object-fit; you should now probably use object-fit/object-position.

It is still useful for older browsers, for extra properties (such as background-repeat), and for edge cases (For example, workaround Chrome bugs with flexbox and object-position and FF's (former?) issues with grid + autoheight + object-fit. Wrapper divs in grid / flexbox often give... unintuitive results.)

JavaScript/jQuery - How to check if a string contain specific words

You might wanna use include method in JS.

var sentence = "This is my line";
console.log(sentence.includes("my"));
//returns true if substring is present.

PS: includes is case sensitive.

How to quickly and conveniently disable all console.log statements in my code?

If you're using gulp, then you can use this plugin:

Install this plugin with the command:

npm install gulp-remove-logging

Next, add this line to your gulpfile:

var gulp_remove_logging = require("gulp-remove-logging");

Lastly, add the configuration settings (see below) to your gulpfile.

Task Configuration

gulp.task("remove_logging", function() {
     return gulp.src("src/javascripts/**/*.js")
    .pipe(
      gulp_remove_logging()
    )
    .pipe(
      gulp.dest(
        "build/javascripts/"
      )
    ); });

What do the return values of Comparable.compareTo mean in Java?

It can be used for sorting, and 0 means "equal" while -1, and 1 means "less" and "more (greater)".

Any return value that is less than 0 means that left operand is lesser, and if value is bigger than 0 then left operand is bigger.

Onclick CSS button effect

Push down the whole button. I suggest this it is looking nice in button.

#button:active {
    position: relative;
    top: 1px;
}

if you only want to push text increase top-padding and decrease bottom padding. You can also use line-height.

How to set image for bar button with swift?

I have achieved that programatically with this code:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        //set image for button
        button.setImage(UIImage(named: "fb.png"), forState: UIControlState.Normal)
        //add function for button
        button.addTarget(self, action: "fbButtonPressed", forControlEvents: UIControlEvents.TouchUpInside)
        //set frame
        button.frame = CGRectMake(0, 0, 53, 31)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        println("Share to fb")
    }
}

And result will be:

enter image description here

Same way you can set button for left side too this way:

self.navigationItem.leftBarButtonItem = barButton

And result will be:

enter image description here

And if you want same transaction as navigation controller have when you go back with default back button then you can achieve that with custom back button with this code:

func backButtonPressed(sender:UIButton) {
    navigationController?.popViewControllerAnimated(true)
}

For swift 3.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton.init(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: UIControlState.normal)
        //add function for button
        button.addTarget(self, action: #selector(ViewController.fbButtonPressed), for: UIControlEvents.touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    func fbButtonPressed() {

        print("Share to fb")
    }
}

For swift 4.0:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //create a new button
        let button = UIButton(type: .custom)
        //set image for button
        button.setImage(UIImage(named: "fb.png"), for: .normal)
        //add function for button
        button.addTarget(self, action: #selector(fbButtonPressed), for: .touchUpInside)
        //set frame
        button.frame = CGRect(x: 0, y: 0, width: 53, height: 51)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.rightBarButtonItem = barButton
    }

    //This method will call when you press button.
    @objc func fbButtonPressed() {

        print("Share to fb")
    }
}

Change header text of columns in a GridView

Better to find cells from gridview instead of static/fix index so it will not generate any problem whenever you will add/remove any columns on gridview.

ASPX:

<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" >
    <Columns>
        <asp:BoundField HeaderText="Date" DataField="CreatedDate" />
    </Columns>
</asp:GridView>

CS:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count; i++)
        {
            if (string.Compare(e.Row.Cells[i].Text, "Date", true) == 0)
            {
                e.Row.Cells[i].Text = "Created Date";
            }
        }
    }
}

Secure FTP using Windows batch script

First, make sure you understand, if you need to use Secure FTP (=FTPS, as per your text) or SFTP (as per tag you have used).

Neither is supported by Windows command-line ftp.exe. As you have suggested, you can use WinSCP. It supports both FTPS and SFTP.

Using WinSCP, your batch file would look like (for SFTP):

echo open sftp://ftp_user:[email protected] -hostkey="server's hostkey" >> ftpcmd.dat
echo put c:\directory\%1-export-%date%.csv >> ftpcmd.dat
echo exit >> ftpcmd.dat
winscp.com /script=ftpcmd.dat
del ftpcmd.dat

And the batch file:

winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date%

Though using all capabilities of WinSCP (particularly providing commands directly on command-line and the %TIMESTAMP% syntax), the batch file simplifies to:

winscp.com /log=ftpcmd.log /command ^
    "open sftp://ftp_user:[email protected] -hostkey=""server's hostkey""" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

For the purpose of -hostkey switch, see verifying the host key in script.

Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you:

Generate batch file

All you need to tweak is the source file name (use the %TIMESTAMP% syntax as shown previously) and the path to the log file.


For FTPS, replace the sftp:// in the open command with ftpes:// (explicit TLS/SSL) or ftps:// (implicit TLS/SSL). Remove the -hostkey switch.

winscp.com /log=ftpcmd.log /command ^
    "open ftps://ftp_user:[email protected] -explicit" ^
    "put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv" ^
    "exit"

You may need to add the -certificate switch, if your server's certificate is not issued by a trusted authority.

Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it generate the script or batch file for you.


See a complete conversion guide from ftp.exe to WinSCP.

You should also read the Guide to automating file transfers to FTP server or SFTP server.


Note to using %TIMESTAMP#yyyymmdd% instead of %date%: A format of %date% variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the %date% resolves to ct 06. 11. 2014, what might be problematic when used as a part of a file name.

For this reason WinSCP supports (locale-neutral) timestamp formatting natively. For example %TIMESTAMP#yyyymmdd% resolves to 20170515 on any locale.

(I'm the author of WinSCP)

Why not inherit from List<T>?

When is it acceptable?

To quote Eric Lippert:

When you're building a mechanism that extends the List<T> mechanism.

For example, you are tired of the absence of the AddRange method in IList<T>:

public interface IMoreConvenientListInterface<T> : IList<T>
{
    void AddRange(IEnumerable<T> collection);
}

public class MoreConvenientList<T> : List<T>, IMoreConvenientListInterface<T> { }

Reset local repository branch to be just like remote repository HEAD

Have you forgotten to create a feature-branch and have committed directly on master by mistake?

You can create the feature branch now and set master back without affecting the worktree (local filesystem) to avoid triggering builds, tests and trouble with file-locks:

git checkout -b feature-branch
git branch -f master origin/master

Logcat not displaying my log calls

some times the problem is not from pc on the other hand IDE,ADB etc, but it arises from your device that doesn't send logs to ADB so if you tried all the ways mentioned before and still your logcat is empty try to restart your device and try again.I tried all the ways mentioned above and neither of them worked but after a restart on my phone logcat worked like magic

Setting the Textbox read only property to true using JavaScript

Try This :-

set Read Only False ( Editable TextBox)

document.getElementById("txtID").readOnly=false;

set Read Only true(Not Editable )

var v1=document.getElementById("txtID");
v1.setAttribute("readOnly","true");

This can work on IE and Firefox also.

PHP __get and __set magic methods

Intenta con:

__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}

C# Interfaces. Implicit implementation versus Explicit implementation

In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.

/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
    string Title { get; }
    string ISBN { get; }
}

/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
    string Title { get; }
    string Forename { get; }
    string Surname { get; }
}

/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
    /// <summary>
    /// This method is shared by both Book and Person
    /// </summary>
    public string Title
    {
        get
        {
            string personTitle = "Mr";
            string bookTitle = "The Hitchhikers Guide to the Galaxy";

            // What do we do here?
            return null;
        }
    }

    #region IPerson Members

    public string Forename
    {
        get { return "Lee"; }
    }

    public string Surname
    {
        get { return "Oades"; }
    }

    #endregion

    #region IBook Members

    public string ISBN
    {
        get { return "1-904048-46-3"; }
    }

    #endregion
}

This code compiles and runs OK, but the Title property is shared.

Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.

string IBook.Title
{
    get
    {
        return "The Hitchhikers Guide to the Galaxy";
    }
}

string IPerson.Title
{
    get
    {
        return "Mr";
    }
}

public string Title
{
    get { return "Still shared"; }
}

Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.

Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.

If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.

How to get the list of files in a directory in a shell script?

$ pwd; ls -l
/home/victoria/test
total 12
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  a
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  b
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  c
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'c d'
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  d
drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_a
drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_b
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'e; f'

$ find . -type f
./c
./b
./a
./d
./c d
./e; f

$ find . -type f | sed 's/^\.\///g' | sort
a
b
c
c d
d
e; f

$ find . -type f | sed 's/^\.\///g' | sort > tmp

$ cat tmp
a
b
c
c d
d
e; f

Variations

$ pwd
/home/victoria

$ find $(pwd) -maxdepth 1 -type f -not -path '*/\.*' | sort
/home/victoria/new
/home/victoria/new1
/home/victoria/new2
/home/victoria/new3
/home/victoria/new3.md
/home/victoria/new.md
/home/victoria/package.json
/home/victoria/Untitled Document 1
/home/victoria/Untitled Document 2

$ find . -maxdepth 1 -type f -not -path '*/\.*' | sed 's/^\.\///g' | sort
new
new1
new2
new3
new3.md
new.md
package.json
Untitled Document 1
Untitled Document 2

Notes:

  • . : current folder
  • remove -maxdepth 1 to search recursively
  • -type f : find files, not directories (d)
  • -not -path '*/\.*' : do not return .hidden_files
  • sed 's/^\.\///g' : remove the prepended ./ from the result list

Java, How to implement a Shift Cipher (Caesar Cipher)

Two ways to implement a Caesar Cipher:

Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.

Option 2: Use a Map map each letter to a digit like this.

A - 0
B - 1
C - 2
etc...

With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.

CSS way to horizontally align table

Steven is right, in theory:

the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:

table
{ 
    margin-left: auto;
    margin-right: auto;
}

But the article mentioned in the beginning of this answer gives you all the other way to center a table.

An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:

div.centered 
{
    text-align: center;
}

div.centered table 
{
    margin: 0 auto; 
    text-align: left;
}


<div class="centered">
    <table>
    …
    </table>
</div>

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

Found a swap file by the name

I've also had this error when trying to pull the changes into a branch which is not created from the upstream branch from which I'm trying to pull.

Eg - This creates a new branch matching night-version of upstream

git checkout upstream/night-version -b testnightversion

This creates a branch testmaster in local which matches the master branch of upstream.

git checkout upstream/master -b testmaster 

Now if I try to pull the changes of night-version into testmaster branch leads to this error.

git pull upstream night-version //while I'm in `master` cloned branch

I managed to solve this by navigating to proper branch and pull the changes.

git checkout testnightversion
git pull upstream night-version // works fine.

Error: Cannot access file bin/Debug/... because it is being used by another process

Run taskmanager.
Locate netcore and delete it.
You can then delete the file manually or by running Clean.

Socket.IO handling disconnect event

Create a Map or a Set, and using "on connection" event set to it each connected socket, in reverse "once disconnect" event delete that socket from the Map we created earlier

import * as Server from 'socket.io';

const io = Server();
io.listen(3000);

const connections = new Set();

io.on('connection', function (s) {

  connections.add(s);

  s.once('disconnect', function () {
    connections.delete(s);
  });

});

How to use the addr2line command in Linux?

Try adding the -f option to show the function names :

addr2line -f -e a.out 0x4005BDC

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

SyntaxError: Cannot use import statement outside a module

Recently have the issue. The fix which work for me was to added this to babel.config.json in the plugins section

["@babel/plugin-transform-modules-commonjs", {
    "allowTopLevelThis": true,
    "loose": true,
    "lazy": true
  }],

I had some imported module with // and the error "cannot use import outside a module".

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

How to set the width of a RaisedButton in Flutter?

we use Row or Column, Expanded, Container and the element to use example RaisedButton

 body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10.0),
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.blue,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Copy'),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.green,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Paste'),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

Color Tint UIButton Image

Custom Buttons appear in their respective image colors. Setting the button type to "System" in the storyboard (or to UIButtonTypeSystem in code), will render the button's image with the default tint color.

Button Type System Renders Icons tinted

(tested on iOS9, Xcode 7.3)

Verify External Script Is Loaded

Merging several answers from above into an easy to use function

function GetScriptIfNotLoaded(scriptLocationAndName)
{
  var len = $('script[src*="' + scriptLocationAndName +'"]').length;

  //script already loaded!
  if (len > 0)
      return;

  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = scriptLocationAndName;
  head.appendChild(script);
}

How to get the current time in milliseconds from C in Linux?

C11 timespec_get

It returns up to nanoseconds, rounded to the resolution of the implementation.

It is already implemented in Ubuntu 15.10. API looks the same as the POSIX clock_gettime.

#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
    time_t   tv_sec;        /* seconds */
    long     tv_nsec;       /* nanoseconds */
};

More details here: https://stackoverflow.com/a/36095407/895245

Conversion failed when converting the nvarchar value ... to data type int

I got this error when I used a where clause which looked at a nvarchar field but didn't use single quotes.

My invalid SQL query looked like this:

SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = 13028533)

This didn't work since the Number column had the data type nvarchar. It wasn't an int as I first thought.

I changed it to:

SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = '13028533')

And it worked.

byte[] to hex string

Here is a extension method for byte array (byte[]), e.g.,

var b = new byte[] { 15, 22, 255, 84, 45, 65, 7, 28, 59, 10 };
Console.WriteLine(b.ToHexString());


public static class HexByteArrayExtensionMethods
{
    private const int AllocateThreshold = 256;
    private const string UpperHexChars = "0123456789ABCDEF";
    private const string LowerhexChars = "0123456789abcdef";
    private static string[] upperHexBytes;
    private static string[] lowerHexBytes;

    public static string ToHexString(this byte[] value)
    {
        return ToHexString(value, false);
    }

    public static string ToHexString(this byte[] value, bool upperCase)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }

        if (value.Length == 0)
        {
            return string.Empty;
        }

        if (upperCase)
        {
            if (upperHexBytes != null)
            {
                return ToHexStringFast(value, upperHexBytes);
            }

            if (value.Length > AllocateThreshold)
            {
                return ToHexStringFast(value, UpperHexBytes);
            }

            return ToHexStringSlow(value, UpperHexChars);
        }

        if (lowerHexBytes != null)
        {
            return ToHexStringFast(value, lowerHexBytes);
        }

        if (value.Length > AllocateThreshold)
        {
            return ToHexStringFast(value, LowerHexBytes);
        }

        return ToHexStringSlow(value, LowerhexChars);
    }

    private static string ToHexStringSlow(byte[] value, string hexChars)
    {
        var hex = new char[value.Length * 2];
        int j = 0;

        for (var i = 0; i < value.Length; i++)
        {
            var b = value[i];
            hex[j++] = hexChars[b >> 4];
            hex[j++] = hexChars[b & 15];
        }

        return new string(hex);
    }

    private static string ToHexStringFast(byte[] value, string[] hexBytes)
    {
        var hex = new char[value.Length * 2];
        int j = 0;

        for (var i = 0; i < value.Length; i++)
        {
            var s = hexBytes[value[i]];
            hex[j++] = s[0];
            hex[j++] = s[1];
        }

        return new string(hex);
    }

    private static string[] UpperHexBytes
    {
        get
        {
            return (upperHexBytes ?? (upperHexBytes = new[] {
                "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
                "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
                "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
                "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
                "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
                "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
                "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
                "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
                "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
                "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
                "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
                "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
                "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
                "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
                "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
                "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" }));
        }
    }

    private static string[] LowerHexBytes
    {
        get
        {
            return (lowerHexBytes ?? (lowerHexBytes = new[] {
                "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
                "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
                "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
                "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
                "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
                "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
                "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
                "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
                "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
                "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
                "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
                "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
                "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
                "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
                "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
                "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff" }));
        }
    }
}

Can I delete a git commit but keep the changes?

There are two ways of handling this. Which is easier depends on your situation

Reset

If the commit you want to get rid of was the last commit, and you have not done any additional work you can simply use git-reset

git reset HEAD^

Takes your branch back to the commit just before your current HEAD. However, it doesn't actually change the files in your working tree. As a result, the changes that were in that commit show up as modified - its like an 'uncommit' command. In fact, I have an alias to do just that.

git config --global alias.uncommit 'reset HEAD^'

Then you can just used git uncommit in the future to back up one commit.

Squashing

Squashing a commit means combining two or more commits into one. I do this quite often. In your case you have a half done feature commited, and then you would finish it off and commit again with the proper, permanent commit message.

git rebase -i <ref>

I say above because I want to make it clear this could be any number of commits back. Run git log and find the commit you want to get rid of, copy its SHA1 and use it in place of <ref>. Git will take you into interactive rebase mode. It will show all the commits between your current state and whatever you put in place of <ref>. So if <ref> is 10 commits ago, it will show you all 10 commits.

In front of each commit, it will have the word pick. Find the commit you want to get rid of and change it from pick to fixup or squash. Using fixup simply discards that commits message and merges the changes into its immediate predecessor in the list. The squash keyword does the same thing, but allows you to edit the commit message of the newly combined commit.

Note that the commits will be re-committed in the order they show up on the list when you exit the editor. So if you made a temporary commit, then did other work on the same branch, and completed the feature in a later commit, then using rebase would allow you to re-sort the commits and squash them.

WARNING:

Rebasing modifies history - DONT do this to any commits you have already shared with other developers.

Stashing

In the future, to avoid this problem consider using git stash to temporarily store uncommitted work.

git stash save 'some message'

This will store your current changes off to the side in your stash list. Above is the most explicit version of the stash command, allowing for a comment to describe what you are stashing. You can also simply run git stash and nothing else, but no message will be stored.

You can browse your stash list with...

git stash list

This will show you all your stashes, what branches they were done on, and the message and at the beginning of each line, and identifier for that stash which looks like this stash@{#} where # is its position in the array of stashes.

To restore a stash (which can be done on any branch, regardless of where the stash was originally created) you simply run...

git stash apply stash@{#}

Again, there # is the position in the array of stashes. If the stash you want to restore is in the 0 position - that is, if it was the most recent stash. Then you can just run the command without specifying the stash position, git will assume you mean the last one: git stash apply.

So, for example, if I find myself working on the wrong branch - I may run the following sequence of commands.

git stash
git checkout <correct_branch>
git stash apply

In your case you moved around branches a bit more, but the same idea still applies.

Hope this helps.

The property 'value' does not exist on value of type 'HTMLElement'

Problem:

error Property 'text' does not exist on type 'HTMLElement'

Solution: in typeScript we need to cast document.getElementById() which returns type HTMLElement in < HTMLScriptElement >

So we can do it by by following way to resolve the error as expected by typescript.js

Code: var content: string = ( < HTMLScriptElement > document.getElementById(contentId)).text;

It worked for me.. hope it works for you as well.

How to filter files when using scp to copy dir recursively?

I'd probably recommend using something like rsync for this due to its include and exclude flags, e.g:-

rsync -rav -e ssh --include '*/' --include='*.class' --exclude='*' \
server:/usr/some/unknown/number/of/sub/folders/ \ 
/usr/project/backup/some/unknown/number/of/sub/folders/

Some other useful flags:

  • -r for recursive
  • -a for archive (mostly all files)
  • -v for verbose output
  • -e to specify ssh instead of the default (which should be ssh, actually)

What's the difference between emulation and simulation?

I was confused between the two processes. I found this simple explaination about the difference between Emulators and Simulators

  1. Simulator:
    Suppose you have written assembly program in a file and corresponding exe file is ready. The simulator is the pc software which reads the instructions from the exe and 'minmics' the operation of the processor.

  2. Emulator:
    Emulator is a (PC software + a processor). The Processor can be plugged into the TARGET BOARD when you want to test the developed software in real time to check run time bugs. When not in use it can be unplugged. The Processor will have a parallel or JTAG interface with the PC for downloading the exe file for execution.

Hence, whereas the Simulator is slow in execution, Emulator will be able to give real time verification of the developed code. Generally you will test your developed code on simulator first and then go for checking on emulator.

source : http://www.dsprelated.com/groups/c6x/show/148.php

How to make a transparent HTML button?

The solution is pretty easy actually:

<button style="border:1px solid black; background-color: transparent;">Test</button>

This is doing an inline style. You're defining the border to be 1px, solid line, and black in color. The background color is then set to transparent.


UPDATE

Seems like your ACTUAL question is how do you prevent the border after clicking on it. That can be resolved with a CSS pseudo selector: :active.

button {
    border: none;
    background-color: transparent;
    outline: none;
}
button:focus {
    border: none;
}

JSFiddle Demo

How do you build a Singleton in Dart?

Here's a concise example that combines the other solutions. Accessing the singleton can be done by:

  • Using a singleton global variable that points to the instance.
  • The common Singleton.instance pattern.
  • Using the default constructor, which is a factory that returns the instance.

Note: You should implement only one of the three options so that code using the singleton is consistent.

Singleton get singleton => Singleton.instance;
ComplexSingleton get complexSingleton => ComplexSingleton._instance;

class Singleton {
  static final Singleton instance = Singleton._private();
  Singleton._private();
  factory Singleton() => instance;
}

class ComplexSingleton {
  static ComplexSingleton _instance;
  static ComplexSingleton get instance => _instance;
  static void init(arg) => _instance ??= ComplexSingleton._init(arg);

  final property;
  ComplexSingleton._init(this.property);
  factory ComplexSingleton() => _instance;
}

If you need to do complex initialization, you'll just have to do so before using the instance later in the program.

Example

void main() {
  print(identical(singleton, Singleton.instance));        // true
  print(identical(singleton, Singleton()));               // true
  print(complexSingleton == null);                        // true
  ComplexSingleton.init(0); 
  print(complexSingleton == null);                        // false
  print(identical(complexSingleton, ComplexSingleton())); // true
}

Create table with jQuery - append

Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HTML Masterpage</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

        <script type="text/javascript">
            function nav() {
                var menuHTML= '<ul><li><a href="#">link 1</a></li></ul><ul><li><a href="#">link 2</a></li></ul>';
                $('#menu').append(menuHTML);
            }
        </script>

        <style type="text/css">
        </style>
    </head>
    <body onload="nav()">
        <div id="menu"></div>
    </body>
    </html>

Redirecting to a new page after successful login

Just add the following code after the final message you give using PHP code

Print'window.location.assign("index.php")

How can I call a WordPress shortcode within a template?

echo do_shortcode('[CONTACT-US-FORM]');

Use this in your template.

Look here for more: Do Shortcode

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

Had the same problem, I just coerced the id into a string.

My schema:

const product = new mongooseClient.Schema({
    retailerID: { type: mongoose.SchemaTypes.ObjectId, required: true, index: true }
});

And then, when inserting:

retailerID: `${retailer._id}`

What is the difference between the dot (.) operator and -> in C++?

It's simple, whenever you see

 x->y

know it is the same as

 (*x).y

data.map is not a function

this.$http.get('https://pokeapi.co/api/v2/pokemon')
.then(response => {
   if(response.status === 200)
   {
      this.usuarios = response.data.results.map(usuario => {
      return { name: usuario.name, url: usuario.url, captched: false } })
          }
    })
.catch( error => { console.log("Error al Cargar los Datos: " + error ) } )

Can I use GDB to debug a running process?

If one want to attach a process, this process must have the same owner. The root is able to attach to any process.

Compiling and Running Java Code in Sublime Text 2

Make sure u install JDK/JRE first.

If you are mac user than follow this steps:

open terminal go to your root dictionary by typing

cd ..

repeatedly. use

ls

to see if u have reach the root

you will see Library folder Now follow this path Library/Java/JVM/bin Once you get into bin you can see JavaC file

Now u need to get the path of this folder for that just write this command

pwd

Copy paste it to your sublime JavaC file and build java code in sublime by cmd+b.

Convert number of minutes into hours & minutes using PHP

<?php

function convertToHoursMins($time, $format = '%02d:%02d') {
    if ($time < 1) {
        return;
    }
    $hours = floor($time / 60);
    $minutes = ($time % 60);
    return sprintf($format, $hours, $minutes);
}

echo convertToHoursMins(250, '%02d hours %02d minutes'); // should output 4 hours 17 minutes

Pass entire form as data in jQuery Ajax function

serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.

Suppose that we have a form with this id : "myform".

the better solution is to make a FormData and send it:

    var myform = document.getElementById("myform");
    var fd = new FormData(myform );
    $.ajax({
        url: "example.php",
        data: fd,
        cache: false,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (dataofconfirm) {
            // do something with the result
        }
    });

Java switch statement: Constant expression required, but it IS constant

In my case, I was getting this exception because

switch (tipoWebServ) {
                            case VariablesKmDialog.OBTENER_KM:
                                resultObtenerKm(result);
                                break;
                            case var.MODIFICAR_KM:
                                resultModificarKm(result);
                                break;
                        }

in the second case I was calling the constant from the instance var.MODIFICAR_KM: but I should use VariablesKmDialog.OBTENER_KM directly from the class.

Import PEM into Java Key Store

There is also a GUI tool that allows visual JKS creation and certificates importing.

http://portecle.sourceforge.net/

Portecle is a user friendly GUI application for creating, managing and examining keystores, keys, certificates, certificate requests, certificate revocation lists and more.

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

Best way to reset an Oracle sequence to the next value in an existing column?

If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):

DECLARE
  last_used  NUMBER;
  curr_seq   NUMBER;
BEGIN
  SELECT MAX(pk_val) INTO last_used FROM your_table;

  LOOP
    SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
    IF curr_seq >= last_used THEN EXIT;
    END IF;
  END LOOP;
END;

This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...

Server unable to read htaccess file, denying access to be safe

In my case apache was somehow configured wrong(?) so I had to set permissions to all parent dirs too. Just setting permission to .htaccess (and it's parent dir) didn't work.

DB2 Timestamp select statement

You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.

SELECT * FROM <table_name> WHERE id = 1 
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';

If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':

hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')

onchange event on input type=range is not triggering in firefox while dragging

You could use the JavaScript "ondrag" event to fire continuously. It is better than "input" due to the following reasons:

  1. Browser support.

  2. Could differentiate between "ondrag" and "change" event. "input" fires for both drag and change.

In jQuery:

$('#sample').on('drag',function(e){

});

Reference: http://www.w3schools.com/TAgs/ev_ondrag.asp

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

How to sort an ArrayList?

You can use Collections.sort(list) to sort list if your list contains Comparable elements. Otherwise I would recommend you to implement that interface like here:

public class Circle implements Comparable<Circle> {}

and of course provide your own realization of compareTo method like here:

@Override
    public int compareTo(Circle another) {
        if (this.getD()<another.getD()){
            return -1;
        }else{
            return 1;
        }
    }

And then you can again use Colection.sort(list) as now list contains objects of Comparable type and can be sorted. Order depends on compareTo method. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html for more detailed information.

REST API - Use the "Accept: application/json" HTTP Header

Basically I use Fiddler or Postman for testing API's.

In fiddler, in request header you need to specify instead of xml, html you need to change it to json. Eg: Accept: application/json. That should do the job.

Python: TypeError: object of type 'NoneType' has no len()

shuffle(names) is an in-place operation. Drop the assignment.

This function returns None and that's why you have the error:

TypeError: object of type 'NoneType' has no len()

Double Iteration in List Comprehension

To answer your question with your own suggestion:

>>> [x for b in a for x in b] # Works fine

While you asked for list comprehension answers, let me also point out the excellent itertools.chain():

>>> from itertools import chain
>>> list(chain.from_iterable(a))
>>> list(chain(*a)) # If you're using python < 2.6

Caching a jquery ajax response in javascript/browser

        function getDatas() {
            let cacheKey = 'memories';

            if (cacheKey in localStorage) {
                let datas = JSON.parse(localStorage.getItem(cacheKey));

                // if expired
                if (datas['expires'] < Date.now()) {
                    localStorage.removeItem(cacheKey);

                    getDatas()
                } else {
                    setDatas(datas);
                }
            } else {
                $.ajax({
                    "dataType": "json",
                    "success": function(datas, textStatus, jqXHR) {
                        let today = new Date();

                        datas['expires'] = today.setDate(today.getDate() + 7) // expires in next 7 days

                        setDatas(datas);

                        localStorage.setItem(cacheKey, JSON.stringify(datas));
                    },
                    "url": "http://localhost/phunsanit/snippets/PHP/json.json_encode.php",
                });
            }
        }

        function setDatas(datas) {
            // display json as text
            $('#datasA').text(JSON.stringify(datas));

            // your code here
           ....

        }

        // call
        getDatas();

enter link description here

XAMPP Port 80 in use by "Unable to open process" with PID 4

So I have faced the same problem when trying to start apache service and I would like to share my solutions with you. Here is some notes about services or programs that may use port 80:

  1. Skype: skype uses port 80/443 by default. You can change this from tools->options-> advanced->connections and disable checkbox "use port 80 and 443 for addtional incoming connections".
  2. IIS: IIS uses port 80 be default so you need to shut down it. You can use the following two commands net stop w3svc net stop iisadmin
  3. SQL Server Reporting Service: You need to stop this service because it may take port 80 if IIS is not running. Go to local services and stop it.

These options work great with me and I can start apache service without errors.

The other option is to change apache listen port from httpd.conf and set another port number.

Hope this solution helps anyone who face the same problem again.

JUnit Testing Exceptions

are you sure you told it to expect the exception?

for newer junit (>= 4.7), you can use something like (from here)

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testRodneCisloRok(){
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("error1");
    new RodneCislo("891415",dopocitej("891415"));
}

and for older junit, this:

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
  int i = 1/0;
}

How do I call a dynamically-named method in Javascript?

Try with this:

var fn_name = "Colours",
fn = eval("populate_"+fn_name);
fn(args1,argsN);

Multiprocessing: How to use Pool.map on a function defined in a class?

You can run your code without any issues if you somehow manually ignore the Pool object from the list of objects in the class because it is not pickleable as the error says. You can do this with the __getstate__ function (look here too) as follow. The Pool object will try to find the __getstate__ and __setstate__ functions and execute them if it finds it when you run map, map_async etc:

class calculate(object):
    def __init__(self):
        self.p = Pool()
    def __getstate__(self):
        self_dict = self.__dict__.copy()
        del self_dict['p']
        return self_dict
    def __setstate__(self, state):
        self.__dict__.update(state)

    def f(self, x):
        return x*x
    def run(self):
        return self.p.map(self.f, [1,2,3])

Then do:

cl = calculate()
cl.run()

will give you the output:

[1, 4, 9]

I've tested the above code in Python 3.x and it works.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

Have you googled about it - insert update delete access vb.net, there are lots of reference about this.

Insert Update Delete Navigation & Searching In Access Database Using VB.NET

  • Create Visual Basic 2010 Project: VB-Access
  • Assume that, we have a database file named data.mdb
  • Place the data.mdb file into ..\bin\Debug\ folder (Where the project executable file (.exe) is placed)

what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB

is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.

it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:

Example code snippet:

Imports System
Imports System.Data
Imports System.Data.OleDb

Public Class DBUtil

 Private connectionString As String

 Public Sub New()

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=d:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource

 End Sub

 Public Function GetCategories() As DataSet

  Dim query As String = "SELECT * FROM Categories"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Categories")

 End Function

 Public SubUpdateCategories(ByVal name As String)
  Dim query As String = "update Categories set name = 'new2' where name = ?"
  Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
  Return FillDataSet(cmd, "Categories")

 End Sub

 Public Function GetItems() As DataSet

  Dim query As String = "SELECT * FROM Items"
  Dim cmd As New OleDbCommand(query)
  Return FillDataSet(cmd, "Items")

 End Function

 Public Function GetItems(ByVal categoryID As Integer) As DataSet

  'Create the command.
  Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
  Dim cmd As New OleDbCommand(query)
  cmd.Parameters.AddWithValue("category_ID", categoryID)

  'Fill the dataset.
  Return FillDataSet(cmd, "Items")

 End Function

 Public Sub AddCategory(ByVal name As String)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Categories "
  insertSQL &= "VALUES(?)"
  Dim cmd As New OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Name", name)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Public Sub AddItem(ByVal title As String, ByVal description As String, _
    ByVal price As Decimal, ByVal categoryID As Integer)

  Dim con As New OleDbConnection(connectionString)

  'Create the command.
  Dim insertSQL As String = "INSERT INTO Items "
  insertSQL &= "(Title, Description, Price, Category_ID)"
  insertSQL &= "VALUES (?, ?, ?, ?)"
  Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
  cmd.Parameters.AddWithValue("Title", title)
  cmd.Parameters.AddWithValue("Description", description)
  cmd.Parameters.AddWithValue("Price", price)
  cmd.Parameters.AddWithValue("CategoryID", categoryID)

  Try
   con.Open()
   cmd.ExecuteNonQuery()
  Finally
   con.Close()
  End Try

 End Sub

 Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet

  Dim con As New OleDb.OleDbConnection
  Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
  Dim dbSource = "Data Source=D:\DB\Database11.accdb"

  connectionString = dbProvider & dbSource
  con.ConnectionString = connectionString
  cmd.Connection = con
  Dim adapter As New OleDbDataAdapter(cmd)
  Dim ds As New DataSet()

  Try
   con.Open()
   adapter.Fill(ds, tableName)
  Finally
   con.Close()
  End Try
  Return ds

 End Function

End Class

Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back

Why AVD Manager options are not showing in Android Studio

I had installed Android studio and was not able to access the AVD Manager directly. I had to follow the steps as mentioned below:

  1. Created a blank project using Android Studio
  2. Once the Project is ready to use I tried open action using the shortcut ctrl+shift+a option and searched for AVD Manager AVD Manager
  3. On double clicking the AVD Manager I got a few errors in console about the missing libararies along with the link to install the neccessary dependencies. On clicking the links which was displayed with the error message few packages which were needed were installed. Once all the required packages were installed the AVD Manager icon becomes active.

enter image description here

Confused about stdin, stdout and stderr?

stdin

Reads input through the console (e.g. Keyboard input). Used in C with scanf

scanf(<formatstring>,<pointer to storage> ...);

stdout

Produces output to the console. Used in C with printf

printf(<string>, <values to print> ...);

stderr

Produces 'error' output to the console. Used in C with fprintf

fprintf(stderr, <string>, <values to print> ...);

Redirection

The source for stdin can be redirected. For example, instead of coming from keyboard input, it can come from a file (echo < file.txt ), or another program ( ps | grep <userid>).

The destinations for stdout, stderr can also be redirected. For example stdout can be redirected to a file: ls . > ls-output.txt, in this case the output is written to the file ls-output.txt. Stderr can be redirected with 2>.

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text != "something")
        e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

setting JAVA_HOME & CLASSPATH in CentOS 6

I created a folder named a in /home/prasanth and copied your code to a file named A.java. I compiled from /home/prasanth as javac a/A.java and run javac a.A. I got output as

a!

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

How to check if a file exists in the Documents directory in Swift?

For the benefit of Swift 3 beginners:

  1. Swift 3 has done away with most of the NextStep syntax
  2. So NSURL, NSFilemanager, NSSearchPathForDirectoriesInDomain are no longer used
  3. Instead use URL and FileManager
  4. NSSearchPathForDirectoriesInDomain is not needed
  5. Instead use FileManager.default.urls

Here is a code sample to verify if a file named "database.sqlite" exists in application document directory:

func findIfSqliteDBExists(){

    let docsDir     : URL       = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let dbPath      : URL       = docsDir.appendingPathComponent("database.sqlite")
    let strDBPath   : String    = dbPath.path
    let fileManager : FileManager   = FileManager.default

    if fileManager.fileExists(atPath:strDBPath){
        print("An sqlite database exists at this path :: \(strDBPath)")
    }else{
        print("SQLite NOT Found at :: \(strDBPath)")
    }

}

Parsing HTML using Python

Here you can read more about different HTML parsers in Python and their performance. Even though the article is a bit dated it still gives you a good overview.

Python HTML parser performance

I'd recommend BeautifulSoup even though it isn't built in. Just because it's so easy to work with for those kinds of tasks. Eg:

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)

x = soup.body.find('div', attrs={'class' : 'container'}).text

Https Connection Android

This is what I am doing. It simply doesn't check the certificate anymore.

// always verify the host - dont check for certificate
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

/**
 * Trust every server - dont check for any certificate
 */
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain,
                String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain,
                String authType) throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection
                .setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and

    HttpURLConnection http = null;

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
        https.setHostnameVerifier(DO_NOT_VERIFY);
        http = https;
    } else {
        http = (HttpURLConnection) url.openConnection();
    }

Serializing and submitting a form with jQuery and PHP

The problem can be PHP configuration:

Please check the setting max_input_vars in the php.ini file.

Try to increase the value of this setting to 5000 as example.

max_input_vars = 5000

Then restart your web-server and try.

how to download image from any web page in java

This works for me:

URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg");
InputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream("Image-Porkeri_001.jpg"));

for ( int i; (i = in.read()) != -1; ) {
    out.write(i);
}
in.close();
out.close();

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

This question helped me identify the problem of why phpMyAdmin refused me grid-edit-etc. on some tables. I just had forgotten to declare my primary key and was overseeing it in my "Why the hell should this table be different from its neighbours" solution search process...

I just wanted to react on following in OP self-answer:

The other table had multiple AI int values that were the Primary field, but there were multiple values of the same kind.

The simple fix for this was to just add a column to the end of the table as Unique AI Int. Basically all MySQL is saying is it needs a unique value in each record to differentiate the rows.

This was actually my case, but there's absolutely no need to add any column: if your primary key is the combination of 2 fields (ex. junction table in many to many relationship), then simply declare it as such:
- eiter in phpyAdmin, just enter "2" in "Create an index on [x] columns", then select your 2 columns
- or ALTER TABLE mytable ADD PRIMARY KEY(mycol1,mycol2)

How to make g++ search for header files in a specific directory?

gcc -I/path -L/path
  • -I /path path to include, gcc will find .h files in this path

  • -L /path contains library files, .a, .so

How to implement static class member functions in *.cpp file?

Try this:

header.hxx:

class CFoo
{
public: 
    static bool IsThisThingOn();
};

class.cxx:

#include "header.hxx"
bool CFoo::IsThisThingOn() // note: no static keyword here
{
    return true;
}