Programs & Examples On #Buildroot

Buildroot is a set of Makefiles and patches that makes it easy to generate a complete embedded Linux system, from the cross-compilation toolchain to the complete image for flashing.

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

How to center-justify the last line of text in CSS?

You can also split the element into two via HTML + JS.

HTML:

<div class='justificator'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a 
type specimen book.
</div>

JS:

function justify() {
    // Query for elements search
    let arr = document.querySelectorAll('.justificator');
    for (let current of arr) {
        let oldHeight = current.offsetHeight;
        // Stores cut part
        let buffer = '';

        if (current.innerText.lastIndexOf(' ') >= 0) {
            while (current.offsetHeight == oldHeight) {
                let lastIndex = current.innerText.lastIndexOf(' ');
                buffer = current.innerText.substring(lastIndex) + buffer;
                current.innerText = current.innerText.substring(0, lastIndex);
            }
            let sibling = current.cloneNode(true);
            sibling.innerText = buffer;
            sibling.classList.remove('justificator');
            // Center
            sibling.style['text-align'] = 'center';


            current.style['text-align'] = 'justify';
            // For devices that do support text-align-last
            current.style['text-align-last'] = 'justify';
            // Insert new element after current
            current.parentNode.insertBefore(sibling, current.nextSibling);
        }
    }
}
document.addEventListener("DOMContentLoaded", justify);

Here is an example with div and p tags

_x000D_
_x000D_
function justify() {_x000D_
    // Query for elements search_x000D_
    let arr = document.querySelectorAll('.justificator');_x000D_
    for (let current of arr) {_x000D_
        let oldHeight = current.offsetHeight;_x000D_
        // Stores cut part_x000D_
        let buffer = '';_x000D_
_x000D_
        if (current.innerText.lastIndexOf(' ') >= 0) {_x000D_
            while (current.offsetHeight == oldHeight) {_x000D_
                let lastIndex = current.innerText.lastIndexOf(' ');_x000D_
                buffer = current.innerText.substring(lastIndex) + buffer;_x000D_
                current.innerText = current.innerText.substring(0, lastIndex);_x000D_
            }_x000D_
            let sibling = current.cloneNode(true);_x000D_
            sibling.innerText = buffer;_x000D_
            sibling.classList.remove('justificator');_x000D_
            // Center_x000D_
            sibling.style['text-align'] = 'center';_x000D_
            // For devices that do support text-align-last_x000D_
            current.style['text-align-last'] = 'justify';_x000D_
            current.style['text-align'] = 'justify';_x000D_
            // Insert new element after current_x000D_
            current.parentNode.insertBefore(sibling, current.nextSibling);_x000D_
        }_x000D_
    }_x000D_
}_x000D_
justify();
_x000D_
p.justificator {_x000D_
    margin-bottom: 0px;_x000D_
}_x000D_
p.justificator + p {_x000D_
    margin-top: 0px;_x000D_
}
_x000D_
<div class='justificator'>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
<p class='justificator'>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</p><p>Some other text</p>
_x000D_
_x000D_
_x000D_ Disadvantage: doesn't work when page width changes dynamically.

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

How to add Drop-Down list (<select>) programmatically?

This will work (pure JS, appending to a div of id myDiv):

Demo: http://jsfiddle.net/4pwvg/

_x000D_
_x000D_
var myParent = document.body;_x000D_
_x000D_
//Create array of options to be added_x000D_
var array = ["Volvo","Saab","Mercades","Audi"];_x000D_
_x000D_
//Create and append select list_x000D_
var selectList = document.createElement("select");_x000D_
selectList.id = "mySelect";_x000D_
myParent.appendChild(selectList);_x000D_
_x000D_
//Create and append the options_x000D_
for (var i = 0; i < array.length; i++) {_x000D_
    var option = document.createElement("option");_x000D_
    option.value = array[i];_x000D_
    option.text = array[i];_x000D_
    selectList.appendChild(option);_x000D_
}
_x000D_
_x000D_
_x000D_

How can I remove a style added with .css() function?

Try This

$(".ClassName").css('color','');
Or 
$("#Idname").css('color','');

pandas dataframe convert column type to string or categorical

With pandas >= 1.0 there is now a dedicated string datatype:

1) You can convert your column to this pandas string datatype using .astype('string'):

df['zipcode'] = df['zipcode'].astype('string')

2) This is different from using str which sets the pandas object datatype:

df['zipcode'] = df['zipcode'].astype(str)

3) For changing into categorical datatype use:

df['zipcode'] = df['zipcode'].astype('category')

You can see this difference in datatypes when you look at the info of the dataframe:

df = pd.DataFrame({
    'zipcode_str': [90210, 90211] ,
    'zipcode_string': [90210, 90211],
    'zipcode_category': [90210, 90211],
})

df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')

df.info()

# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
 #   Column            Non-Null Count  Dtype   
---  ------            --------------  -----   
 0   zipcode_str       2 non-null      object  
 1   zipcode_string    2 non-null      string  
 2   zipcode_category  2 non-null      category
dtypes: category(1), object(1), string(1)

From the docs:

The 'string' extension type solves several issues with object-dtype NumPy arrays:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than string.

More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

Connect over ssh using a .pem file

chmod 400 mykey.pem

ssh -i mykey.pem [email protected]

Will connect you over ssh using a .pem file to any server.

Recover unsaved SQL query scripts

SSMSBoost add-in (currently free)

  • keeps track on all executed statements (saves them do disk)
  • regulary saves snapshot of SQL Editor contents. You keep history of the modifications of your script. Sometimes "the best" version is not the last and you want to restore the intermediate state.
  • keeps track of opened tabs and allows to restore them after restart. Unsaved tabs are also restored.

+tons of other features. (I am the developer of the add-in)

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

What is the difference between fastcgi and fpm?

FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.

Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).

Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.

Connecting to a network folder with username/password in Powershell

This is not a PowerShell-specific answer, but you could authenticate against the share using "NET USE" first:

net use \\server\share /user:<domain\username> <password>

And then do whatever you need to do in PowerShell...

How can I call the 'base implementation' of an overridden virtual method?

You can't do it by C#, but you can edit MSIL.

IL code of your Main method:

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] class MsilEditing.A a)
    L_0000: nop 
    L_0001: newobj instance void MsilEditing.B::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: callvirt instance void MsilEditing.A::X()
    L_000d: nop 
    L_000e: ret 
}

You should change opcode in L_0008 from callvirt to call

L_0008: call instance void MsilEditing.A::X()

Can someone explain how to implement the jQuery File Upload plugin?

Check out the Image drag and drop uploader with image preview using dropper jquery plugin.

HTML

<div class="target" width="78" height="100"><img /></div>

JS

$(".target").dropper({
    action: "upload.php",

}).on("start.dropper", onStart);
function onStart(e, files){
console.log(files[0]);

    image_preview(files[0].file).then(function(res){
$('.dropper-dropzone').empty();
//$('.dropper-dropzone').css("background-image",res.data);
 $('#imgPreview').remove();        
$('.dropper-dropzone').append('<img id="imgPreview"/><span style="display:none">Drag and drop files or click to select</span>');
var widthImg=$('.dropper-dropzone').attr('width');
        $('#imgPreview').attr({width:widthImg});
    $('#imgPreview').attr({src:res.data});

    })

}

function image_preview(file){
    var def = new $.Deferred();
    var imgURL = '';
    if (file.type.match('image.*')) {
        //create object url support
        var URL = window.URL || window.webkitURL;
        if (URL !== undefined) {
            imgURL = URL.createObjectURL(file);
            URL.revokeObjectURL(file);
            def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
        }
        //file reader support
        else if(window.File && window.FileReader)
        {
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function () {
                imgURL = reader.result;
                def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
            }
        }
        else {
            def.reject({status: 1001, message: 'File uploader not supported', data:imgURL, error: {}});
        }
    }
    else
        def.reject({status: 1002, message: 'File type not supported', error: {}});
    return def.promise();
}

$('.dropper-dropzone').mouseenter(function() {
 $( '.dropper-dropzone>span' ).css("display", "block");
});

$('.dropper-dropzone').mouseleave(function() {
 $( '.dropper-dropzone>span' ).css("display", "none");
});

CSS

.dropper-dropzone{
    width:78px;
padding:3px;
    height:100px;
position: relative;
}
.dropper-dropzone>img{
    width:78px;
    height:100px;
margin-top=0;
}

.dropper-dropzone>span {
    position: absolute;
    right: 10px;
    top: 20px;
color:#ccc;


}

.dropper .dropper-dropzone{

padding:3px !important    
}

Demo Jsfiddle

Best way to format multiple 'or' conditions in an if statement (Java)

I use this kind of pattern often. It's very compact:

// Define a constant in your class. Use a HashSet for performance
private static final Set<Integer> values = new HashSet<Integer>(Arrays.asList(12, 16, 19));

// In your method:
if (values.contains(x)) {
    ...
}

A HashSet is used here to give good look-up performance - even very large hash sets are able to execute contains() extremely quickly.

If performance is not important, you can code the gist of it into one line:

if (Arrays.asList(12, 16, 19).contains(x))

but know that it will create a new ArrayList every time it executes.

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Add your Maven bin path to the System variable as given below

Go to the

> Enviornment Variables > set Path=D:\apache-maven-3.2.1\bin

or if path is already set than append the path with ";"

restart command and try

Add/remove HTML inside div using JavaScript

please try following to generate

 function addRow()
    {
        var e1 = document.createElement("input");
        e1.type = "text";
        e1.name = "name1";

        var cont = document.getElementById("content")
        cont.appendChild(e1);

    }

Dart: mapping a list (list.map)

you can use

moviesTitles.map((title) => Tab(text: title)).toList()

example:

    bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) => Tab(text: title)).toList()
      ,
    ),

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Mail not sending with PHPMailer over SSL using SMTP

Firstly, use these settings for Google:

$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls"; //edited from tsl
$mail->Username = "myEmail";
$mail->Password = "myPassword";
$mail->Port = "587";

But also, what firewall have you got set up?

If you're filtering out TCP ports 465/995, and maybe 587, you'll need to configure some exceptions or take them off your rules list.

https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Python Checking a string's first and last character

When you say [:-1] you are stripping the last element. Instead of slicing the string, you can apply startswith and endswith on the string object itself like this

if str1.startswith('"') and str1.endswith('"'):

So the whole program becomes like this

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

Even simpler, with a conditional expression, like this

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

jquery AJAX and json format

$.ajax({
   type: "POST",
   url: hb_base_url + "consumer",
   contentType: "application/json",
   dataType: "json",
   data: {
       data__value = JSON.stringify(
       {
           first_name: $("#namec").val(),
           last_name: $("#surnamec").val(),
           email: $("#emailc").val(),
           mobile: $("#numberc").val(),
           password: $("#passwordc").val()
       })
   },
   success: function(response) {
       console.log(response);
   },
   error: function(response) {
       console.log(response);
   }
});

(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:

(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:

$test = json_decode( $_POST['data__value'] );
echo $test->first_name;

SELECT INTO USING UNION QUERY

select *
into new_table
from table_A
UNION
Select * 
From table_B

This only works if Table_A and Table_B have the same schemas

Counting Line Numbers in Eclipse

Under linux, the simpler is:

  1. go to the root folder of your project
  2. use find to do a recursive search of *.java files
  3. use wc -l to count lines:

To resume, just do:

find . -name '*.java' | xargs wc -l    

Add button to a layout programmatically

If you just have included a layout file at the beginning of onCreate() inside setContentView and want to get this layout to add new elements programmatically try this:

ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);

then you can create a new Button for example and just add it:

Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                                    LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);

Maven artifact and groupId naming

Consider following as for building basic first Maven application:

groupId

  • com.companyname.project

artifactId

  • project

version

  • 0.0.1

Excel Define a range based on a cell value

Based on answer by @Cici I give here a more generic solution:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

In Italian version of Excel:

=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))

Where B1-C2 cells hold these values:

  • A, 1
  • A, 5

You can change these valuese to change the final range at wish.


Splitting the formula in parts:

  • SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
  • CONCATENATE(B1,C1) - result is A1
  • INDIRECT(CONCATENATE(B1,C1)) - result is reference to A1

Hence:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

results in

=SUM(A1:A5)


I'll write down here a couple of SEO keywords for Italian users:

  • come creare dinamicamente l'indirizzo di un intervallo in excel
  • formula per definire un intervallo di celle in excel.

Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.

An invalid form control with name='' is not focusable

My scenario I hope not missed in this lengthy seed of answers was something really odd.

I have div elements that dynamically update through a dialogBox being called in them to load and get actioned in.

In short the div ids had

<div id="name${instance.username}"/>

I had a user: ???? and for some reason the encoding did some strange stuff in the java script world. I got this error message for a form working in other places.

Narrowed it down to this and a retest of using numeric numbers instead i.e id appears to fix the issue.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Both Encrypt and Decrypt with AES and DES Algoritham ,This worked for me perfectly GithubLink: Java Code For Encryption and Decryption

package decrypt;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/* Decrypt encrypted string into plain string with aes and Des algoritham*/ 

public class Decrypt {

public String decrypt(String str,String k) throws Exception {
// Decode base64 to get bytes

 Cipher  dcipher = Cipher.getInstance("AES");
 Key aesKey = new SecretKeySpec(k.getBytes(), "AES");
 dcipher.init(dcipher.DECRYPT_MODE, aesKey);
//System.out.println(aesKey);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
//System.out.println(utf8);
// Decode using utf-8
 return new String(utf8, "UTF8");
 }


  public String encrypt(String str,String k) throws Exception {
 Cipher ecipher = Cipher.getInstance("AES");
 Key aeskey = new SecretKeySpec(k.getBytes(),"AES");
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
 public String encrypt(String str,String k,String Algo) throws Exception {
 Cipher ecipher = Cipher.getInstance(Algo);
 Key aeskey = new SecretKeySpec(k.getBytes(),Algo);
 byte[] utf8 = str.getBytes("UTF8");
 ecipher.init(ecipher.ENCRYPT_MODE, aeskey );

 byte[] enc = ecipher.doFinal(utf8);

 return new sun.misc.BASE64Encoder().encode(enc);

}
public String decrypt(String str,String k,String Algo) throws Exception {
    // Decode base64 to get bytes

     Cipher  dcipher = Cipher.getInstance(Algo);
     Key aesKey = new SecretKeySpec(k.getBytes(), Algo);
     dcipher.init(dcipher.DECRYPT_MODE, aesKey);
    //System.out.println(aesKey);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    byte[] utf8 = dcipher.doFinal(dec);
    //System.out.println(utf8);
 // Decode using utf-8
     return new String(utf8, "UTF8");
  }

public static void main(String args []) throws Exception
{
    String original = "rakesh";
    String data = "CfPcX0G+e7TLKKMyyvrvrQ==";
    String k = "qertyuiopasdfghw"; //AES key length must be 16
    String k1 = "qertyuio";  // DES key length must be 8 
    String data1 = "rakesh";
    String data2 = "nAtvNq7uHKE=";
    String Algo= "DES";
    String Algo1= "AES";
    Decrypt decrypter = new Decrypt();
     System.out.println("Original String: " + original);

     System.out.println("encrypted String in DES: " + decrypter.encrypt(data1, 
      k1,Algo));
     System.out.println("Decrypted String in DES: " + decrypter.decrypt(data2, 
       k1,Algo));
     System.out.println("encrypted String in AES: " + decrypter.encrypt(data1, 
      k,Algo1));
     System.out.println("Decrypted String in AES: " + decrypter.decrypt(data, 
      k,Algo1));
   }
}

How to copy files from host to Docker container?

tar and docker cp are a good combo for copying everything in a directory.

Create a data volume container

docker create --name dvc --volume /path/on/container cirros

To preserve the directory hierarchy

tar -c -C /path/on/local/machine . | docker cp - dvc:/path/on/container

Check your work

docker run --rm --volumes-from dvc cirros ls -al /path/on/container

Change limit for "Mysql Row size too large"

The question has been asked on serverfault too.

You may want to take a look at this article which explains a lot about MySQL row sizes. It's important to note that even if you use TEXT or BLOB fields, your row size could still be over 8K (limit for InnoDB) because it stores the first 768 bytes for each field inline in the page.

The simplest way to fix this is to use the Barracuda file format with InnoDB. This basically gets rid of the problem altogether by only storing the 20 byte pointer to the text data instead of storing the first 768 bytes.


The method that worked for the OP there was:

  1. Add the following to the my.cnf file under [mysqld] section.

    innodb_file_per_table=1
    innodb_file_format = Barracuda
    
  2. ALTER the table to use ROW_FORMAT=COMPRESSED.

    ALTER TABLE nombre_tabla
        ENGINE=InnoDB
        ROW_FORMAT=COMPRESSED 
        KEY_BLOCK_SIZE=8;
    

There is a possibility that the above still does not resolve your issues. It is a known (and verified) bug with the InnoDB engine, and a temporary fix for now is to fallback to MyISAM engine as temporary storage. So, in your my.cnf file:

internal_tmp_disk_storage_engine=MyISAM

Delete a single record from Entity Framework?

Using EntityFramework.Plus could be an option:

dbContext.Employ.Where(e => e.Id == 1).Delete();

More examples are available here

JTable - Selected Row click event

I would recommend using Glazed Lists for this. It makes it very easy to map a data structure to a table model.

To react to the mouseclick on the JTable, use an ActionListener: ActionListener on JLabel or JTable cell

Header set Access-Control-Allow-Origin in .htaccess doesn't work

This should work:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

How can I flush GPU memory using CUDA (physical reset is unavailable)

First type

nvidia-smi

then select the PID that you want to kill

sudo kill -9 PID

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

1.On Child Widget : add parameter Function paramter

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : create a Function for the child to callback

refresh() {
  setState(() {});
}

3.On Parent Widget : pass parentFunction to Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget : call the Parent Function

  widget.notifyParent();

Database Diagram Support Objects cannot be Installed ... no valid owner

you must enter as administrator right click to microsofft sql server management studio and run as admin

The order of keys in dictionaries

Python 3.7+

In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.

Python 3.6 (CPython)

As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.

Python >=2.7 and <3.6

Use the collections.OrderedDict class when you need a dict that remembers the order of items inserted.

Find the max of 3 numbers in Java with different data types

You can do like this:

public static void main(String[] args) {

    int x=2 , y=7, z=14;
    int max1= Math.max(x,y);

    System.out.println("Max value is: "+ Math.max(max1, z)); 
}  

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Android Plugin for Gradle HTTP proxy settings

For application-specific HTTP proxy settings, set the proxy settings in the build.gradle file as required for each application module.

apply plugin: 'com.android.application'

android {
    ...

    defaultConfig {
        ...
        systemProp.http.proxyHost=proxy.company.com
        systemProp.http.proxyPort=443
        systemProp.http.proxyUser=userid
        systemProp.http.proxyPassword=password
        systemProp.http.auth.ntlm.domain=domain
    }
    ...
}

For project-wide HTTP proxy settings, set the proxy settings in the gradle/gradle.properties file.

# Project-wide Gradle settings.
...

systemProp.http.proxyHost=proxy.company.com
systemProp.http.proxyPort=443
systemProp.http.proxyUser=username
systemProp.http.proxyPassword=password
systemProp.http.auth.ntlm.domain=domain

systemProp.https.proxyHost=proxy.company.com
systemProp.https.proxyPort=443
systemProp.https.proxyUser=username
systemProp.https.proxyPassword=password
systemProp.https.auth.ntlm.domain=domain

...

Please read Official Document Configuration

FormsAuthentication.SignOut() does not log the user out

Be aware that WIF refuses to tell the browser to cleanup the cookies if the wsignoutcleanup message from STS doesn't match the url with the name of the application from IIS, and I mean CASE SENSITIVE. WIF responds with the green OK check, but will not send the command to delete cookies to browser.

So, you need to pay attention to the case sensitivity of your url's.

For example, ThinkTecture Identity Server saves the urls of the visiting RPs in one cookie, but it makes all of them lower case. WIF will receive the wsignoutcleanup message in lower case and will compare it with the application name in IIS. If it doesn't match, it deletes no cookies, but will report OK to the browser. So, for this Identity Server I needed to write all urls in web.config and all application names in IIS in lower case, in order to avoid such problems.

Also don't forget to allow third party cookies in the browser if you have the applications outside of the subdomain of STS, otherwise the browser will not delete the cookies even if WIF tells him so.

Clean up a fork and restart it from the upstream

Love VonC's answer. Here's an easy version of it for beginners.

There is a git remote called origin which I am sure you are all aware of. Basically, you can add as many remotes to a git repo as you want. So, what we can do is introduce a new remote which is the original repo not the fork. I like to call it original

Let's add original repo's to our fork as a remote.

git remote add original https://git-repo/original/original.git

Now let's fetch the original repo to make sure we have the latest coded

git fetch original

As, VonC suggested, make sure we are on the master.

git checkout master

Now to bring our fork up to speed with the latest code on original repo, all we have to do is hard reset our master branch in accordance with the original remote.

git reset --hard original/master

And you are done :)

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

Postgres: How to convert a json string to text?

An easy way of doing this:

SELECT  ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;

Just convert the json string into a json list

using href links inside <option> tag

The <select> tag creates a dropdown list. You can't put html links inside a dropdown.

However, there are JavaScript libraries that provide similar functionality. Here is one example: http://www.dynamicdrive.com/dynamicindex1/dropmenuindex.htm

What's the difference between REST & RESTful

Web services are essentially web sites whose content is consumed by computer programs, not people. REST is a set of architectural principles that stipulate that web services should maximally leverage HTTP and other web standards, so that programs gain all the good stuff that people already can get out of the web. REST is often contrasted with SOAP web services, and other "remote procedure call" oriented web services.

Stefan Tilkov's presentations on REST at Parleys.com are quite good, especially this one.

For a book, you can't get any better than Richardson and Ruby's Restful Web Services.

The APK file does not exist on disk

    1) This problem occure due to apk file .if your apk file
        (output/apk/debug.apk) not generated in this format . 

    2) you should use always in gradle file .

    buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }

Best way to remove from NSMutableArray while iterating?

Either use loop counting down over indices:

for (NSInteger i = array.count - 1; i >= 0; --i) {

or make a copy with the objects you want to keep.

In particular, do not use a for (id object in array) loop or NSEnumerator.

Downloading an entire S3 bucket?

AWS sdk API will only best option for upload entire folder and repo to s3 and download entire bucket of s3 to locally.

For uploading whole folder to s3

aws s3 sync . s3://BucketName

for download whole s3 bucket locally

aws s3 sync s3://BucketName . 

you can also assign path As like BucketName/Path for particular folder in s3 to download

C#: Assign same value to multiple variables in single statement

int num1, num2, num3;

num1 = num2 = num3 = 5;

Console.WriteLine(num1 + "=" + num2 + "=" + num3);    // 5=5=5

Regex, every non-alphanumeric character except white space or colon

This regex works for C#, PCRE and Go to name a few.

It doesn't work for JavaScript on Chrome from what RegexBuddy says. But there's already an example for that here.

This main part of this is:

\p{L}

which represents \p{L} or \p{Letter} any kind of letter from any language.`


The full regex itself: [^\w\d\s:\p{L}]

Example: https://regex101.com/r/K59PrA/2

Git commit with no commit message

Note: starting git1.8.3.2 (July 2013), the following command (mentioned above by Jeremy W Sherman) won't open an editor anymore:

git commit --allow-empty-message -m ''

See commit 25206778aac776fc6cc4887653fdae476c7a9b5a:

If an empty message is specified with the option -m of git commit then the editor is started.
That's unexpected and unnecessary.
Instead of using the length of the message string for checking if the user specified one, directly remember if the option -m was given.


git 2.9 (June 2016) improves the empty message behavior:

See commit 178e814 (06 Apr 2016) by Adam Dinwoodie (me-and).
See commit 27014cb (07 Apr 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 0709261, 22 Apr 2016)

commit: do not ignore an empty message given by -m ''

  • "git commit --amend -m '' --allow-empty-message", even though it looks strange, is a valid request to amend the commit to have no message at all.
    Due to the misdetection of the presence of -m on the command line, we ended up keeping the log messsage from the original commit.
  • "git commit -m "$msg" -F file" should be rejected whether $msg is an empty string or not, but due to the same bug, was not rejected when $msg is empty.
  • "git -c template=file -m "$msg"" should ignore the template even when $msg is empty, but it didn't and instead used the contents from the template file.

Sort array of objects by single key with date value

I have created a sorting function in Typescript which we can use to search strings, dates and numbers in array of objects. It can also sort on multiple fields.

export type SortType = 'string' | 'number' | 'date';
export type SortingOrder = 'asc' | 'desc';

export interface SortOptions {
  sortByKey: string;
  sortType?: SortType;
  sortingOrder?: SortingOrder;
}


class CustomSorting {
    static sortArrayOfObjects(fields: SortOptions[] = [{sortByKey: 'value', sortType: 'string', sortingOrder: 'desc'}]) {
        return (a, b) => fields
          .map((field) => {
            if (!a[field.sortByKey] || !b[field.sortByKey]) {
              return 0;
            }

            const direction = field.sortingOrder === 'asc' ? 1 : -1;

            let firstValue;
            let secondValue;

            if (field.sortType === 'string') {
              firstValue = a[field.sortByKey].toUpperCase();
              secondValue = b[field.sortByKey].toUpperCase();
            } else if (field.sortType === 'number') {
              firstValue = parseInt(a[field.sortByKey], 10);
              secondValue = parseInt(b[field.sortByKey], 10);
            } else if (field.sortType === 'date') {
              firstValue = new Date(a[field.sortByKey]);
              secondValue = new Date(b[field.sortByKey]);
            }
            return firstValue > secondValue ? direction : firstValue < secondValue ? -(direction) : 0;

          })
          .reduce((pos, neg) => pos ? pos : neg, 0);
      }
    }
}

Usage:

const sortOptions = [{
      sortByKey: 'anyKey',
      sortType: 'string',
      sortingOrder: 'asc',
    }];

arrayOfObjects.sort(CustomSorting.sortArrayOfObjects(sortOptions));

Setting Java heap space under Maven 2 on Windows

After trying to use the MAVEN_OPTS variable with no luck, I came across this site which worked for me. So all I had to do was add -Xms128m -Xmx1024m to the default VM options and it worked.

To change those in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Finding the last index of an array

Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index type to keep array's indexes from end:

var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];

You can use this index to get last array value in any lenght of array. For example:

var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5

For more information check documentation

release Selenium chromedriver.exe from memory

Observed on version 3.141.0:

If you initialize your ChromeDriver with just ChromeOptions, quit() will not close out chromedriver.exe.

    ChromeOptions chromeOptions = new ChromeOptions();
    ChromeDriver driver = new ChromeDriver(chromeOptions);
    // .. do stuff ..
    driver.quit()

If you create and pass in a ChromeDriverService, quit() will close chromedriver.exe out correctly.

    ChromeDriverService driverService = ChromeDriverService.CreateDefaultService();
    ChromeOptions chromeOptions = new ChromeOptions();
    ChromeDriver driver = new ChromeDriver(driverService, chromeOptions);
    // .. do stuff ..
    driver.quit()

PHPmailer sending HTML CODE

In version 5.2.7 I use this to send plain text: $mail->set('Body', $Body);

execute function after complete page load

Try this jQuery:

$(function() {
 // Handler for .ready() called.
});

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.

To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

How to prevent multiple definitions in C?

Including the implementation file (test.c) causes it to be prepended to your main.c and complied there and then again separately. So, the function test has two definitions -- one in the object code of main.c and once in that of test.c, which gives you a ODR violation. You need to create a header file containing the declaration of test and include it in main.c:

/* test.h */
#ifndef TEST_H
#define TEST_H
void test(); /* declaration */
#endif /* TEST_H */

Video auto play is not working in Safari and Chrome desktop browser

I've just get now the same issue with my video

<video preload="none" autoplay="autoplay" loop="loop">
  <source src="Home_Teaser.mp4" type="video/mp4">
  <source src="Home_Teaser" type="video/webm">
  <source src="Home_Teaser.ogv" type="video/ogg">
</video>

After search, I've found a solution:

If I set "preload" attributes to "true" the video start normally

Get first n characters of a string

if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";

Segmentation fault on large array sizes

Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:

ulimit -s unlimited

But be careful, memory is a limited resource and with great power come great responsibilities :)

Using IS NULL or IS NOT NULL on join conditions - Theory question

Your execution plan should make this clear; the JOIN takes precedence, after which the results are filtered.

How do you force a CIFS connection to unmount

There's a -f option to umount that you can try:

umount -f /mnt/fileshare

Are you specifying the '-t cifs' option to mount? Also make sure you're not specifying the 'hard' option to mount.

You may also want to consider fusesmb, since the filesystem will be running in userspace you can kill it just like any other process.

The imported project "C:\Microsoft.CSharp.targets" was not found

I got this after reinstalling Windows. Visual Studio was installed, and I could see the Silverlight project type in the New Project window, but opening one didn't work. The solution was simple: I had to install the Silverlight Developer runtime and/or the Microsoft Silverlight 4 Tools for Visual Studio. This may seem stupid, but I overlooked it because I thought it should work, as the Silverlight project type was available.

Form submit with AJAX passing form data to PHP without page refresh

JS Code

    $("#submit").click(function() { 
    //get input field values
    var name            = $('#name').val(); 
    var email           = $('#email').val();
    var message         = $('#comment').val();
    var flag = true;
    /********validate all our form fields***********/
    /* Name field validation  */
    if(name==""){ 
        $('#name').css('border-color','red'); 
        flag = false;
    }
    /* email field validation  */
    if(email==""){ 
        $('#email').css('border-color','red'); 
        flag = false;
    } 
    /* message field validation */
    if(message=="") {  
       $('#comment').css('border-color','red'); 
        flag = false;
    }
    /********Validation end here ****/
    /* If all are ok then we send ajax request to email_send.php *******/
    if(flag) 
    {
        $.ajax({
            type: 'post',
            url: "email_send.php", 
            dataType: 'json',
            data: 'username='+name+'&useremail='+email+'&message='+message,
            beforeSend: function() {
                $('#submit').attr('disabled', true);
                $('#submit').after('<span class="wait">&nbsp;<img src="image/loading.gif" alt="" /></span>');
            },
            complete: function() {
                $('#submit').attr('disabled', false);
                $('.wait').remove();
            },  
            success: function(data)
            {
                if(data.type == 'error')
                {
                    output = '<div class="error">'+data.text+'</div>';
                }else{
                    output = '<div class="success">'+data.text+'</div>';
                    $('input[type=text]').val(''); 
                    $('#contactform textarea').val(''); 
                }

                $("#result").hide().html(output).slideDown();           
                }
        });
    }
});
//reset previously set border colors and hide all message on .keyup()
$("#contactform input, #contactform textarea").keyup(function() { 
    $("#contactform input, #contactform textarea").css('border-color',''); 
    $("#result").slideUp();
});

HTML Form

<div  class="cover">
<div id="result"></div>
<div id="contactform">
    <p class="contact"><label for="name">Name</label></p>
    <input id="name" name="name" placeholder="Yourname" type="text">

    <p class="contact"><label for="email">Email</label></p>
    <input id="email" name="email" placeholder="[email protected]" type="text">

    <p class="contact"><label for="comment">Your Message</label></p>
    <textarea name="comment" id="comment" tabindex="4"></textarea> <br>
    <input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>

PHP Code

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

//check if its an ajax request, exit if not
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

    //exit script outputting json data
    $output = json_encode(
            array(
                'type' => 'error',
                'text' => 'Request must come from Ajax'
    ));

    die($output);
}

//check $_POST vars are set, exit if any missing
if (!isset($_POST["username"]) || !isset($_POST["useremail"]) || !isset($_POST["message"])) {
    $output = json_encode(array('type' => 'error', 'text' => 'Input fields are empty!'));
    die($output);
}

//Sanitize input data using PHP filter_var().
$username = filter_var(trim($_POST["username"]), FILTER_SANITIZE_STRING);
$useremail = filter_var(trim($_POST["useremail"]), FILTER_SANITIZE_EMAIL);
$message = filter_var(trim($_POST["message"]), FILTER_SANITIZE_STRING);

//additional php validation
if (strlen($username) < 4) { // If length is less than 4 it will throw an HTTP error.
    $output = json_encode(array('type' => 'error', 'text' => 'Name is too short!'));
    die($output);
}
if (!filter_var($useremail, FILTER_VALIDATE_EMAIL)) { //email validation
    $output = json_encode(array('type' => 'error', 'text' => 'Please enter a valid email!'));
    die($output);
}
if (strlen($message) < 5) { //check emtpy message
    $output = json_encode(array('type' => 'error', 'text' => 'Too short message!'));
    die($output);
}

$to = "[email protected]"; //Replace with recipient email address
//proceed with PHP email.
$headers = 'From: ' . $useremail . '' . "\r\n" .
        'Reply-To: ' . $useremail . '' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

$sentMail = @mail($to, $subject, $message . '  -' . $username, $headers);
//$sentMail = true;
if (!$sentMail) {
    $output = json_encode(array('type' => 'error', 'text' => 'Could not send mail! Please contact administrator.'));
    die($output);
} else {
    $output = json_encode(array('type' => 'message', 'text' => 'Hi ' . $username . ' Thank you for your email'));
    die($output);
}

This page has a simpler example http://wearecoders.net/submit-form-without-page-refresh-with-php-and-ajax/

Populate unique values into a VBA array from Excel

one more way ...

Sub get_unique()
Dim unique_string As String
    lr = Sheets("data").Cells(Sheets("data").Rows.Count, 1).End(xlUp).Row
    Set range1 = Sheets("data").Range("A2:A" & lr)
    For Each cel In range1
       If Not InStr(output, cel.Value) > 0 Then
           unique_string = unique_string & cel.Value & ","
       End If
    Next
End Sub

Image style height and width not taken in outlook mails

This works for me in Outlook:

<img src="image.jpg" width="120" style="display:block;width:100%" />

I hope it works for you.

How to convert a full date to a short date in javascript?

The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate() to return a number for the day in month:

var day = convertedStartDate.getDate();

If you like, you can try to add a custom format function to the prototype of the Date object:

Date.prototype.formatMMDDYYYY = function(){
    return (this.getMonth() + 1) + 
    "/" +  this.getDate() +
    "/" +  this.getFullYear();
}

After doing this, you can call formatMMDDYYY() on any instance of the Date object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)

(tangent: the Date object always confuses me... getYear() vs getFullYear(), getDate() vs getDay(), getDate() ranges from 1..31, but getMonth() from 0..11

It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)

Passing on command line arguments to runnable JAR

You can pass program arguments on the command line and get them in your Java app like this:

public static void main(String[] args) {
  String pathToXml = args[0];
....
}

Alternatively you pass a system property by changing the command line to:

java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt

and your main class to:

public static void main(String[] args) {
  String pathToXml = System.getProperty("path-to-xml");
....
}

Check if element is visible on screen

Could you use jQuery, since it's cross-browser compatible?

function isOnScreen(element)
{
    var curPos = element.offset();
    var curTop = curPos.top;
    var screenHeight = $(window).height();
    return (curTop > screenHeight) ? false : true;
}

And then call the function using something like:

if(isOnScreen($('#myDivId'))) { /* Code here... */ };

How to close a web page on a button click, a hyperlink or a link button click?

Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.

Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close

    private void myNewButton_Click(object sender, EventArgs e) {
        this.Close();
    }

And that should be it.

The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.

C# ListView Column Width Auto

If you have ListView in any Parent panel (ListView dock fill), you can use simply method...

private void ListViewHeaderWidth() {
        int HeaderWidth = (listViewInfo.Parent.Width - 2) / listViewInfo.Columns.Count;
        foreach (ColumnHeader header in listViewInfo.Columns)
        {
            header.Width = HeaderWidth;
        }
    }

How can I split a string with a string delimiter?

Read C# Split String Examples - Dot Net Pearls and the solution can be something like:

var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);

How to run python script in webpage

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

#!/usr/bin/python   
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

How to uninstall a package installed with pip install --user

I strongly recommend you to use virtual environments for python package installation. With virtualenv, you prevent any package conflict and total isolation from your python related userland commands.

To delete all your package follow this;

It's possible to uninstall packages installed with --user flag. This one worked for me;

pip freeze --user | xargs pip uninstall -y

For python 3;

pip3 freeze --user | xargs pip3 uninstall -y

But somehow these commands don't uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;

pip uninstall setuptools && pip uninstall pip

How do I use MySQL through XAMPP?

XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.

After the successful installation navigate to your xampp folder and execute the xampp-control.exe

Press the start Button at the mysql row.

enter image description here

Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.

But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost or 127.0.0.1 in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.

Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.

enter image description here

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

Create a simple HTTP server with Java?

This is how I would go about this:

  1. Start a ServerSocket listening (probably on port 80).
  2. Once you get a connection request, accept and pass to another thread/process (this leaves your ServerSocket available to keep listening and accept other connections).
  3. Parse the request text (specifically, the headers where you will see if it is a GET or POST, and the parameters passed.
  4. Answer with your own headers (Content-Type, etc.) and the HTML.

I find it useful to use Firebug (in Firefox) to see examples of headers. This is what you want to emulate.

Try this link: - Multithreaded Server in Java

How to set background color of view transparent in React Native

You should be aware of the current conflicts that exists with iOS and RGBA backgrounds.

Summary: public React Native currently exposes the iOS layer shadow properties more-or-less directly, however there are a number of problems with this:

1) Performance when using these properties is poor by default. That's because iOS calculates the shadow by getting the exact pixel mask of the view, including any tranlucent content, and all of its subviews, which is very CPU and GPU-intensive. 2) The iOS shadow properties do not match the syntax or semantics of the CSS box-shadow standard, and are unlikely to be possible to implement on Android. 3) We don't expose the layer.shadowPath property, which is crucial to getting good performance out of layer shadows.

This diff solves problem number 1) by implementing a default shadowPath that matches the view border for views with an opaque background. This improves the performance of shadows by optimizing for the common usage case. I've also reinstated background color propagation for views which have shadow props - this should help ensure that this best-case scenario occurs more often.

For views with an explicit transparent background, the shadow will continue to work as it did before ( shadowPath will be left unset, and the shadow will be derived exactly from the pixels of the view and its subviews). This is the worst-case path for performance, however, so you should avoid it unless absolutely necessary. Support for this may be disabled by default in future, or dropped altogether.

For translucent images, it is suggested that you bake the shadow into the image itself, or use another mechanism to pre-generate the shadow. For text shadows, you should use the textShadow properties, which work cross-platform and have much better performance.

Problem number 2) will be solved in a future diff, possibly by renaming the iOS shadowXXX properties to boxShadowXXX, and changing the syntax and semantics to match the CSS standards.

Problem number 3) is now mostly moot, since we generate the shadowPath automatically. In future, we may provide an iOS-specific prop to set the path explicitly if there's a demand for more precise control of the shadow.

Reviewed By: weicool

Commit: https://github.com/facebook/react-native/commit/e4c53c28aea7e067e48f5c8c0100c7cafc031b06

Django auto_now and auto_now_add

Any field with the auto_now attribute set will also inherit editable=False and therefore will not show up in the admin panel. There has been talk in the past about making the auto_now and auto_now_add arguments go away, and although they still exist, I feel you're better off just using a custom save() method.

So, to make this work properly, I would recommend not using auto_now or auto_now_add and instead define your own save() method to make sure that created is only updated if id is not set (such as when the item is first created), and have it update modified every time the item is saved.

I have done the exact same thing with other projects I have written using Django, and so your save() would look like this:

from django.utils import timezone

class User(models.Model):
    created     = models.DateTimeField(editable=False)
    modified    = models.DateTimeField()

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        if not self.id:
            self.created = timezone.now()
        self.modified = timezone.now()
        return super(User, self).save(*args, **kwargs)

Hope this helps!

Edit in response to comments:

The reason why I just stick with overloading save() vs. relying on these field arguments is two-fold:

  1. The aforementioned ups and downs with their reliability. These arguments are heavily reliant on the way each type of database that Django knows how to interact with treats a date/time stamp field, and seems to break and/or change between every release. (Which I believe is the impetus behind the call to have them removed altogether).
  2. The fact that they only work on DateField, DateTimeField, and TimeField, and by using this technique you are able to automatically populate any field type every time an item is saved.
  3. Use django.utils.timezone.now() vs. datetime.datetime.now(), because it will return a TZ-aware or naive datetime.datetime object depending on settings.USE_TZ.

To address why the OP saw the error, I don't know exactly, but it looks like created isn't even being populated at all, despite having auto_now_add=True. To me it stands out as a bug, and underscores item #1 in my little list above: auto_now and auto_now_add are flaky at best.

Django values_list vs values

The values() method returns a QuerySet containing dictionaries:

<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>

The values_list() method returns a QuerySet containing tuples:

<QuerySet [(1,), (2,)]>

If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples:

<QuerySet [1, 2]>

Count the number of times a string appears within a string

With Linq...

string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
var count = s.Split(new[] {',', ':'}).Count(s => s == "true" );

Make an existing Git branch track a remote branch?

For 1.6.x, it can be done using the git_remote_branch tool:

grb track foo upstream

That will cause Git to make foo track upstream/foo.

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

Could not install packages due to an EnvironmentError: [Errno 13]

I had similar trouble in a venv on a mounted NTFS partition on linux with all the right permissions. Making sure pip ran with --ignore-installed solved it, i.e.:

python -m pip install --upgrade --ignore-installed

How do I turn off PHP Notices?

For PHP code:

<?php
error_reporting(E_ALL & ~E_NOTICE);

For php.ini config:

error_reporting = E_ALL & ~E_NOTICE

Microsoft Excel ActiveX Controls Disabled?

Here is the best answer that I have found on the Microsoft Excel Support Team Blog

For some users, Forms Controls (FM20.dll) are no longer working as expected after installing December 2014 updates. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.

You may received errors such as:

"Cannot insert object" "Object library invalid or contains references to object definitions that could not be found"

Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code. Steps to follow after the update:

To resolve this issue, you must delete the cached versions of the control type libraries (extender files) on the client computer. To do this, you must search your hard disk for files that have the ".exd" file name extension and delete all the .exd files that you find. These .exd files will be re-created automatically when you use the new controls the next time that you use VBA. These extender files will be under the user's profile and may also be in other locations, such as the following:

%appdata%\Microsoft\forms

%temp%\Excel8.0

%temp%\VBE

Scripting solution:

Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.

del %temp%\vbe\*.exd

del %temp%\excel8.0\*.exd

del %appdata%\microsoft\forms\*.exd

del %appdata%\microsoft\local\*.exd

del %appdata%\Roaming\microsoft\forms\*.exd

del %temp%\word8.0\*.exd

del %temp%\PPT11.0\*.exd

Additional step:

If the steps above do not resolve your issue, another step that can be tested (see warning below):

  1. On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.

    Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.

    Save and reopen the file. Test for resolution. If resolved, provide this updated project to additional users.

    Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.

If this does not resolve your issue, it may be a different issue and further troubleshooting may be necessary.

Microsoft is currently working on this issue. Watch the blog for updates.

Source

Take the content of a list and append it to another list

You can simply concatnate two lists, e.g:

list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2

print(list3)
>> [0, 1, 2, 3]

How to get relative path from absolute path

As Alex Brault points out, especially on Windows, the absolute path (with drive letter and all) is unambiguous and often better.

Shouldn't your OpenFileDialog use a regular tree-browser structure?

To get some nomenclature in place, the RefDir is the directory relative to which you want to specify the path; the AbsName is the absolute path name that you want to map; and the RelPath is the resulting relative path.

Take the first of these options that matches:

  • If you have different drive letters, there is no relative path from RefDir to AbsName; you must use the AbsName.
  • If the AbsName is in a sub-directory of RefDir or is a file within RefDir then simply remove the RefDir from the start of AbsName to create RelPath; optionally prepend "./" (or ".\" since you are on Windows).
  • Find the longest common prefix of RefDir and AbsName (where D:\Abc\Def and D:\Abc\Default share D:\Abc as the longest common prefix; it has to be a mapping of name components, not a simple longest common substring); call it LCP. Remove LCP from AbsName and RefDir. For each path component left in (RefDir - LCP), prepend "..\" to (AbsName - LCP) to yield RelPath.

To illustrate the last rule (which is, of course, by far the most complex), start with:

RefDir = D:\Abc\Def\Ghi
AbsName = D:\Abc\Default\Karma\Crucible

Then

LCP = D:\Abc
(RefDir - LCP) = Def\Ghi
(Absname - LCP) = Default\Karma\Crucible
RelPath = ..\..\Default\Karma\Crucible

While I was typing, DavidK produced an answer which suggests that you are not the first to need this feature and that there is a standard function to do this job. Use it. But there's no harm in being able to think your way through from first principles, either.

Except that Unix systems do not support drive letters (so everything is always located under the same root directory, and the first bullet therefore is irrelevant), the same technique could be used on Unix.

How do I set path while saving a cookie value in JavaScript?

simply: document.cookie="name=value;path=/";

There is a negative point to it

Now, the cookie will be available to all directories on the domain it is set from. If the website is just one of many at that domain, it’s best not to do this because everyone else will also have access to your cookie information.

How do I find the current directory of a batch file, and then use it for the path?

You can also do

 Pushd "%~dp0"

Which also takes running from a unc path into consideration.

View's getWidth() and getHeight() returns 0

We can use

@Override
 public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  //Here you can get the size!
 }

Is there a Python equivalent of the C# null-coalescing operator?

Here's a function that will return the first argument that isn't None:

def coalesce(*arg):
  return reduce(lambda x, y: x if x is not None else y, arg)

# Prints "banana"
print coalesce(None, "banana", "phone", None)

reduce() might needlessly iterate over all the arguments even if the first argument is not None, so you can also use this version:

def coalesce(*arg):
  for el in arg:
    if el is not None:
      return el
  return None

How can I see the raw SQL queries Django is running?

Take a look at debug_toolbar, it's very useful for debugging.

Documentation and source is available at http://django-debug-toolbar.readthedocs.io/.

Screenshot of debug toolbar

Read HttpContent in WebApi controller

Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.

If you still want to have the model as a parameter in the method, you can create a DelegatingHandler to buffer the content.

internal sealed class BufferizingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        await request.Content.LoadIntoBufferAsync();
        var result = await base.SendAsync(request, cancellationToken);
        return result;
    }
}

And add it to the global message handlers:

configuration.MessageHandlers.Add(new BufferizingHandler());

This solution is based on the answer by Darrel Miller.

This way all the requests will be buffered.

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

How to redirect to Login page when Session is expired in Java web application?

How to redirect to Login page when Session is expired in Java web application?

This is a wrong question. You should differentiate between the cases "User is not logged in" and "Session is expired". You basically want to redirect to login page when user is not logged in. Not when session is expired. The currently accepted answer only checks HttpSession#isNew(). But this obviously fails when the user has sent more than one request in the same session when the session is implicitly created by the JSP or what not. E.g. when just pressing F5 on the login page.

As said, you should instead be checking if the user is logged in or not. Given the fact that you're asking this kind of question while standard authentication frameworks like j_security_check, Shiro, Spring Security, etc already transparently manage this (and thus there would be no need to ask this kind of question on them), that can only mean that you're using a homegrown authentication approach.

Assuming that you're storing the logged-in user in the session in some login servlet like below:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @EJB
    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.find(username, password);

        if (user != null) {
            request.getSession().setAttribute("user", user);
            response.sendRedirect(request.getContextPath() + "/home");
        } else {
            request.setAttribute("error", "Unknown login, try again");
            doGet(request, response);
        }
    }

}

Then you can check for that in a login filter like below:

@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {    
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String loginURI = request.getContextPath() + "/login";

        boolean loggedIn = session != null && session.getAttribute("user") != null;
        boolean loginRequest = request.getRequestURI().equals(loginURI);

        if (loggedIn || loginRequest) {
            chain.doFilter(request, response);
        } else {
            response.sendRedirect(loginURI);
        }
    }

    // ...
}

No need to fiddle around with brittle HttpSession#isNew() checks.

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

Table with table-layout: fixed; and how to make one column wider

Are you creating a very large table (hundreds of rows and columns)? If so, table-layout: fixed; is a good idea, as the browser only needs to read the first row in order to compute and render the entire table, so it loads faster.

But if not, I would suggest dumping table-layout: fixed; and changing your css as follows:

table th, table td{
border: 1px solid #000;
width:20px;  //or something similar   
}

table td.wideRow, table th.wideRow{
width: 300px;
}

http://jsfiddle.net/6p9K3/1/

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

That's your jQuery API problem, not your script. There is not much to worry about.

Copy file from source directory to binary directory using CMake

I would suggest TARGET_FILE_DIR if you want the file to be copied to the same folder as your .exe file.

$ Directory of main file (.exe, .so.1.2, .a).

add_custom_command(
  TARGET ${PROJECT_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy 
    ${CMAKE_CURRENT_SOURCE_DIR}/input.txt 
    $<TARGET_FILE_DIR:${PROJECT_NAME}>)

In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

Running this:

sqllocaldb create "v12.0"

From cmd prompt solved this for me...

Cannot create Maven Project in eclipse

For me the solution was a bit simpler, I just had to clean the repository : .m2/repository/org/apache/maven/archetypes

Pretty graphs and charts in Python

If you like to use gnuplot for plotting, you should consider Gnuplot.py. It provides an object-oriented interface to gnuplot, and also allows you to pass commands directly to gnuplot. Unfortunately, it is no longer being actively developed.

How to overlay one div over another div

The accepted solution works great, but IMO lacks an explanation as to why it works. The example below is boiled down to the basics and separates the important CSS from the non-relevant styling CSS. As a bonus, I've also included a detailed explanation of how CSS positioning works.

TLDR; if you only want the code, scroll down to The Result.

The Problem

There are two separate, sibling, elements and the goal is to position the second element (with an id of infoi), so it appears within the previous element (the one with a class of navi). The HTML structure cannot be changed.

Proposed Solution

To achieve the desired result we're going to move, or position, the second element, which we'll call #infoi so it appears within the first element, which we'll call .navi. Specifically, we want #infoi to be positioned in the top-right corner of .navi.

CSS Position Required Knowledge

CSS has several properties for positioning elements. By default, all elements are position: static. This means the element will be positioned according to its order in the HTML structure, with few exceptions.

The other position values are relative, absolute, sticky, and fixed. By setting an element's position to one of these other values it's now possible to use a combination of the following four properties to position the element:

  • top
  • right
  • bottom
  • left

In other words, by setting position: absolute, we can add top: 100px to position the element 100 pixels from the top of the page. Conversely, if we set bottom: 100px the element would be positioned 100 pixels from the bottom of the page.

Here's where many CSS newcomers get lost - position: absolute has a frame of reference. In the example above, the frame of reference is the body element. position: absolute with top: 100px means the element is positioned 100 pixels from the top of the body element.

The position frame of reference, or position context, can be altered by setting the position of a parent element to any value other than position: static. That is, we can create a new position context by giving a parent element:

  • position: relative;
  • position: absolute;
  • position: sticky;
  • position: fixed;

For example, if a <div class="parent"> element is given position: relative, any child elements use the <div class="parent"> as their position context. If a child element were given position: absolute and top: 100px, the element would be positioned 100 pixels from the top of the <div class="parent"> element, because the <div class="parent"> is now the position context.

The other factor to be aware of is stack order - or how elements are stacked in the z-direction. The must-know here is the stack order of elements are, by default, defined by the reverse of their order in the HTML structure. Consider the following example:

<body>
  <div>Bottom</div>
  <div>Top</div>
</body>

In this example, if the two <div> elements were positioned in the same place on the page, the <div>Top</div> element would cover the <div>Bottom</div> element. Since <div>Top</div> comes after <div>Bottom</div> in the HTML structure it has a higher stacking order.

_x000D_
_x000D_
div {_x000D_
  position: absolute;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
}_x000D_
_x000D_
#bottom {_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
#top {_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  background-color: red;_x000D_
}
_x000D_
<div id="bottom">Bottom</div>_x000D_
<div id="top">Top</div>
_x000D_
_x000D_
_x000D_

The stacking order can be changed with CSS using the z-index or order properties.

We can ignore the stacking order in this issue as the natural HTML structure of the elements means the element we want to appear on top comes after the other element.

So, back to the problem at hand - we'll use position context to solve this issue.

The Solution

As stated above, our goal is to position the #infoi element so it appears within the .navi element. To do this, we'll wrap the .navi and #infoi elements in a new element <div class="wrapper"> so we can create a new position context.

<div class="wrapper">
  <div class="navi"></div>
  <div id="infoi"></div>
</div>

Then create a new position context by giving .wrapper a position: relative.

.wrapper {
  position: relative;
}

With this new position context, we can position #infoi within .wrapper. First, give #infoi a position: absolute, allowing us to position #infoi absolutely in .wrapper.

Then add top: 0 and right: 0 to position the #infoi element in the top-right corner. Remember, because the #infoi element is using .wrapper as its position context, it will be in the top-right of the .wrapper element.

#infoi {
  position: absolute;
  top: 0;
  right: 0;
}

Because .wrapper is merely a container for .navi, positioning #infoi in the top-right corner of .wrapper gives the effect of being positioned in the top-right corner of .navi.

And there we have it, #infoi now appears to be in the top-right corner of .navi.

The Result

The example below is boiled down to the basics, and contains some minimal styling.

_x000D_
_x000D_
/*_x000D_
*  position: relative gives a new position context_x000D_
*/_x000D_
.wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  The .navi properties are for styling only_x000D_
*  These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
  background-color: #eaeaea;_x000D_
  height: 40px;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the top-right_x000D_
*  of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
_x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  height: 20px;_x000D_
  padding: 10px 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="navi"></div>_x000D_
  <div id="infoi">_x000D_
    <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

An Alternate (Grid) Solution

Here's an alternate solution using CSS Grid to position the .navi element with the #infoi element in the far right. I've used the verbose grid properties to make it as clear as possible.

_x000D_
_x000D_
:root {_x000D_
  --columns: 12;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  Setup the wrapper as a Grid element, with 12 columns, 1 row_x000D_
*/_x000D_
.wrapper {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(var(--columns), 1fr);_x000D_
  grid-template-rows: 40px;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  Position the .navi element to span all columns_x000D_
*/_x000D_
.navi {_x000D_
  grid-column-start: 1;_x000D_
  grid-column-end: span var(--columns);_x000D_
  grid-row-start: 1;_x000D_
  grid-row-end: 2;_x000D_
  _x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  background-color: #eaeaea;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the last column, and center it_x000D_
*/_x000D_
#infoi {_x000D_
  grid-column-start: var(--columns);_x000D_
  grid-column-end: span 1;_x000D_
  grid-row-start: 1;_x000D_
  place-self: center;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="navi"></div>_x000D_
  <div id="infoi">_x000D_
    <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

An Alternate (No Wrapper) Solution

In the case we can't edit any HTML, meaning we can't add a wrapper element, we can still achieve the desired effect.

Instead of using position: absolute on the #infoi element, we'll use position: relative. This allows us to reposition the #infoi element from its default position below the .navi element. With position: relative we can use a negative top value to move it up from its default position, and a left value of 100% minus a few pixels, using left: calc(100% - 52px), to position it near the right-side.

_x000D_
_x000D_
/*_x000D_
*  The .navi properties are for styling only_x000D_
*  These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
  background-color: #eaeaea;_x000D_
  height: 40px;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the top-right_x000D_
*  of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  top: -40px;_x000D_
  left: calc(100% - 52px);_x000D_
_x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  height: 20px;_x000D_
  padding: 10px 10px;_x000D_
}
_x000D_
<div class="navi"></div>_x000D_
<div id="infoi">_x000D_
  <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

After installing OpenSSL, you need to restart your computer and use Run As Administrator. Then its works.

Regular Expression for matching parentheses

  • You can escape any meta-character by using a backslash, so you can match ( with the pattern \(.
  • Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
  • Some flavors support \Q and \E, with literal text between them.
  • Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

ImportError: No module named psycopg2

For Python3

Step 1: Install Dependencies

sudo apt-get install python3 python-dev python3-dev

Step 2: Install

pip install psycopg2

Spring MVC - Why not able to use @RequestBody and @RequestParam together

The @RequestBody javadoc states

Annotation indicating a method parameter should be bound to the body of the web request.

It uses registered instances of HttpMessageConverter to deserialize the request body into an object of the annotated parameter type.

And the @RequestParam javadoc states

Annotation which indicates that a method parameter should be bound to a web request parameter.

  1. Spring binds the body of the request to the parameter annotated with @RequestBody.

  2. Spring binds request parameters from the request body (url-encoded parameters) to your method parameter. Spring will use the name of the parameter, ie. name, to map the parameter.

  3. Parameters are resolved in order. The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream. When it then tries to resolve the @RequestParam, which is by default required, there is no request parameter in the query string or what remains of the request body, ie. nothing. So it fails with 400 because the request can't be correctly handled by the handler method.

  4. The handler for @RequestParam acts first, reading what it can of the HttpServletRequest InputStream to map the request parameter, ie. the whole query string/url-encoded parameters. It does so and gets the value abc mapped to the parameter name. When the handler for @RequestBody runs, there's nothing left in the request body, so the argument used is the empty string.

  5. The handler for @RequestBody reads the body and binds it to the parameter. The handler for @RequestParam can then get the request parameter from the URL query string.

  6. The handler for @RequestParam reads from both the body and the URL query String. It would usually put them in a Map, but since the parameter is of type String, Spring will serialize the Map as comma separated values. The handler for @RequestBody then, again, has nothing left to read from the body.

Can I get JSON to load into an OrderedDict?

Some great news! Since version 3.6 the cPython implementation has preserved the insertion order of dictionaries (https://mail.python.org/pipermail/python-dev/2016-September/146327.html). This means that the json library is now order preserving by default. Observe the difference in behaviour between python 3.5 and 3.6. The code:

import json
data = json.loads('{"foo":1, "bar":2, "fiddle":{"bar":2, "foo":1}}')
print(json.dumps(data, indent=4))

In py3.5 the resulting order is undefined:

{
    "fiddle": {
        "bar": 2,
        "foo": 1
    },
    "bar": 2,
    "foo": 1
}

In the cPython implementation of python 3.6:

{
    "foo": 1,
    "bar": 2,
    "fiddle": {
        "bar": 2,
        "foo": 1
    }
}

The really great news is that this has become a language specification as of python 3.7 (as opposed to an implementation detail of cPython 3.6+): https://mail.python.org/pipermail/python-dev/2017-December/151283.html

So the answer to your question now becomes: upgrade to python 3.6! :)

Plot width settings in ipython notebook

This is way I did it:

%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)

You can define your own sizes.

Swift: print() vs println() vs NSLog()

  1. NSLog - add meta info (like timestamp and identifier) and allows you to output 1023 symbols. Also print message into Console. The slowest method
@import Foundation
NSLog("SomeString")
  1. print - prints all string to Xcode. Has better performance than previous
@import Foundation
print("SomeString")
  1. println (only available Swift v1) and add \n at the end of string
  2. os_log (from iOS v10) - prints 32768 symbols also prints to console. Has better performance than previous
@import os.log
os_log("SomeIntro: %@", log: .default, type: .info, "someString")
  1. Logger (from iOS v14) - prints 32768 symbols also prints to console. Has better performance than previous
@import os
let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "someCategory")
logger.log("\(s)")

Add CSS class to a div in code behind

For a non ASP.NET control, i.e. HTML controls like div, table, td, tr, etc. you need to first make them a server control, assign an ID, and then assign a property from server code:

ASPX page

<head>
    <style type="text/css">
        .top_rounded
        {
            height: 75px;
            width: 75px;
            border: 2px solid;
            border-radius: 5px;
            -moz-border-radius: 5px; /* Firefox 3.6 and earlier */
            border-color: #9c1c1f;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div runat="server" id="myDiv">This is my div</div>
    </form>
</body>

CS page

myDiv.Attributes.Add("class", "top_rounded");

How to capture the browser window close event?

Try this also

window.onbeforeunload = function ()
{       
    if (pasteEditorChange) {
        var btn = confirm('Do You Want to Save the Changess?');
           if(btn === true ){
               SavetoEdit();//your function call
           }
           else{
                windowClose();//your function call
           }
    }  else { 
        windowClose();//your function call
    }
};

Setting Short Value Java

Generally you can just cast the variable to become a short.

You can also get problems like this that can be confusing. This is because the + operator promotes them to an int

enter image description here

Casting the elements won't help:

enter image description here

You need to cast the expression:

enter image description here

++i or i++ in for loops ??

No compiler worth its weight in salt will run differently between

for(int i=0; i<10; i++)

and

for(int i=0;i<10;++i)

++i and i++ have the same cost. The only thing that differs is that the return value of ++i is i+1 whereas the return value of i++ is i.

So for those prefering ++i, there's probably no valid justification, just personal preference.

EDIT: This is wrong for classes, as said in about every other post. i++ will generate a copy if i is a class.

Is there possibility of sum of ArrayList without looping

The only alternative to using a loop is to use recursion.

You can define a method like

public static int sum(List<Integer> ints) {
   return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}

This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.

An alternative which avoid a stack overflow is to use.

public static int sum(List<Integer> ints) {
    int len = ints.size();
    if (len == 0) return 0;
    if (len == 1) return ints.get(0);
    return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}

This is just as inefficient, but will avoid a stack overflow.


The shortest way to write the same thing is

int sum = 0, a[] = {2, 4, 6, 8};

for(int i: a) {
    sum += i;
}

System.out.println("sum(a) = " + sum);

prints

sum(a) = 20

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

Using an authorization header with Fetch in React Native

completed = (id) => {
    var details = {
        'id': id,

    };

    var formBody = [];
    for (var property in details) {
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch(markcompleted, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formBody
    })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson, 'res JSON');
            if (responseJson.status == "success") {
                console.log(this.state);
                alert("your todolist is completed!!");
            }
        })
        .catch((error) => {
            console.error(error);
        });
};

How to read files and stdout from a running Docker container

To view the stdout, you can start the docker container with -i. This of course does not enable you to leave the started process and explore the container.

docker start -i containerid

Alternatively you can view the filesystem of the container at

/var/lib/docker/containers/containerid/root/

However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v switch when you use docker run. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.

How can I hide the Android keyboard using JavaScript?

rdougan's post did not work for me but it was a good starting point for my solution.

function androidSoftKeyHideFix(selectorName){
    $(selectorName).on('focus', function (event) {
        $(selectorName).off('focus')
        $('body').on('touchend', function (event) {
            $('body').off('touchend')
            $('.blurBox').focus();
            setTimeout(function() {
                $('.blurBox').blur();
                $('.blurBox').focus();
                $('.blurBox').blur();
                androidSoftKeyHideFix(selectorName); 
            },1)
        });
    });
}    

You need an input element at the top of the body, I classed as 'blurBox'. It must not be display:none. So give it opacity:0, and position:absolute. I tried placing it at the bottom of the body and it didn't work.

I found it necessary to repeat the .focus() .blur() sequence on the blurBox. I tried it without and it doesn't work.

This works on my 2.3 Android. I imagine that custom keyboard apps could still have issues.

I encountered a number of issues before arriving at this. There was a bizarre issue with subsequent focuses retriggering a blur/focus, which seemed like an android bug. I used a touchend listener instead of a blur listener to get around the function refiring closing the keyboard immediately after a non-initial opening. I also had an issue with keyboard typing making the scroll jump around...which is realted to a 3d transform used on a parent. That emerged from an attempt to workaround the blur-refiring issue, where I didn't unblur the blurBox at the end. So this is a delicate solution.

ITextSharp insert text to an existing pdf

I found a way to do it (dont know if it is the best but it works)

string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";

// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);

// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();

// the pdf content
PdfContentByte cb = writer.DirectContent;

// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);

// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();

// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);

// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();

I hope this can be usefull for someone =) (and post here any errors)

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

Delete empty lines using sed

sed '/^$/d' should be fine, are you expecting to modify the file in place? If so you should use the -i flag.

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

I am a beginner in Maven - don't know much about it. Carefully check on your input i.e. file path in my case. After I have carefully check, my file path is wrong so it leads to this error. After I fixed it, it works magically lol.

Xcode 4 - "Archive" is greyed out?

As the other answers state, you need to select an active scheme to something that is not a simulator, i.e. a device that's connected to your mac.

If you have no device connected to the mac then selecting "Generic IOS Device" works also.

enter image description here

How to restore the dump into your running mongodb

The directory should be named 'dump' and this directory should have a directory which contains the .bson and .json files. This directory should be named as your db name.

eg: if your db name is institution then the second directory name should be institution.

After this step, go the directory enclosing the dump folder in the terminal, and run the command

mongorestore --drop.

Do see to it that mongo is up and running.

This should work fine.

PHP regular expression - filter number only

You could do something like this if you want only whole numbers.

function make_whole($v){
    $v = floor($v);
    if(is_numeric($v)){
      echo (int)$v;
      // if you want only positive whole numbers
      //echo (int)$v = abs($v);
    }
}

Save image from url with curl PHP

Option #1

Instead of picking the binary/raw data into a variable and then writing, you can use CURLOPT_FILE option to directly show a file to the curl for the downloading.

Here is the function:

// takes URL of image and Path for the image as parameter
function download_image1($image_url, $image_file){
    $fp = fopen ($image_file, 'w+');              // open file handle

    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);

    curl_close($ch);                              // closing curl handle
    fclose($fp);                                  // closing file handle
}

And here is how you should call it:

// test the download function
download_image1("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2", "local_image1.jpg");

Option #2

Now, If you want to download a very large file, that case above function may not become handy. You can use the below function this time for handling a big file. Also, you can print progress(in % or in any other format) if you want. Below function is implemented using a callback function that writes a chunk of data in to the file in to the progress of downloading.

// takes URL of image and Path for the image as parameter
function download_image2($image_url){
    $ch = curl_init($image_url);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, "curl_callback");
    // curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
    curl_exec($ch);

    curl_close($ch);                              // closing curl handle
}

/** callback function for curl */
function curl_callback($ch, $bytes){
    global $fp;
    $len = fwrite($fp, $bytes);
    // if you want, you can use any progress printing here
    return $len;
}

And here is how to call this function:

// test the download function
$image_file = "local_image2.jpg";
$fp = fopen ($image_file, 'w+');              // open file handle
download_image2("http://www.gravatar.com/avatar/10773ae6687b55736e171c038b4228d2");
fclose($fp);                                  // closing file handle

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

qmake: could not find a Qt installation of ''

Search where is qmake-qt4:

which qmake-qt4

For example qmake-qt4 is in this path:

/usr/bin/qmake-qt4

Create symbolic link:

cd /usr/local/sbin/
ln -s /usr/bin/qmake-qt4 .
mv qmake-qt4 qmake

Regards

How to remove new line characters from data rows in mysql?

your syntax is wrong:

update mytable SET title = TRIM(TRAILING '\n' FROM title)

Addition:

If the newline character is at the start of the field:

update mytable SET title = TRIM(LEADING '\n' FROM title)

Python add item to the tuple

>>> x = (u'2',)
>>> x += u"random string"

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    x += u"random string"
TypeError: can only concatenate tuple (not "unicode") to tuple
>>> x += (u"random string", )  # concatenate a one-tuple instead
>>> x
(u'2', u'random string')

Auto increment in MongoDB to store sequence of Unique User ID

The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:

maxObj = db.CollectionName.aggregate([
  {
    $group : { _id: '$item', maxValue: { $max: '$fieldName' } } 
  }
];
fieldNextValue = maxObj.maxValue + 1;

$fieldName is the name of your field, but without the $ sign.

CollectionName is the name of your collection.

The reason I am not using count() is that the produced value could meet an existing value.

The creation of an enforcing unique index could make it safer:

db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )

Create a root password for PHPMyAdmin

  • Go tohttp://localhost/security/index.php
  • Select language, it redirects to http://localhost/security/xamppsecurity.php
  • You will find an option to change the password here

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

Solution for me (Android Studio) :

1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure

2) and increase the level of SDK "Compile SDK Version".

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Could not find a version that satisfies the requirement tensorflow

In case you are using Docker, make sure you have

FROM python:x.y.z

instead of

FROM python:x.y.z-alpine.

How do you input command line arguments in IntelliJ IDEA?

We cannot go into Terminal and give in the good old java Classname arg1 arg2 arg3

We'll have to edit the run configuration.

Step 1 : Take the Run menu
Step 2 : Select Edit Configurations
Step 3 : Fill the Program arguments field

enter image description here

After that, the arguments will be inserted to the end of the command that IntelliJ creates whenever you run the program :)

How to use multiple @RequestMapping annotations in spring?

The shortest way is: @RequestMapping({"", "/", "welcome"})

Although you can also do:

  • @RequestMapping(value={"", "/", "welcome"})
  • @RequestMapping(path={"", "/", "welcome"})

How to hide a button programmatically?

In Kotlin

myButton.visibility = View.GONE

Asp.net Validation of viewstate MAC failed

I had this problem, and for me the answer was different than the other answers to this question.

I have an application with a lot of customers. I catch all error in the application_error in global.asax and I send myself an email with the error detail. After I published a new version of my apps, I began receiving a lot of Validation of viewstate MAC failed error message.

After a day of searching I realized that I have a timer in my apps, that refresh an update panel every minute. So when I published a new version of my apps, and some customer have left her computer open on my website. I receive an error message every time that the timer refresh because the actual viewstate does not match with the new one. I received this message until all customers closed the website or refresh their browser to get the new version.

I'm sorry for my English, and I know that my case is very specific, but if it can help someone to save a day, I think that it is a good thing.

Token Authentication vs. Cookies

Use Token when...

Federation is desired. For example, you want to use one provider (Token Dispensor) as the token issuer, and then use your api server as the token validator. An app can authenticate to Token Dispensor, receive a token, and then present that token to your api server to be verified. (Same works with Google Sign-In. Or Paypal. Or Salesforce.com. etc)

Asynchrony is required. For example, you want the client to send in a request, and then store that request somewhere, to be acted on by a separate system "later". That separate system will not have a synchronous connection to the client, and it may not have a direct connection to a central token dispensary. a JWT can be read by the asynchronous processing system to determine whether the work item can and should be fulfilled at that later time. This is, in a way, related to the Federation idea above. Be careful here, though: JWT expire. If the queue holding the work item does not get processed within the lifetime of the JWT, then the claims should no longer be trusted.

Cient Signed request is required. Here, request is signed by client using his private key and server would validate using already registered public key of the client.

How to read lines of a file in Ruby

Don't forget that if you are concerned about reading in a file that might have huge lines that could swamp your RAM during runtime, you can always read the file piece-meal. See "Why slurping a file is bad".

File.open('file_path', 'rb') do |io|
  while chunk = io.read(16 * 1024) do
    something_with_the chunk
    # like stream it across a network
    # or write it to another file:
    # other_io.write chunk
  end
end

Javascript select onchange='this.form.submit()'

My psychic debugging skills tell me that your submit button is named submit.
Therefore, form.submit refers to the button rather than the method.

Rename the button to something else so that form.submit refers to the method again.

"Instantiating" a List in Java?

A List in java is an interface that defines certain qualities a "list" must have. Specific list implementations, such as ArrayList implement this interface and flesh out how the various methods are to work. What are you trying to accomplish with this list? Most likely, one of the built-in lists will work for you.

What version of JBoss I am running?

You can retrieve information about the version of your JBoss EAP installation by running the same script used to start the server with the -V switch. For Linux and Unix installations this script is run.sh and on Microsoft Windows installations it is run.bat. Regardless of platform the script is located in $JBOSS_HOME/bin. Using these scripts to actually start your server is dealt with in Chapter 4, Launching the JBoss EAP Server.

Loop through all the rows of a temp table and call a stored procedure for each row

you could use a cursor:

DECLARE @id int
DECLARE @pass varchar(100)

DECLARE cur CURSOR FOR SELECT Id, Password FROM @temp
OPEN cur

FETCH NEXT FROM cur INTO @id, @pass

WHILE @@FETCH_STATUS = 0 BEGIN
    EXEC mysp @id, @pass ... -- call your sp here
    FETCH NEXT FROM cur INTO @id, @pass
END

CLOSE cur    
DEALLOCATE cur

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

How do you resize a form to fit its content automatically?

You could calculate the required height of the TreeView, by figuring out the height of a node, multiplying it by the number of nodes, then setting the form's MinimumSize property accordingly.

// assuming the treeview is populated!
nodeHeight = treeview1.Nodes[0].Bounds.Height;

this.MaximumSize = new Size(someMaximumWidth, someMaximumHeight);

int requiredFormHeight = (treeView1.GetNodeCount(true) * nodeHeight);

this.MinimumSize = new Size(this.Width, requiredFormHeight);

NB. This assumes though that the treeview1 is the only control on the form. When setting the requiredFormHeight variable you'll need to allow for other controls and height requirements surrounding the treeview, such as the tabcontrol you mentioned.

(I would however agree with @jgauffin and assess the rationale behind the requirement to resize a form everytime it loads without the user's consent - maybe let the user position and size the form and remember that instead??)

How to grep and replace

This works best for me on OS X:

grep -r -l 'searchtext' . | sort | uniq | xargs perl -e "s/matchtext/replacetext/" -pi

Source: http://www.praj.com.au/post/23691181208/grep-replace-text-string-in-files

What is the @Html.DisplayFor syntax for?

Html.DisplayFor() will render the DisplayTemplate that matches the property's type.

If it can't find any, I suppose it invokes .ToString().


If you don't know about display templates, they're partial views that can be put in a DisplayTemplates folder inside the view folder associated to a controller.


Example:

If you create a view named String.cshtml inside the DisplayTemplates folder of your views folder (e.g Home, or Shared) with the following code:

@model string

@if (string.IsNullOrEmpty(Model)) {
   <strong>Null string</strong>
}
else {
   @Model
}

Then @Html.DisplayFor(model => model.Title) (assuming that Title is a string) will use the template and display <strong>Null string</strong> if the string is null, or empty.

How to read html from a url in python 3

urllib.request.urlopen(url).read() should return you the raw HTML page as a string.

How can I use break or continue within for loop in Twig template?

From docs TWIG docs:

Unlike in PHP, it's not possible to break or continue in a loop.

But still:

You can however filter the sequence during iteration which allows you to skip items.

Example 1 (for huge lists you can filter posts using slice, slice(start, length)):

{% for post in posts|slice(0,10) %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

Example 2:

{% for post in posts if post.id < 10 %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

You can even use own TWIG filters for more complexed conditions, like:

{% for post in posts|onlySuperPosts %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

require 'date'

current_time = DateTime.now

current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"

current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"

How to write a foreach in SQL Server?

This generally (almost always) performs better than a cursor and is simpler:

DECLARE @PractitionerList TABLE(PracticionerID INT)
DECLARE @PracticionerID INT
    
INSERT @PractitionerList(PracticionerID)
SELECT PracticionerID
FROM Practitioner
    
WHILE(1 = 1)
BEGIN
            
    SET @PracticionerID = NULL
    SELECT TOP(1) @PracticionerID = PracticionerID
    FROM @PractitionerList
    
    IF @PracticionerID IS NULL
        BREAK
            
    PRINT 'DO STUFF'
    
    DELETE TOP(1) FROM @PractitionerList
    
END

What is the difference between iterator and iterable and how to use them?

Basically speaking, both of them are very closely related to each other.

Consider Iterator to be an interface which helps us in traversing through a collection with the help of some undefined methods like hasNext(), next() and remove()

On the flip side, Iterable is another interface, which, if implemented by a class forces the class to be Iterable and is a target for For-Each construct. It has only one method named iterator() which comes from Iterator interface itself.

When a collection is iterable, then it can be iterated using an iterator.

For understanding visit these:

ITERABLE: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java

ITERATOR http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

jQuery UI Dialog Box - does not open after being closed

 <button onClick="abrirOpen()">Open Dialog</button>

<script type="text/javascript">
var $dialogo = $("<div></div>").html("Aqui tu contenido(here your content)").dialog({
       title: "Dialogo de UI",
       autoOpen: false,
       close: function(ev, ui){
               $(this).dialog("destroy");
       }
 function abrirOpen(){
       $dialogo.dialog("open");
 }
});

//**Esto funciona para mi... (this works for me)**
</script>

How do I set default values for functions parameters in Matlab?

Another slightly less hacky way is

function output = fun(input)
   if ~exist('input','var'), input='BlahBlahBlah'; end
   ...
end

What is the correct syntax of ng-include?

try this

<div ng-app="myApp" ng-controller="customersCtrl"> 
  <div ng-include="'myTable.htm'"></div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
    $http.get("customers.php").then(function (response) {
        $scope.names = response.data.records;
    });
});
</script>

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

how to create insert new nodes in JsonNode?

These methods are in ObjectNode: the division is such that most read operations are included in JsonNode, but mutations in ObjectNode and ArrayNode.

Note that you can just change first line to be:

ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type

or

ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast

Tooltip with HTML content without JavaScript

Using the title attribute:

_x000D_
_x000D_
<a href="#" title="Tooltip here">Link</a>
_x000D_
_x000D_
_x000D_

How do I debug error ECONNRESET in Node.js?

I had this Error too and was able to solve it after days of debugging and analysis:

my solution

For me VirtualBox (for Docker) was the Problem. I had Port Forwarding configured on my VM and the error only occured on the forwarded port.

general conclusions

The following observations may save you days of work I had to invest:

  • For me the problem only occurred on connections from localhost to localhost on one port. -> check changing any of these constants solves the problem.
  • For me the problem only occurred on my machine -> let someone else try it.
  • For me the problem only occurred after a while and couldn't be reproduced reliably
  • My Problem couldn't be inspected with any of nodes or expresses (debug-)tools. -> don't waste time on this

-> figure out if something is messing around with your network (-settings), like VMs, Firewalls etc., this is probably the cause of the problem.

How to Convert unsigned char* to std::string in C++?

If has access to CryptoPP

Readable Hex String to unsigned char

std::string& hexed = "C23412341324AB";
uint8_t      buffer[64] = {0};
StringSource ssk(hexed, true,
            new HexDecoder(new ArraySink(buffer,sizeof(buffer))));

And back

std::string hexed;
uint8_t val[32]  = {0};
StringSource ss(val, sizeof(val), true,new HexEncoder(new StringSink(hexed));
// val == buffer

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

jQuery Mobile how to check if button is disabled?

Faced with the same issue when trying to check if a button is disabled. I've tried a variety of approaches, such as btn.disabled, .is(':disabled'), .attr('disabled'), .prop('disabled'). But no one works for me.

Some, for example .disabled or .is(':disabled') returned undefined and other like .attr('disabled') returned the wrong result - false when the button was actually disabled.

But only one technique works for me: .is('[disabled]') (with square brackets).

So to determine if a button is disabled try this:

$("#myButton").is('[disabled]');

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Instantiate and Present a viewController in Swift

Swift 4.2 updated code is

let storyboard = UIStoryboard(name: "StoryboardNameHere", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerNameHere")
self.present(controller, animated: true, completion: nil)

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Bash script to cd to directory with spaces in pathname

use double quotes

go () 
{ 
    cd "$*"
}

How do I position an image at the bottom of div?

Using flexbox:

HTML:

<div class="wrapper">
    <img src="pikachu.gif"/>
</div>

CSS:

.wrapper {
    height: 300px;
    width: 300px;
    display: flex;
    align-items: flex-end;
}

As requested in some comments on another answer, the image can also be horizontally centred with justify-content: center;

Ways to circumvent the same-origin policy

Well, I used curl in PHP to circumvent this. I have a webservice running in port 82.

<?php

$curl = curl_init();
$timeout = 30;
$ret = "";
$url="http://localhost:82/put_val?val=".$_GET["val"];
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl, CURLOPT_MAXREDIRS, 20);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
$text = curl_exec($curl);
echo $text;

?>

Here is the javascript that makes the call to the PHP file

function getdata(obj1, obj2) {

    var xmlhttp;

    if (window.XMLHttpRequest)
            xmlhttp=new XMLHttpRequest();
    else
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","phpURLFile.php?eqp="+obj1+"&val="+obj2,true);
    xmlhttp.send();
}

My HTML runs on WAMP in port 80. So there we go, same origin policy has been circumvented :-)

Do Git tags only apply to the current branch?

CharlesB's answer and helmbert's answer are both helpful, but it took me a while to understand them. Here's another way of putting it:

  • A tag is a pointer to a commit, and commits exist independently of branches.
    • It is important to understand that tags have no direct relationship with branches - they only ever identify a commit.
      • That commit can be pointed to from any number of branches - i.e., it can be part of the history of any number of branches - including none.
    • Therefore, running git show <tag> to see a tag's details contains no reference to any branches, only the ID of the commit that the tag points to.
      • (Commit IDs (a.k.a. object names or SHA-1 IDs) are 40-character strings composed of hex. digits that are hashes over the contents of a commit; e.g.: 6f6b5997506d48fc6267b0b60c3f0261b6afe7a2)
  • Branches come into play only indirectly:
    • At the time of creating a tag, by implying the commit that the tag will point to:
      • Not specifying a target for a tag defaults to the current branch's most recent commit (a.k.a. HEAD); e.g.:
        • git tag v0.1.0 # tags HEAD of *current* branch
      • Specifying a branch name as the tag target defaults to that branch's most recent commit; e.g.:
        • git tag v0.1.0 develop # tags HEAD of 'develop' branch
      • (As others have noted, you can also specify a commit ID explicitly as the tag's target.)
    • When using git describe to describe the current branch:
      • git describe [--tags] describes the current branch in terms of the commits since the most recent [possibly lightweight] tag in this branch's history.
      • Thus, the tag referenced by git describe may NOT reflect the most recently created tag overall.

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

How do I localize the jQuery UI Datepicker?

This solution may help.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
  var userLang = navigator.language || navigator.userLanguage;_x000D_
_x000D_
  var options = $.extend({},_x000D_
    $.datepicker.regional["ja"], {_x000D_
      dateFormat: "yy/mm/dd",_x000D_
      changeMonth: true,_x000D_
      changeYear: true,_x000D_
      highlightWeek: true_x000D_
    }_x000D_
  );_x000D_
_x000D_
  $("#japaneseCalendar").datepicker(options);_x000D_
});
_x000D_
#ui-datepicker-div {_x000D_
  font-size: 14px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <link rel="stylesheet" type="text/css"_x000D_
          href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">_x000D_
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<h3>Japanese JQuery UI Datepicker</h3>_x000D_
<input type="text" id="japaneseCalendar"/>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to edit hosts file via CMD?

echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts

the >> appends the output of echo to the file.

Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.

First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.

Second, it requires you to add an entry for every host name on a domain; just adding websitename.com will not block www.websitename.com, for example.

CALL command vs. START with /WAIT option

Call

Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call. Call has no effect at the command-line when used outside of a script or batch file. https://technet.microsoft.com/en-us/library/bb490873.aspx

Start

Starts a separate Command Prompt window to run a specified program or command. Used without parameters, start opens a second command prompt window. https://technet.microsoft.com/en-us/library/bb491005.aspx

How to name variables on the fly?

FAQ says:

If you have

varname <- c("a", "b", "d")

you can do

get(varname[1]) + 2

for

a + 2

or

assign(varname[1], 2 + 2)

for

a <- 2 + 2

So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.

Syntax for assign: assign(x, value)

x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.

value: value to be assigned to x.

How do you set the EditText keyboard to only consist of numbers on Android?

If you want to show just numbers without characters, put this line of code inside your XML file android:inputType="number". The output:

enter image description here

If you want to show a number keyboard that also shows characters, put android:inputType="phone" on your XML. The output (with characters):

with characters

And if you want to show a number keyboard that masks your input just like a password, put android:inputType="numberpassword". The output:

enter image description here

I'm really sorry if I only post the links of the screenshot, I want to do research on how to do really post images here but it might consume my time so here it is. I hope my post can help other people. Yes, my answer is duplicate with other answers posted here but to save other people's time that they might need to run their code before seeing the output, my post might save you some time.

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

I had the same problem with Java 7 u51. Only after I reset Internet Explorer it work again, Java was enabled in browser etc.

Internet options -> Advanced -> Reset...

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

What is the best IDE for PHP?

  • Best of all: Notepad ++ (Free and helpful with colors and link)
  • Average: NetBeans (Normal IDE)
  • Not good: Eclipse (It crashes when you don't wait for it)
  • Oh and I forget: Don't ever use JDeveloper :D

How to convert a single char into an int

The answers provided are great as long as you only want to handle Arabic numerals, and are working in an encoding where those numerals are sequential, and in the same place as ASCII.

This is almost always the case.

If it isn't then you need a proper library to help you.

Let's start with ICU.

  1. First convert the byte-string to a unicode string. (Left as an exercise for the reader).
  2. Then use uchar.h to look at each character.
  3. if we the character is UBool u_isdigit (UChar32 c)
  4. then the value is int32_t u_charDigitValue ( UChar32 c )

Or maybe ICU has some function to do it for you - I haven't looked at it in detail.

Submit a form using jQuery

$("form:first").submit();

See events/submit.

Testing the type of a DOM element in JavaScript

roenving is correct BUT you need to change the test to:

if(element.nodeType == 1) {
//code
}

because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp

Redirect all output to file in Bash

Use >> to append:

command >> file

How can I remove a trailing newline?

It looks like there is not a perfect analog for perl's chomp. In particular, rstrip cannot handle multi-character newline delimiters like \r\n. However, splitlines does as pointed out here. Following my answer on a different question, you can combine join and splitlines to remove/replace all newlines from a string s:

''.join(s.splitlines())

The following removes exactly one trailing newline (as chomp would, I believe). Passing True as the keepends argument to splitlines retain the delimiters. Then, splitlines is called again to remove the delimiters on just the last "line":

def chomp(s):
    if len(s):
        lines = s.splitlines(True)
        last = lines.pop()
        return ''.join(lines + last.splitlines())
    else:
        return ''

Go build: "Cannot find package" (even though GOPATH is set)

I solved this problem by set my go env GO111MODULE to off

go env -w  GO111MODULE=off

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

I use this for cleaning up data in test/development databases. You can filter by table name and record count.

DECLARE @sqlCommand VARCHAR(3000);
DECLARE @tableList TABLE(Value NVARCHAR(128));
DECLARE @TableName VARCHAR(128);
DECLARE @RecordCount INT;

-- get a cursor with a list of table names and their record counts
DECLARE MyCursor CURSOR FAST_FORWARD
FOR SELECT t.name TableName,
           i.rows Records
    FROM sysobjects t,
         sysindexes i
    WHERE 
          t.xtype = 'U'              -- only User tables
          AND i.id = t.id          
          AND i.indid IN(0, 1)       -- 0=Heap, 1=Clustered Index
          AND i.rows < 10            -- Filter by number of records in the table
          AND t.name LIKE 'Test_%';  -- Filter tables by name. You could also provide a list:
                                     -- AND t.name IN ('MyTable1', 'MyTable2', 'MyTable3');
                                     -- or a list of tables to exclude:
                                     -- AND t.name NOT IN ('MySpecialTable', ... );

OPEN MyCursor;

FETCH NEXT FROM MyCursor INTO @TableName, @RecordCount;

-- for each table name in the cursor, delete all records from that table:
WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @sqlCommand = 'DELETE FROM ' + @TableName;
        EXEC (@sqlCommand);
        FETCH NEXT FROM MyCursor INTO @TableName, @RecordCount;
    END;

CLOSE MyCursor;
DEALLOCATE MyCursor;

Reference info:

How to print matched regex pattern using awk?

If you know what column the text/pattern you're looking for (e.g. "yyy") is in, you can just check that specific column to see if it matches, and print it.

For example, given a file with the following contents, (called asdf.txt)

xxx yyy zzz

to only print the second column if it matches the pattern "yyy", you could do something like this:

awk '$2 ~ /yyy/ {print $2}' asdf.txt

Note that this will also match basically any line where the second column has a "yyy" in it, like these:

xxx yyyz zzz
xxx zyyyz