Programs & Examples On #Intptr

IntPtr is a .NET Framework platform-specific type that is used to represent a pointer or a handle.

Just what is an IntPtr exactly?

Here's an example:

I'm writing a C# program that interfaces with a high-speed camera. The camera has its own driver that acquires images and loads them into the computer's memory for me automatically.

So when I'm ready to bring the latest image into my program to work with, the camera driver provides me with an IntPtr to where the image is ALREADY stored in physical memory, so I don't have to waste time/resources creating another block of memory to store an image that's in memory already. The IntPtr just shows me where the image already is.

char *array and char array[]

No, you're creating an array, but there's a big difference:

char *string = "Some CONSTANT string";
printf("%c\n", string[1]);//prints o
string[1] = 'v';//INVALID!!

The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:

char string[] = "Some string";

creates the same, read only, constant string, and copies it to the stack array. That's why:

string[1] = 'v';

Is valid in the latter case.
If you write:

char string[] = {"some", " string"};

the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:

char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
//this is a bit silly, because it's the same as char string[] = "some string";
//or
char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
//or
char string[][10] = {"some", " string"};

Where the last version gives you an array of strings (arrays of chars) that you actually can edit...

How can I change the date format in Java?

Or you could go the regex route:

String date = "10/07/2010";
String newDate = date.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3/$2/$1");
System.out.println(newDate);

It works both ways too. Of course this won't actually validate your date and will also work for strings like "21432/32423/52352". You can use "(\\d{2})/(\\d{2})/(\\d{4}" to be more exact in the number of digits in each group, but it will only work from dd/MM/yyyy to yyyy/MM/dd and not the other way around anymore (and still accepts invalid numbers in there like 45). And if you give it something invalid like "blabla" it will just return the same thing back.

I can’t find the Android keytool

The 4-Step Answer above worked for me, but it returns the SH1-key... but Google asks for the MD5-key to generate your API key.

One needs simply to add a '-v' in the command in step 3. -like so:

Updated 4-Step Answer

Ok I did this in Windows 7 32-bit system.

step 1: go to - C:\Program Files\Java\jdk1.7.0\bin - and run jarsigner.exe first ( double click)

step2: locate debug.keystore (in Eclipse: Windows/Preferences/Android/build..), in my case it was - C:\Users\MyPcName.android

step3: open command prompt and go to dir - C:\Program Files\Java\jdk1.7.0\bin and give the following command: keytool -v -list -keystore "C:\Users\MyPcName.android\debug.keystore"

step4: it will ask for Keystore password now. The default is 'android'

Visual Studio opens the default browser instead of Internet Explorer

Scott Guthrie has made a post on how to change Visual Studio's default browser:

1) Right click on a .aspx page in your solution explorer

2) Select the "browse with" context menu option

3) In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename

4) Click the "Set as Default" button to make this the default browser when you run any page on the site.

I however dislike the fact that this isn't as straightforward as it should be.

ASP.NET: Session.SessionID changes between requests

Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:

if (HttpContext.Current.Response.Cookies.Count > 0)
        {
            foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
            {
                if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
                {
                    HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
                }
            }
        }

How to ping ubuntu guest on VirtualBox

If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces still configured for eth0.

Diagnose:

ethtool -i eth0
Cannot get driver information: no such device

Find your interfaces:

ls /sys/class/net
eth1 eth2 lo

Fix it:

Edit /etc/networking/interfaces and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)

:%s/eth0/eth2/g

How to remove the default arrow icon from a dropdown list (select element)?

Just wanted to complete the thread. To be very clear this does not works in IE9, however we can do it by little css trick.

<div class="customselect">
    <select>
    <option>2000</option>
    <option>2001</option>
    <option>2002</option>
    </select>
</div>

.customselect {
    width: 80px;
    overflow: hidden;
   border:1px solid;
}

.customselect select {
   width: 100px;
   border:none;
  -moz-appearance: none;
   -webkit-appearance: none;
   appearance: none;
}

Generate signed apk android studio

Read this my answer here

How do I export a project in the Android studio?

This will guide you step by step to generate signed APK and how to create keystore file from Android Studio.

From the link you can do it easily as I added the screenshot of it step by step.

Short answer

If you have Key-store file then you can do same simply.

Go to Build then click on Generate Signed APK

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

printing all contents of array in C#

If it's an array of strings you can use Aggregate

var array = new string[] { "A", "B", "C", "D"};
Console.WriteLine(array.Aggregate((result, next) => $"{result}, {next}")); // A, B, C, D

that way you can reverses the order by changing the order of the parameters like so

Console.WriteLine(array.Aggregate((result, next) => $"{next}, {result}")); // D, C, B, A

An error when I add a variable to a string

You're missing your database name:

$sql = "SELECT ID, ListStID, ListEmail, Title FROM ".$entry_database." WHERE ID = ". $ReqBookID .";

And make sure that $entry_database isn't null or empty:

var_dump($entry_database);

Also notice that you don't need to have $ReqBookID in '' as if it's an Int.

How to check if Thread finished execution

You could fire an event from your thread when it finishes and subscribe to that.

Alternatively you can call Thread.Join() without any arguments:

Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.

Thread.Join(1) will:

Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.

In this case the specified time is 1 millisecond.

"call to undefined function" error when calling class method

You dont have a function named assign(), but a method with this name. PHP is not Java and in PHP you have to make clear, if you want to call a function

assign()

or a method

$object->assign()

In your case the call to the function resides inside another method. $this always refers to the object, in which a method exists, itself.

$this->assign()

Warning about `$HTTP_RAW_POST_DATA` being deprecated

; always_populate_raw_post_data = -1 in php.init remove comment of this line .. always_populate_raw_post_data = -1

How do I change column default value in PostgreSQL?

'SET' is forgotten

ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';

How to use comparison and ' if not' in python?

Why think? If not confuses you, switch your if and else clauses around to avoid the negation.

i want to make sure that ( u0 <= u < u0+step ) before do sth.

Just write that.

if u0 <= u < u0+step:
    "do sth" # What language is "sth"?  No vowels.  An odd-looking word.
else:
    u0 = u0+ step

Why overthink it?

If you need an empty if -- and can't work out the logic -- use pass.

 if some-condition-that's-too-complex-for-me-to-invert:
     pass
 else: 
     do real work here

Any reason to prefer getClass() over instanceof when generating .equals()?

Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:

class A { }

class B extends A { }

Object oA = new A();
Object oB = new B();

oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true

oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true

Inserting a Python datetime.datetime object into MySQL

Use Python method datetime.strftime(format), where format = '%Y-%m-%d %H:%M:%S'.

import datetime

now = datetime.datetime.utcnow()

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, %s)",
               ("name", 4, now.strftime('%Y-%m-%d %H:%M:%S')))

Timezones

If timezones are a concern, the MySQL timezone can be set for UTC as follows:

cursor.execute("SET time_zone = '+00:00'")

And the timezone can be set in Python:

now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)

MySQL Documentation

MySQL recognizes DATETIME and TIMESTAMP values in these formats:

As a string in either 'YYYY-MM-DD HH:MM:SS' or 'YY-MM-DD HH:MM:SS' format. A “relaxed” syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012@12@31 11^30^45' are equivalent.

The only delimiter recognized between a date and time part and a fractional seconds part is the decimal point.

The date and time parts can be separated by T rather than a space. For example, '2012-12-31 11:30:45' '2012-12-31T11:30:45' are equivalent.

As a string with no delimiters in either 'YYYYMMDDHHMMSS' or 'YYMMDDHHMMSS' format, provided that the string makes sense as a date. For example, '20070523091528' and '070523091528' are interpreted as '2007-05-23 09:15:28', but '071122129015' is illegal (it has a nonsensical minute part) and becomes '0000-00-00 00:00:00'.

As a number in either YYYYMMDDHHMMSS or YYMMDDHHMMSS format, provided that the number makes sense as a date. For example, 19830905132800 and 830905132800 are interpreted as '1983-09-05 13:28:00'.

minimize app to system tray

This is the method I use in my applications, it's fairly simple and self explanatory but I'm happy to give more details in answer to your comments.

    public Form1()
    {
        InitializeComponent();

        // When window state changed, trigger state update.
        this.Resize += SetMinimizeState;

        // When tray icon clicked, trigger window state change.       
        systemTrayIcon.Click += ToggleMinimizeState;
    }      

    // Toggle state between Normal and Minimized.
    private void ToggleMinimizeState(object sender, EventArgs e)
    {    
        bool isMinimized = this.WindowState == FormWindowState.Minimized;
        this.WindowState = (isMinimized) ? FormWindowState.Normal : FormWindowState.Minimized;
    }

    // Show/Hide window and tray icon to match window state.
    private void SetMinimizeState(object sender, EventArgs e)
    {    
        bool isMinimized = this.WindowState == FormWindowState.Minimized;

        this.ShowInTaskbar = !isMinimized;           
        systemTrayIcon.Visible = isMinimized;
        if (isMinimized) systemTrayIcon.ShowBalloonTip(500, "Application", "Application minimized to tray.", ToolTipIcon.Info);
    }

How to start and stop android service from a adb shell?

You need to add android:exported="true" to start service from ADB command line. Then your manifest looks something like this:

<!-- Service declared in manifest -->
<service
    android:name=".YourServiceName"
    android:exported="true"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="com.your.package.name.YourServiceName"/>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</service> <!-- Note: Service is exported to start it using ADB command -->

And then from ADB

To start service:

adb shell am startservice com.your.package.name/.YourServiceName

To stop service (on Marshmallow):

adb shell am stopservice com.your.package.name/.YourServiceName

To stop service (on Jelly Bean):

adb shell am force-stop com.your.package.name

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

Use multiple custom fonts using @font-face?

You simply add another @font-face rule:

@font-face {
    font-family: CustomFont;
    src: url('CustomFont.ttf');
}

@font-face {
    font-family: CustomFont2;
    src: url('CustomFont2.ttf');
}

If your second font still doesn't work, make sure you're spelling its typeface name and its file name correctly, your browser caches are behaving, your OS isn't messing around with a font of the same name, etc.

Joining three tables using MySQL

Simply use:

select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid 

Can you get the number of lines of code from a GitHub repository?

npm install sloc -g
git clone --depth 1 https://github.com/vuejs/vue/
sloc ".\vue\src" --format cli-table
rm -rf ".\vue\"

Instructions and Explanation

  1. Install sloc from npm, a command line tool (Node.js needs to be installed).
npm install sloc -g
  1. Clone shallow repository (faster download than full clone).
git clone --depth 1 https://github.com/facebook/react/
  1. Run sloc and specifiy the path that should be analyzed.
sloc ".\react\src" --format cli-table

sloc supports formatting the output as a cli-table, as json or csv. Regular expressions can be used to exclude files and folders (Further information on npm).

  1. Delete repository folder (optional)

Powershell: rm -r -force ".\react\" or on Mac/Unix: rm -rf ".\react\"

Screenshots of the executed steps (cli-table):

sloc output as acli-table

sloc output (no arguments):

sloc output without arguments

It is also possible to get details for every file with the --details option:

sloc ".\react\src" --format cli-table --details     

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

How to style readonly attribute with CSS?

To be safe you may want to use both...

input[readonly], input[readonly="readonly"] {
    /*styling info here*/
}

The readonly attribute is a "boolean attribute", which can be either blank or "readonly" (the only valid values). http://www.whatwg.org/specs/web-apps/current-work/#boolean-attribute

If you are using something like jQuery's .prop('readonly', true) function, you'll end up needing [readonly], whereas if you are using .attr("readonly", "readonly") then you'll need [readonly="readonly"].


Correction: You only need to use input[readonly]. Including input[readonly="readonly"] is redundant. See https://stackoverflow.com/a/19645203/1766230

How do you pass a function as a parameter in C?

You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

This is the working solution to this problem I found.

sudo apt-get clean
cd /var/lib/apt
sudo mv lists lists.old
sudo mkdir -p lists/partial
sudo apt-get clean
sudo apt-get update

Catching "Maximum request length exceeded"

It can be checked via:

        var httpException = ex as HttpException;
        if (httpException != null)
        {
            if (httpException.WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
            {
                // Request too large

                return;

            }
        }

How do I sort a vector of pairs based on the second element of the pair?

EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution

std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

Just use a custom comparator (it's an optional 3rd argument to std::sort)

struct sort_pred {
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    }
};

std::sort(v.begin(), v.end(), sort_pred());

If you're using a C++11 compiler, you can write the same using lambdas:

std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
    return left.second < right.second;
});

EDIT: in response to your edits to your question, here's some thoughts ... if you really wanna be creative and be able to reuse this concept a lot, just make a template:

template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
    bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
        Pred p;
        return p(left.second, right.second);
    }
};

then you can do this too:

std::sort(v.begin(), v.end(), sort_pair_second<int, int>());

or even

std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());

Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P

how to create dynamic two dimensional array in java?

List<Integer>[] array;  
array = new List<Integer>[10]; 

this the second case in @TofuBeer's answer is incorrect. because can't create arrays with generics. u can use:

List<List<Integer>> array = new ArrayList<>();

jquery - Check for file extension before uploading

 $("#file-upload").change(function () {

    var validExtensions = ["jpg","pdf","jpeg","gif","png"]
    var file = $(this).val().split('.').pop();
    if (validExtensions.indexOf(file) == -1) {
        alert("Only formats are allowed : "+validExtensions.join(', '));
    }

});

Find file in directory from command line

When I was in the UNIX world (using tcsh (sigh...)), I used to have all sorts of "find" aliases/scripts setup for searching for files. I think the default "find" syntax is a little clunky, so I used to have aliases/scripts to pipe "find . -print" into grep, which allows you to use regular expressions for searching:

# finds all .java files starting in current directory
find . -print | grep '\.java'

#finds all .java files whose name contains "Message"
find . -print | grep '.*Message.*\.java'

Of course, the above examples can be done with plain-old find, but if you have a more specific search, grep can help quite a bit. This works pretty well, unless "find . -print" has too many directories to recurse through... then it gets pretty slow. (for example, you wouldn't want to do this starting in root "/")

How to run single test method with phpunit?

Following command will execute exactly testSaveAndDrop test.

phpunit --filter '/::testSaveAndDrop$/' escalation/EscalationGroupTest.php

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Difference between matches() and find() in Java Regex

matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.

Django CharField vs TextField

In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.

Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.

How can I remove file extension from a website address?

Tony, your script is ok, but if you have 100 files? Need add this code in all these :

include_once('scripts.php');
strip_php_extension();

I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D

Tab space instead of multiple non-breaking spaces ("nbsp")?

Try &emsp;

It is equivalent to four &nbsp;s.

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

This isn't exactly an "asking for yes or no" but just a hack: alias the hg push ... not to hgpushrepo but to hgpushrepoconfirmedpush and by the time I can spell out the whole thing, the left brain has made a logical choice.

Android, How to read QR code in my application?

In android studio, You can use bellow process to create & Read QR Code &image look like bellw enter image description here

  1. Create a android studio empty project
  2. Add library in app.gradle

    compile 'com.google.zxing:core:3.2.1'
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    
  3. In activity.main xml use bellow..

     <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context="com.example.enamul.qrcode.MainActivity">
    
    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="20dp"
      android:orientation="vertical">
    
    
    <EditText
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="Enter Text Here" />
    
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/editText"
        android:text="Click Here TO generate qr code"
        android:textAllCaps="false"
        android:textSize="16sp" />
    
    
    <Button
        android:id="@+id/btnScan"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_below="@+id/editText"
        android:text="Scan Your QR Code"
        android:textAllCaps="false"
        android:textSize="16sp" />
    
    <TextView
        android:id="@+id/tv_qr_readTxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
    
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@+id/button"
        android:src="@android:drawable/ic_dialog_email" />
    
    
    </LinearLayout>
    
    </LinearLayout>
    
  4. In MainActivity you can use bellow code

    public class MainActivity extends AppCompatActivity {
      ImageView imageView;
      Button button;
      Button btnScan;
      EditText editText;
      String EditTextValue ;
      Thread thread ;
      public final static int QRcodeWidth = 350 ;
      Bitmap bitmap ;
    
      TextView tv_qr_readTxt;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
    
        imageView = (ImageView)findViewById(R.id.imageView);
        editText = (EditText)findViewById(R.id.editText);
        button = (Button)findViewById(R.id.button);
        btnScan = (Button)findViewById(R.id.btnScan);
         tv_qr_readTxt = (TextView) findViewById(R.id.tv_qr_readTxt);
    
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
    
    
            if(!editText.getText().toString().isEmpty()){
                EditTextValue = editText.getText().toString();
    
                try {
                    bitmap = TextToImageEncode(EditTextValue);
    
                    imageView.setImageBitmap(bitmap);
    
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
            else{
                editText.requestFocus();
                Toast.makeText(MainActivity.this, "Please Enter Your Scanned Test" , Toast.LENGTH_LONG).show();
            }
    
          }
      });
    
    
    btnScan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
            IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
            integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
            integrator.setPrompt("Scan");
            integrator.setCameraId(0);
            integrator.setBeepEnabled(false);
            integrator.setBarcodeImageEnabled(false);
            integrator.initiateScan();
    
         }
       });
        }
    
    
     Bitmap TextToImageEncode(String Value) throws WriterException {
       BitMatrix bitMatrix;
        try {
        bitMatrix = new MultiFormatWriter().encode(
                Value,
                BarcodeFormat.DATA_MATRIX.QR_CODE,
                QRcodeWidth, QRcodeWidth, null
        );
    
        } catch (IllegalArgumentException Illegalargumentexception) {
    
         return null;
       }
      int bitMatrixWidth = bitMatrix.getWidth();
    
      int bitMatrixHeight = bitMatrix.getHeight();
    
      int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];
    
      for (int y = 0; y < bitMatrixHeight; y++) {
          int offset = y * bitMatrixWidth;
    
         for (int x = 0; x < bitMatrixWidth; x++) {
    
             pixels[offset + x] = bitMatrix.get(x, y) ?
                    getResources().getColor(R.color.QRCodeBlackColor):getResources().getColor(R.color.QRCodeWhiteColor);
          }
        }
        Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);
    
       bitmap.setPixels(pixels, 0, 350, 0, 0, bitMatrixWidth, bitMatrixHeight);
       return bitmap;
    }
    
    
    
    
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
      if(result != null) {
        if(result.getContents() == null) {
            Log.e("Scan*******", "Cancelled scan");
    
         } else {
            Log.e("Scan", "Scanned");
    
            tv_qr_readTxt.setText(result.getContents());
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
         }
      } else {
          // This is important, otherwise the result will not be passed to the fragment
        super.onActivityResult(requestCode, resultCode, data);
         }
       }
     }
    
  5. You can download full source code from GitHub. GitHub link is : https://github.com/enamul95/QRCode

Is it possible to have a multi-line comments in R?

No multi-line comments in R as of version 2.12 and unlikely to change. In most environments, you can comment blocks by highlighting and toggle-comment. In emacs, this is 'M-x ;'.

How do I format date and time on ssrs report?

=Format(Now(), "MM/dd/yyyy hh:mm tt")

Output:

04/12/2013 05:09 PM

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

@OneToMany(mappedBy = "xxxx", cascade={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}) worked for me.

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Looks like the installed driver was in bad state. Here is what I did to make it work:

  1. Delete the device from Device Manager.
  2. Rescan for hardware changes.
  3. "Slate 21" will show up with "Unknown driver" status.
  4. Click on "Update Driver" and select /extras/google/usb_driver
  5. Device Manager will find the driver and warn you about installing it. Select "Yes."

This time the device got installed properly.

Note that I didn't have to modify winusb.inf file or update any other driver.

Hope this helps.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Try the following code to display scroll bar always on your page,

::-webkit-scrollbar {
  -webkit-appearance: none;
  width: 10px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
  -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

this will always show the vertical and horizontal scroll bar on your page. If you need only a vertical scroll bar then put overflow-x: hidden

Is there a typical state machine implementation pattern?

there is also the logic grid which is more maintainable as the state machine gets bigger

Communicating between a fragment and an activity - best practices

The easiest way to communicate between your activity and fragments is using interfaces. The idea is basically to define an interface inside a given fragment A and let the activity implement that interface.

Once it has implemented that interface, you could do anything you want in the method it overrides.

The other important part of the interface is that you have to call the abstract method from your fragment and remember to cast it to your activity. It should catch a ClassCastException if not done correctly.

There is a good tutorial on Simple Developer Blog on how to do exactly this kind of thing.

I hope this was helpful to you!

How to sleep for five seconds in a batch file/cmd

PING -n 60 127.0.0.1>nul

in case your LAN adapter is not available.

Why is the time complexity of both DFS and BFS O( V + E )

DFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or BACK
  • Method incidentEdges is called once for each vertex
  • DFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

BFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or CROSS
  • Each vertex is inserted once into a sequence Li
  • Method incidentEdges is called once for each vertex
  • BFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

Java: how do I initialize an array size if it's unknown?

If you want to stick to an array then this way you can make use. But its not good as compared to List and not recommended. However it will solve your problem.

import java.util.Scanner;

public class ArrayModify {

    public static void main(String[] args) {
        int[] list;
        String st;
        String[] stNew;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter Numbers: "); // If user enters 5 6 7 8 9 
        st = scan.nextLine();
        stNew = st.split("\\s+");
        list = new int[stNew.length]; // Sets array size to 5

        for (int i = 0; i < stNew.length; i++){
            list[i] =  Integer.parseInt(stNew[i]);
            System.out.println("You Enterred: " + list[i]);
        }
    }
}

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

Fastest way to update 120 Million records

If the table has an index which you can iterate over I would put update top(10000) statement in a while loop moving over the data. That would keep the transaction log slim and won't have such a huge impact on the disk system. Also, I would recommend to play with maxdop option (setting it closer to 1).

PHP PDO with foreach and fetch

This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.

If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.

Can I set text box to readonly when using Html.TextBoxFor?

The following snippet worked for me.

@Html.TextBoxFor(m => m.Crown, new { id = "", @style = "padding-left:5px", @readonly = "true" }) 

Linux command for extracting war file?

Extracting a specific folder (directory) within war file:

# unzip <war file> '<folder to extract/*>' -d <destination path> 
unzip app##123.war 'some-dir/*' -d extracted/

You get ./extracted/some-dir/ as a result.

Python threading.timer - repeat function every 'n' seconds

I have implemented a class that works as a timer.

I leave the link here in case anyone needs it: https://github.com/ivanhalencp/python/tree/master/xTimer

Rails.env vs RAILS_ENV

ENV['RAILS_ENV'] is now deprecated.

You should use Rails.env which is clearly much nicer.

R not finding package even after package installation

When you run

install.packages("whatever")

you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:

.libPaths()

If libPaths shows 2 locations, then paste into second one. Load library:

library(whatever)

Fixed.

How can I exclude directories from grep -R?

A simple working command:

root/dspace# grep -r --exclude-dir={log,assetstore} "creativecommons.org"

Above I grep for text "creativecommons.org" in current directory "dspace" and exclude dirs {log,assetstore}.

Done.

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

You can also use a formula in excel in order to convert this type of date to a date type excel can read: =DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))

And you get: 12/7/2016 from: Wed Dec 07 00:00:00 UTC 2016

Gradle build without tests

The accepted answer is the correct one.

OTOH, the way I previously solved this was to add the following to all projects:

test.onlyIf { ! Boolean.getBoolean('skip.tests') }

Run the build with -Dskip.tests=true and all test tasks will be skipped.

Find the most frequent number in a NumPy array

Expanding on this method, applied to finding the mode of the data where you may need the index of the actual array to see how far away the value is from the center of the distribution.

(_, idx, counts) = np.unique(a, return_index=True, return_counts=True)
index = idx[np.argmax(counts)]
mode = a[index]

Remember to discard the mode when len(np.argmax(counts)) > 1

How can I get the request URL from a Java Filter?

Is this what you're looking for?

if (request instanceof HttpServletRequest) {
 String url = ((HttpServletRequest)request).getRequestURL().toString();
 String queryString = ((HttpServletRequest)request).getQueryString();
}

To Reconstruct:

System.out.println(url + "?" + queryString);

Info on HttpServletRequest.getRequestURL() and HttpServletRequest.getQueryString().

What is an ORM, how does it work, and how should I use one?

Can anyone give me a brief explanation...

Sure.

ORM stands for "Object to Relational Mapping" where

  • The Object part is the one you use with your programming language ( python in this case )

  • The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )

  • And finally the Mapping part is where you do a bridge between your objects and your tables.

In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.

So let's say you have this object.

 class Employee:
      def __init__( self, name ): 
          self.__name = name

       def getName( self ):
           return self.__name

       #etc.

and the table

   create table employee(
          name varcar(10),
          -- etc  
    )

Using an ORM framework would allow you to map that object with a db record automagically and write something like:

   emp = Employee("Ryan")

   orm.save( emp )

And have the employee inserted into the DB.

Oops it was not that brief but I hope it is simple enough to catch other articles you read.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

This is a confusion between constructors and instances.

Remember that when you write a component in React:

class Greeter extends React.Component<any, any> {
    render() {
        return <div>Hello, {this.props.whoToGreet}</div>;
    }
}

You use it this way:

return <Greeter whoToGreet='world' />;

You don't use it this way:

let Greet = new Greeter();
return <Greet whoToGreet='world' />;

In the first example, we're passing around Greeter, the constructor function for our component. That's the correct usage. In the second example, we're passing around an instance of Greeter. That's incorrect, and will fail at runtime with an error like "Object is not a function".


The problem with this code

function renderGreeting(Elem: React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

is that it's expecting an instance of React.Component. What you want is a function that takes a constructor for React.Component:

function renderGreeting(Elem: new() => React.Component<any, any>) {
    return <span>Hello, <Elem />!</span>;
}

or similarly:

function renderGreeting(Elem: typeof React.Component) {
    return <span>Hello, <Elem />!</span>;
}

How to change the size of the radio button using CSS?

Directly you can not do this. [As per my knowledge].

You should use images to supplant the radio buttons. You can make them function in the same manner as the radio buttons inmost cases, and you can make them any size you want.

How do I add to the Windows PATH variable using setx? Having weird problems

I was facing the same problems and found a easy solution now.

Using pathman.

pathman /as %M2%

Adds for example %M2% to the system path. Nothing more and nothing less. No more problems getting a mixture of user PATH and system PATH. No more hardly trying to get the correct values from registry...

Tried at Windows 10

Sample settings.xml

The reference for the user-specific configuration for Maven is available on-line and it doesn't make much sense to share a settings.xml with you since these settings are user specific.

If you need to configure a proxy, have a look at the section about Proxies.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  ...
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.somewhere.com</host>
      <port>8080</port>
      <username>proxyuser</username>
      <password>somepassword</password>
      <nonProxyHosts>*.google.com|ibiblio.org</nonProxyHosts>
    </proxy>
  </proxies>
  ...
</settings>
  • id: The unique identifier for this proxy. This is used to differentiate between proxy elements.
  • active: true if this proxy is active. This is useful for declaring a set of proxies, but only one may be active at a time.
  • protocol, host, port: The protocol://host:port of the proxy, seperated into discrete elements.
  • username, password: These elements appear as a pair denoting the login and password required to authenticate to this proxy server.
  • nonProxyHosts: This is a list of hosts which should not be proxied. The delimiter of the list is the expected type of the proxy server; the example above is pipe delimited - comma delimited is also common

Enabling HTTPS on express.js

This is how its working for me. The redirection used will redirect all the normal http as well.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('certificates/private.key'),
  cert: fs.readFileSync('certificates/certificate.crt'),
  ca: fs.readFileSync('certificates/ca_bundle.crt')
};

// API file for interacting with MongoDB
const api = require('./server/routes/api');

// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
  if (req.headers['x-forwarded-proto'] == 'http') {
      return resp.redirect(301, 'https://' + req.headers.host + '/');
  } else {
      return next();
  }
});


http.createServer(app).listen(80)
https.createServer(options, app).listen(443);

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.

Install php-mcrypt on CentOS 6

The best way is to:

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm
yum localinstall php-mcrypt-5.3.3-3.el6.x86_64.rpm

wget http://dl.fedoraproject.org/pub/epel/6/x86_64/libmcrypt-2.5.8-9.el6.x86_64.rpm
yum localinstall libmcrypt-2.5.8-9.el6.x86_64.rpm

or go to: http://dl.fedoraproject.org/pub/epel/6/x86_64/ to match your version check from your info.php that is ok -- done!

How to use both onclick and target="_blank"

you can use

        <p><a href="/link/to/url" target="_blank"><button id="btn_id">Present Name </button></a></p>

What are all the possible values for HTTP "Content-Type" header?

As is defined in RFC 1341:

In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:

Content-Type := type "/" subtype *[";" parameter]

type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token

x-token := < The two characters "X-" followed, with no intervening white space, by any token >

subtype := token

parameter := attribute "=" value

attribute := token

value := token / quoted-string

token := 1*

tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values

And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).

As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).

Also note the comment above:

If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.

You'll notice that a lot of HTTP requests/responses include an X- header of some sort which are self defined, keep this in mind when validating the types.

What is copy-on-write?

I shall not repeat the same answer on Copy-on-Write. I think Andrew's answer and Charlie's answer have already made it very clear. I will give you an example from OS world, just to mention how widely this concept is used.

We can use fork() or vfork() to create a new process. vfork follows the concept of copy-on-write. For example, the child process created by vfork will share the data and code segment with the parent process. This speeds up the forking time. It is expected to use vfork if you are performing exec followed by vfork. So vfork will create the child process which will share data and code segment with its parent but when we call exec, it will load up the image of a new executable in the address space of the child process.

Easy way to get a test file into JUnit

If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:

public String loadResourceAsString(String fileName) throws IOException {
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
    String contents = scanner.useDelimiter("\\A").next();
    scanner.close();
    return contents;
}

"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).

How to Update/Drop a Hive Partition?

You can update a Hive partition by, for example:

ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18) 
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';

This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.

To drop a partition, you can do

ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);

Hope it helps!

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Recently released JDK 1.8.0_40 added support for JavaFX dialogs, alerts, etc. For example, to show a confirmation dialog, one would use the Alert class:

Alert alert = new Alert(AlertType.CONFIRMATION, "Delete " + selection + " ?", ButtonType.YES, ButtonType.NO, ButtonType.CANCEL);
alert.showAndWait();

if (alert.getResult() == ButtonType.YES) {
    //do stuff
}

Here's a list of added classes in this release:

INNER JOIN ON vs WHERE clause

I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

Strip spaces/tabs/newlines - python

Use str.split([sep[, maxsplit]]) with no sep or sep=None:

From docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Demo:

>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']

Use str.join on the returned list to get this output:

>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'

Finding a substring within a list in Python

This prints all elements that contain sub:

for s in filter (lambda x: sub in x, list): print (s)

How do you check if a JavaScript Object is a DOM Object?

The only way to guarentee you're checking an actual HTMLEement, and not just an object with the same properties as an HTML Element, is to determine if it inherits from Node, since its impossible to make a new Node() in JavaScript. (unless the native Node function is overwritten, but then you're out of luck). So:

_x000D_
_x000D_
function isHTML(obj) {_x000D_
    return obj instanceof Node;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
  isHTML(test),_x000D_
  isHTML(ok),_x000D_
  isHTML(p),_x000D_
  isHTML(o),_x000D_
  isHTML({_x000D_
    constructor: {_x000D_
      name: "HTML"_x000D_
    }_x000D_
  }),_x000D_
  isHTML({_x000D_
    __proto__: {_x000D_
      __proto__: {_x000D_
        __proto__: {_x000D_
          __proto__: {_x000D_
            constructor: {_x000D_
              constructor: { _x000D_
                name: "Function"_x000D_
                _x000D_
              },_x000D_
              name: "Node"_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
  }),_x000D_
)
_x000D_
<div id=test></div>_x000D_
<blockquote id="ok"></blockquote>_x000D_
<p id=p></p>_x000D_
<br id=o>_x000D_
<!--think of anything else you want--!>
_x000D_
_x000D_
_x000D_

Formatting floats without trailing zeros

OP would like to remove superflouous zeros and make the resulting string as short as possible.

I find the %g exponential formatting shortens the resulting string for very large and very small values. The problem comes for values that don't need exponential notation, like 128.0, which is neither very large or very small.

Here is one way to format numbers as short strings that uses %g exponential notation only when Decimal.normalize creates strings that are too long. This might not be the fastest solution (since it does use Decimal.normalize)

def floatToString (inputValue, precision = 3):
    rc = str(Decimal(inputValue).normalize())
    if 'E' in rc or len(rc) > 5:
        rc = '{0:.{1}g}'.format(inputValue, precision)        
    return rc

inputs = [128.0, 32768.0, 65536, 65536 * 2, 31.5, 1.000, 10.0]

outputs = [floatToString(i) for i in inputs]

print(outputs)

# ['128', '32768', '65536', '1.31e+05', '31.5', '1', '10']

Using multiple delimiters in awk

Good news! awk field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|...":

awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file

Returns:

tc0001  tomcat7.1  demo.example.com
tc0001  tomcat7.2  quest.example.com
tc0001  tomcat7.5  www.example.com

Here:

  • -F"/|=" sets the input field separator to either / or =. Then, it sets the output field separator to a tab.

  • -vOFS='\t' is using the -v flag for setting a variable. OFS is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F.

  • {print $3, $5, $NF} prints the 3rd, 5th and last fields based on the input field separator.


See another example:

$ cat file
hello#how_are_you
i#am_very#well_thank#you

This file has two fields separators, # and _. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!

$ awk -F"#|_" '{print $2}' file
how
am

Where the files are numbered as follows:

hello#how_are_you           i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^           ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
  1    2   3   4            1  2   3    4    5    6

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

What is newline character -- '\n'

sed can be put into multi-line search & replace mode to match newline characters \n.

To do so sed first has to read the entire file or string into the hold buffer ("hold space") so that it then can treat the file or string contents as a single line in "pattern space".

To replace a single newline portably (with respect to GNU and FreeBSD sed) you can use an escaped "real" newline.

# cf. http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
echo 'California
Massachusetts
Arizona' | 
sed -n -e '
# if the first line copy the pattern to the hold buffer
1h
# if not the first line then append the pattern to the hold buffer
1!H
# if the last line then ...
$ {
# copy from the hold to the pattern buffer
g
# double newlines
s/\n/\
\
/g
s/$/\
/
p
}'

# output
# California
#
# Massachusetts
#
# Arizona
#

There is, however, a much more convenient was to achieve the same result:

echo 'California
Massachusetts
Arizona' | 
   sed G

How to equalize the scales of x-axis and y-axis in Python matplotlib?

You need to dig a bit deeper into the api to do this:

from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()

doc for set_aspect

Change UITableView height dynamically

create your cell by xib or storyboard. give it's outlet's contents. now call it in CellForRowAtIndexPath. eg. if you want to set cell height according to Comment's label text. enter image description here

so set you commentsLbl.numberOfLine=0;enter image description here

so set you commentsLbl.numberOfLine=0;

then in ViewDidLoad

 self.table.estimatedRowHeight = 44.0 ;
self.table.rowHeight = UITableViewAutomaticDimension;

and now

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;}

How do I use tools:overrideLibrary in a build.gradle file?

I just changed minSdkVersion="7" in C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml and it worked.

Steps:

  1. Path: C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml
  2. Value: <uses-sdk android:minSdkVersion="7"/>
  3. Ran command in new cmd prompt:

    C:\MyApp>phonegap build android --debug [phonegap] executing 'cordova build android --debug'... [phonegap] completed 'cordova build android --debug'

nodejs - How to read and output jpg image?

Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:

var http = require('http')
var fs = require('fs')

fs.readFile('image.jpg', function(err, data) {
  if (err) throw err // Fail if the file can't be read.
  http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'})
    res.end(data) // Send the file data to the browser.
  }).listen(8124)
  console.log('Server running at http://localhost:8124/')
})

Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg.

[Edit] You could even embed the image in an HTML page directly by using an <img> with a data URI source. For example:

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write('<html><body><img src="data:image/jpeg;base64,')
  res.write(Buffer.from(data).toString('base64'));
  res.end('"/></body></html>');

PHP Change Array Keys

No, there is not, for starters, it is impossible to have an array with elements sharing the same key

$x =array(); 
$x['foo'] = 'bar' ; 
$x['foo'] = 'baz' ; #replaces 'bar'

Secondarily, if you wish to merely prefix the numbers so that

$x[0] --> $x['foo_0']  

That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is "extract" which will prefix numeric keys prior to making them variables.

The very simplest way is this:

function rekey( $input , $prefix ) { 
    $out = array(); 
    foreach( $input as $i => $v ) { 
        if ( is_numeric( $i ) ) { 
            $out[$prefix . $i] = $v; 
            continue; 
        }
        $out[$i] = $v;
    }
    return $out;
}

Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.

<section> 
    <foo_0></foo_0>
   <foo_1></foo_1>
   <bar></bar>
   <foo_2></foo_2>
</section>

Is not good XML.

<section> 
   <foo></foo>
   <foo></foo>
   <bar></bar>
   <foo></foo>
</section>

Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:

section => { 
    0 => [ foo , {} ]
    1 => [ foo , {} ]
    2 => [ bar , {} ]
    3 => [ foo , {} ] 
}

VBA Excel - Insert row below with same format including borders and frames

When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.

I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).

I've found three workarounds that don't require copying the formatting from the source row:

  1. Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)

  2. Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:

    • Conditional formatting borders are limited to the thin-weight lines.
    • Works best for sheets where borders are relatively consistent so you don't have to create a bunch of conditional formatting rules.
  3. Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).

S3 - Access-Control-Allow-Origin Header

fwuensche "answer" is corret to set up a CDN; doing this, i removed MaxAgeSeconds.

<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>

How to give a delay in loop execution using Qt

As an update of @Live's answer, for Qt = 5.2 there is no more need to subclass QThread, as now the sleep functions are public:

Static Public Members

  • QThread * currentThread()
  • Qt::HANDLE currentThreadId()
  • int idealThreadCount()
  • void msleep(unsigned long msecs)
  • void sleep(unsigned long secs)
  • void usleep(unsigned long usecs)
  • void yieldCurrentThread()

cf http://qt-project.org/doc/qt-5/qthread.html#static-public-members

How to use the "required" attribute with a "radio" input field

I had to use required="required" along with the same name and type, and then validation worked fine.

<input type="radio" name="user-radio"  id="" value="User" required="required" />

<input type="radio" name="user-radio" id="" value="Admin" />

<input type="radio" name="user-radio" id="" value="Guest" /> 

How can I use mySQL replace() to replace strings in multiple records?

UPDATE some_table SET some_field = REPLACE(some_field, '&lt;', '<')

How do you auto format code in Visual Studio?

I have a Mac and I clicked Code > Preferences > Settings > Workspace > Formatting and then selected Format On Save.

Now every time I hit cmd + s it auto formats the file.

enter image description here

Extract source code from .jar file

Do the following on your linux box where java works (if u like the terminal way of doing things)

cd ~
mkdir decompiled_code && cd decompiled_code
wget https://bitbucket.org/mstrobel/procyon/downloads/procyon-decompiler-0.5.36.jar
java -jar procyon-decompiler-0.5.36.jar /Path/to/your/jar -o .

NOTE : as @Richard commented "this may be illegal depending on whether you own the copyright to the jar, the country you live in and your purpose for doing it."

How can two strings be concatenated?

glue is a new function, data class, and package that has been developed as part of the tidyverse, with a lot of extended functionality. It combines features from paste, sprintf, and the previous other answers.

tmp <- tibble::tibble(firststring = "GAD", secondstring = "AB")
(tmp_new <- glue::glue_data(tmp, "{firststring},{secondstring}"))
#> GAD,AB

Created on 2019-03-06 by the reprex package (v0.2.1)

Yes, it's overkill for the simple example in this question, but powerful for many situations. (see https://glue.tidyverse.org/)

Quick example compared to paste with with below. The glue code was a bit easier to type and looks a bit easier to read.

tmp <- tibble::tibble(firststring = c("GAD", "GAD2", "GAD3"), secondstring = c("AB1", "AB2", "AB3"))
(tmp_new <- glue::glue_data(tmp, "{firststring} and {secondstring} went to the park for a walk. {firststring} forgot his keys."))
#> GAD and AB1 went to the park for a walk. GAD forgot his keys.
#> GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys.
#> GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys.
(with(tmp, paste(firststring, "and", secondstring, "went to the park for a walk.", firststring, "forgot his keys.")))
#> [1] "GAD and AB1 went to the park for a walk. GAD forgot his keys."  
#> [2] "GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys."
#> [3] "GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys."

Created on 2019-03-06 by the reprex package (v0.2.1)

Get text from pressed button

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();

Later this btnText can be used .

For example:

if(btnText == "Text for comparison")

Checking to see if one array's elements are in another array in PHP

That code is invalid as you can only pass variables into language constructs. empty() is a language construct.

You have to do this in two lines:

$result = array_intersect($people, $criminals);
$result = !empty($result);

Pandas Replace NaN with blank/empty string

I tried with one column of string values with nan.

To remove the nan and fill the empty string:

df.columnname.replace(np.nan,'',regex = True)

To remove the nan and fill some values:

df.columnname.replace(np.nan,'value',regex = True)

I tried df.iloc also. but it needs the index of the column. so you need to look into the table again. simply the above method reduced one step.

Understanding dispatch_async

Swift version

This is the Swift version of David's Objective-C answer. You use the global queue to run things in the background and the main queue to update the UI.

DispatchQueue.global(qos: .background).async {
    
    // Background Thread
    
    DispatchQueue.main.async {
        // Run UI Updates
    }
}

Clear the value of bootstrap-datepicker

I was having similar trouble and the following worked for me:

$('#datepicker').val('').datepicker('update');

Both method calls were needed, otherwise it didn't clear.

java.sql.SQLException: Fail to convert to internal representation

Your data types are mismatched when you are retrieving the field values. Check your code and ensure that for each field that you are retrieving that the java object matches that type. For example, retrieving a date into and int. If you are doing a select * then it is possible a change in the fields of the table has happened causing this error to occur. Your SQL should only select the fields you specifically want in order to avoid this error.

Hope this helps.

Calculating number of full months between two dates in SQL

SELECT 12 * (YEAR(end_date) - YEAR(start_date)) +
    ((MONTH(end_date) - MONTH(start_date))) +
    SIGN(DAY(end_date) / DAY(start_date));

This works fine for me on SQL SERVER 2000.

How to do a non-greedy match in grep?

The short answer is using the next regular expression:

(?s)<car .*? model=BMW .*?>.*?</car>
  • (?s) - this makes a match across multiline
  • .*? - matches any character, a number of times in a lazy way (minimal match)

A (little) more complicated answer is:

(?s)<([a-z\-_0-9]+?) .*? model=BMW .*?>.*?</\1>

This will makes possible to match car1 and car2 in the following text

<car1 ... model=BMW ...>
...
...
...
</car1>
<car2 ... model=BMW ...>
...
...
...
</car2>
  • (..) represents a capturing group
  • \1 in this context matches the sametext as most recently matched by capturing group number 1

How to convert integers to characters in C?

In C, int, char, long, etc. are all integers.

They typically have different memory sizes and thus different ranges as in INT_MIN to INT_MAX. char and arrays of char are often used to store characters and strings. Integers are stored in many types: int being the most popular for a balance of speed, size and range.

ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.

int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;

To convert an int to a char, simple assign:

int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4; 

This warning comes up because int typically has a greater range than char and so some loss-of-information may occur. By using the cast (char), the potential loss of info is explicitly directed.

To print the value of an integer:

printf("<%c>\n", c3); // prints <b>

// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>

// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>

printf("<%d>\n", i3); // prints <98>

There are additional issues about printing such as using %hhu or casting when printing an unsigned char, but leave that for later. There is a lot to printf().

jQuery find parent form

As of HTML5 browsers one can use inputElement.form - the value of the attribute must be an id of a <form> element in the same document. More info on MDN.

How to convert string to XML using C#

string test = "<body><head>test header</head></body>";

XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);

XmlNodeList elemlist = xmltest.GetElementsByTagName("head");

string result = elemlist[0].InnerXml; 

//result -> "test header"

How can I simulate an anchor click via jquery?

Do you need to fake an anchor click? From the thickbox site:

ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).

If that is acceptable it should be as easy as putting the thickbox class on the input itself:

<input id="thickboxButton" type="button" class="thickbox" value="Click me">

If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.

Edit:

Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:

<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>

The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.

Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.

dyld: Library not loaded: @rpath/libswiftCore.dylib

What worked for me in Xcode 11 was going to General -> Frameworks, Libraries, and Embedded Content and changing the "Embed" option for the framework in question to "Embed & Sign"

Embed and Sign option

How to install SQL Server Management Studio 2008 component only

If you have the SQL Server 2008 Installation media, you can install just the Client/Workstation Components. You don't have to install the database engine to install the workstation tools, but if you plan to do Integration Services development, you do need to install the Integration Services Engine on the workstation for BIDS to be able to be used for development. Keep in mind that Visual Studio 2010 does not have BI development support currently, so you have to install BIDS from the SQL Installation media and use the Visual Studio 2008 BI Development Studio that installs under the SQL Server 2008 folder in Program Files if you need to do any SSIS, SSRS, or SSAS development from the workstation.

As mentioned in the comments you can download Management Studio Express free from Microsoft, but if you already have the installation media for SQL Server Standard/Enterprise/Developer edition, you'd be better off using what you have.

Download SSMS 2008 Express

How to access to the parent object in c#

I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.

How to get the full url in Express?

Just the code below was enough for me!

const baseUrl = `${request.protocol}://${request.headers.host}`;
// http://127.0.0.1:3333

What is the difference between field, variable, attribute, and property in Java POJOs?

My understanding is as below, and I am not saying that this is 100% correct, I might as well be mistaken..

A variable is something that you declare, which can by default change and have different values, but that can also be explicitly said to be final. In Java that would be:

public class Variables {

    List<Object> listVariable; // declared but not assigned
    final int aFinalVariableExample = 5; // declared, assigned and said to be final!

    Integer foo(List<Object> someOtherObjectListVariable) {
        // declare..
        Object iAmAlsoAVariable;

        // assign a value..
        iAmAlsoAVariable = 5;

        // change its value..
        iAmAlsoAVariable = 8;

        someOtherObjectListVariable.add(iAmAlsoAVariable);

        return new Integer();
    }
}

So basically, a variable is anything that is declared and can hold values. Method foo above returns a variable for example.. It returns a variable of type Integer which holds the memory address of the new Integer(); Everything else you see above are also variables, listVariable, aFinalVariableExample and explained here:

A field is a variable where scope is more clear (or concrete). The variable returning from method foo 's scope is not clear in the example above, so I would not call it a field. On the other hand, iAmAlsoVariable is a "local" field, limited by the scope of the method foo, and listVariable is an "instance" field where the scope of the field (variable) is limited by the objects scope.

A property is a field that can be accessed / mutated. Any field that exposes a getter / setter is a property.

I do not know about attribute and I would also like to repeat that this is my understanding of what variables, fields and properties are.

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

How do I get my Maven Integration tests to run

I have done EXACTLY what you want to do and it works great. Unit tests "*Tests" always run, and "*IntegrationTests" only run when you do a mvn verify or mvn install. Here it the snippet from my POM. serg10 almost had it right....but not quite.

  <plugin>
    <!-- Separates the unit tests from the integration tests. -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
       <!-- Skip the default running of this plug-in (or everything is run twice...see below) -->
       <skip>true</skip>
       <!-- Show 100% of the lines from the stack trace (doesn't work) -->
       <trimStackTrace>false</trimStackTrace>
    </configuration>
    <executions>
       <execution>
          <id>unit-tests</id>
          <phase>test</phase>
          <goals>
             <goal>test</goal>
          </goals>
          <configuration>
                <!-- Never skip running the tests when the test phase is invoked -->
                <skip>false</skip>
             <includes>
                   <!-- Include unit tests within integration-test phase. -->
                <include>**/*Tests.java</include>
             </includes>
             <excludes>
               <!-- Exclude integration tests within (unit) test phase. -->
                <exclude>**/*IntegrationTests.java</exclude>
            </excludes>
          </configuration>
       </execution>
       <execution>
          <id>integration-tests</id>
          <phase>integration-test</phase>
          <goals>
             <goal>test</goal>
          </goals>
          <configuration>
            <!-- Never skip running the tests when the integration-test phase is invoked -->
             <skip>false</skip>
             <includes>
               <!-- Include integration tests within integration-test phase. -->
               <include>**/*IntegrationTests.java</include>
             </includes>
          </configuration>
       </execution>
    </executions>
  </plugin>

Good luck!

Login to remote site with PHP cURL

Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :


// options
$login_email = '[email protected]';
$login_pass = 'alabala4807';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "http://alabala.com/index.php?route=account/login";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";

// begin script
$ch = curl_init();

// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";

// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// execute session to get cookies and required form inputs
$content = curl_exec($ch);

// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['email'] = $login_email;
$fields['password'] = $login_pass;

// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

// perform login
$result = curl_exec($ch);

print $result;

function getFormFields($data)
{
if (preg_match('/()/is', $data, $matches)) {
$inputs = getInputs($matches[1]);

return $inputs;
} else {
die('didnt find login form');
}
}

function getInputs($form)
{
$inputs = array();
$elements = preg_match_all("/(]+>)/is", $form, $matches);
if ($elements > 0) {
for($i = 0;$i $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];

$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}

$inputs[$name] = $value;
}
}
}

return $inputs;
}

$grab_url='http://grab.url/alabala';

//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, $grab_url);
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

var_dump($html);
die;

What are the parameters for the number Pipe - Angular 2

From the DOCS

Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.

SYNTAX:

number_expression | number[:digitInfo[:locale]]

where expression is a number:

digitInfo is a string which has a following format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  • minIntegerDigits is the minimum number of integer digits to use.Defaults to 1
  • minFractionDigits is the minimum number of digits
  • after fraction. Defaults to 0. maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
  • locale is a string defining the locale to use (uses the current LOCALE_ID by default)

DEMO

Swift alert view with OK and Cancel: which button tapped?

If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated.

Here is an example of how to use it:

var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
  print("Handle Ok logic here")
  }))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
  print("Handle Cancel Logic here")
  }))

presentViewController(refreshAlert, animated: true, completion: nil)

As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/

Swift 3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
    print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
    print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
      print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
      print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Swift 5.3 update:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
      print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
      print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Listview Scroll to the end of the list after updating the list

I use

setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);

to add entries at the bottom, and older entries scroll off the top, like a chat transcript

Remove Style on Element

var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");

Deleting a pointer in C++

Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.

You can however use pointers to allocate a 'block' of memory, for example like this:

int *some_integers = new int[20000]

This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.

Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:

delete [] some_integers;

Hope that helps.

Fixed width buttons with Bootstrap

You can also use the .btn-block class on the button, so that it expands to the parent's width.

If the parent is a fixed width element the button will expand to take all width. You can apply existing markup to the container to ensure fixed/fluid buttons take up only the required space.

<div class="span2">
<p><button class="btn btn-primary btn-block">Save</button></p>
<p><button class="btn btn-success btn-block">Download</button></p>
</div>

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<div class="span2">_x000D_
  <p><button class="btn btn-primary btn-block">Save</button></p>_x000D_
  <p><button class="btn btn-success btn-block">Download</button></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Find child element in AngularJS directive

In your link function, do this:

// link function
function (scope, element, attrs) {
  var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}

Also, in your link function, don't name your scope variable using a $. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.

What exactly is a Maven Snapshot and why do we need it?

The three others answers provide you a good vision of what a -SNAPSHOT version is. I just wanted to add some information regarding the behavior of Maven when it finds a SNAPSHOT dependency.

When you build an application, Maven will search for dependencies in the local repository. If a stable version is not found there, it will search the remote repositories (defined in settings.xml or pom.xml) to retrieve this dependency. Then, it will copy it into the local repository, to make it available for the next builds.

For example, a foo-1.0.jar library is considered as a stable version, and if Maven finds it in the local repository, it will use this one for the current build.

Now, if you need a foo-1.0-SNAPSHOT.jar library, Maven will know that this version is not stable and is subject to changes. That's why Maven will try to find a newer version in the remote repositories, even if a version of this library is found on the local repository. However, this check is made only once per day. That means that if you have a foo-1.0-20110506.110000-1.jar (i.e. this library has been generated on 2011/05/06 at 11:00:00) in your local repository, and if you run the Maven build again the same day, Maven will not check the repositories for a newer version.

Maven provides you a way to change this update policy in your repository definition:

<repository>
    <id>foo-repository</id>
    <url>...</url>
    <snapshots>
        <enabled>true</enabled>
        <updatePolicy>XXX</updatePolicy>
    </snapshots>
</repository>

where XXX can be:

  • always: Maven will check for a newer version on every build;
  • daily, the default value;
  • interval:XXX: an interval in minutes (XXX)
  • never: Maven will never try to retrieve another version. It will do that only if it doesn't exist locally. With the configuration, SNAPSHOT version will be handled as the stable libraries.

(model of the settings.xml can be found here)

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

In my case the "cudnn64_6.dll" file in the /bin folder had to be renamed to "cudnn64_5.dll" for the error to go away. I easily spent two hours to figure this out, and I followed the official install guide to the letter. This is true for installation via pip (officially supported) and conda (community supported).

How to make HTTP Post request with JSON body in Swift

    var request = URLRequest(url: URL(string:  "your URL")!)
    request.httpMethod = "POST"


    let postString =  String(format: "email=%@&lang=%@", arguments: [txt_emailVirify.text!, language!])
    print(postString)

    emailString = txt_emailVirify.text!

    request.httpBody = postString.data(using: .utf8)
    request.addValue("delta141forceSEAL8PARA9MARCOSBRAHMOS", forHTTPHeaderField: "Authorization")
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")


    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil
            else
        {
            print("error=\(String(describing: error))")
            return
        }

        do
        {

            let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
            print(dictionary)

            let status = dictionary.value(forKey: "status") as! String
            let sts = Int(status)
            DispatchQueue.main.async()
                {
                    if sts == 200
                    {
                        print(dictionary)


                    }
                    else
                    {
                       self.alertMessageOk(title: self.Alert!, message: dictionary.value(forKey: "message") as! String)


                    }
            }
        }
        catch
        {
            print(error)
        }

    }
    task.resume()

Angular ng-class if else

You can use the ternary operator notation:

<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">

Regular expression for validating names and surnames?

I don’t think that’s a good idea. Even if you find an appropriate regular expression (maybe using Unicode character properties), this wouldn’t prevent users from entering pseudo-names like John Doe, Max Mustermann (there even is a person with that name), Abcde Fghijk or Ababa Bebebe.

Loading DLLs at runtime in C#

Activator.CreateInstance() returns an object, which doesn't have an Output method.

It looks like you come from dynamic programming languages? C# is definetly not that, and what you are trying to do will be difficult.

Since you are loading a specific dll from a specific location, maybe you just want to add it as a reference to your console application?

If you absolutely want to load the assembly via Assembly.Load, you will have to go via reflection to call any members on c

Something like type.GetMethod("Output").Invoke(c, null); should do it.

Correct way to focus an element in Selenium WebDriver using Java

This code actually doesn't provide focus:

new Actions(driver).moveToElement(element).perform();

It provides a hover effect.

Additionally, the JS code .focus() requires that the window be active in order to work.

js.executeScript("element.focus();");

I have found that this code works:

element.sendKeys(Keys.SHIFT);

For my own code, I use both:

element.sendKeys(Keys.SHIFT);
js.executeScript("element.focus();");

validate natural input number with ngpattern

The problem is that your REGX pattern will only match the input "0-9".

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

My example:

HTML:

<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="number" ng-model="price" name="price_field" 
           ng-pattern="/^[0-9]{1,7}$/" required>
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <span ng-show="myForm.price_field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

JS:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}

Here is a jsFiddle demo.

What does -> mean in Python function definitions?

def f(x) -> str:
return x+4

print(f(45))

# will give the result : 
49

# or with other words '-> str' has NO effect to return type:

print(f(45).__class__)

<class 'int'>

Simulate low network connectivity for Android

for and mac OS user you can use Network Link Conditioner which could be downloaded from apple. set it as a AP on mac and any divices could connected it.

you can either use facebook open source tools ATC http://facebook.github.io/augmented-traffic-control/

Understanding Bootstrap's clearfix class

When a clearfix is used in a parent container, it automatically wraps around all the child elements.

It is usually used after floating elements to clear the float layout.

When float layout is used, it will horizontally align the child elements. Clearfix clears this behaviour.

Example - Bootstrap Panels

In bootstrap, when the class panel is used, there are 3 child types: panel-header, panel-body, panel-footer. All of which have display:block layout but panel-body has a clearfix pre-applied. panel-body is a main container type whereas panel-header & panel-footer isn't intended to be a container, it is just intended to hold some basic text.

If floating elements are added, the parent container does not get wrapped around those elements because the height of floating elements is not inherited by the parent container.

So for panel-header & panel-footer, clearfix is needed to clear the float layout of elements: Clearfix class gives a visual appearance that the height of the parent container has been increased to accommodate all of its child elements.

 <div class="container">
    <div class="panel panel-default">
        <div class="panel-footer">
            <div class="col-xs-6">
                <input type="button" class="btn btn-primary"   value="Button1">
                <input type="button" class="btn btn-primary"   value="Button2">
                <input type="button" class="btn btn-primary"   value="Button3">
            </div>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-footer">
            <div class="col-xs-6">
                <input type="button" class="btn btn-primary"   value="Button1">
                <input type="button" class="btn btn-primary"   value="Button2">
                <input type="button" class="btn btn-primary"   value="Button3">
            </div>
            <div class="clearfix"/>
        </div>
    </div>
</div>

see an example photo here

Generate a random letter in Python

def randchar(a, b):
    return chr(random.randint(ord(a), ord(b)))

Plain Old CLR Object vs Data Transfer Object

I think a DTO can be a POCO. DTO is more about the usage of the object while POCO is more of the style of the object (decoupled from architectural concepts).

One example where a POCO is something different than DTO is when you're talking about POCO's inside your domain model/business logic model, which is a nice OO representation of your problem domain. You could use the POCO's throughout the whole application, but this could have some undesirable side effect such a knowledge leaks. DTO's are for instance used from the Service Layer which the UI communicates with, the DTO's are flat representation of the data, and are only used for providing the UI with data, and communicating changes back to the service layer. The service layer is in charge of mapping the DTO's both ways to the POCO domain objects.

Update Martin Fowler said that this approach is a heavy road to take, and should only be taken if there is a significant mismatch between the domain layer and the user interface.

How to get a list of sub-folders and their files, ordered by folder-names

In command prompt go to the main directory you want the list for ... and type the command tree /f

Installing Numpy on 64bit Windows 7 with Python 2.7.3

The (unofficial) binaries (http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy) worked for me.
I've tried Mingw, Cygwin, all failed due to varies reasons. I am on Windows 7 Enterprise, 64bit.

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

<sqlserverdir>\setup.exe /ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck

Above worked for me... I did installed it, from my external, using command line interface.

Input type=password, don't let browser remember the password

I solved in another way. You can try this.

<input id="passfld" type="text" autocomplete="off" />
<script type="text/javascript">
// Using jQuery
$(function(){                                               
    setTimeout(function(){
        $("input#passfld").attr("type","password");
    },10);
});


// or in pure javascript
 window.onload=function(){                                              
    setTimeout(function(){  
        document.getElementById('passfld').type = 'password';
    },10);
  }   
</script>

#another way

 <script type="text/javascript">    
 function setAutoCompleteOFF(tm){
    if(typeof tm =="undefined"){tm=10;}
    try{
    var inputs=$(".auto-complete-off,input[autocomplete=off]"); 
    setTimeout(function(){
        inputs.each(function(){     
            var old_value=$(this).attr("value");            
            var thisobj=$(this);            
            setTimeout(function(){  
                thisobj.removeClass("auto-complete-off").addClass("auto-complete-off-processed");
                thisobj.val(old_value);
            },tm);
         });
     },tm); 
    }catch(e){}
  }
 $(function(){                                              
        setAutoCompleteOFF();
    });
</script>

// you need to add attribute autocomplete="off" or you can add class .auto-complete-off into the input box and enjoy

Example:

  <input id="passfld" type="password" autocomplete="off" />
    OR
  <input id="passfld" class="auto-complete-off" type="password"  />

Add newline to VBA or Visual Basic 6

Use this code between two words:

& vbCrLf &

Using this, the next word displays on the next line.

Unable to open a file with fopen()

Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

Java: How to convert String[] to List or Set

java.util.Arrays.asList(new String[]{"a", "b"})

Convert/cast an stdClass object to another class

And yet another approach using the decorator pattern and PHPs magic getter & setters:

// A simple StdClass object    
$stdclass = new StdClass();
$stdclass->foo = 'bar';

// Decorator base class to inherit from
class Decorator {

    protected $object = NULL;

    public function __construct($object)
    {
       $this->object = $object;  
    }

    public function __get($property_name)
    {
        return $this->object->$property_name;   
    }

    public function __set($property_name, $value)
    {
        $this->object->$property_name = $value;   
    }
}

class MyClass extends Decorator {}

$myclass = new MyClass($stdclass)

// Use the decorated object in any type-hinted function/method
function test(MyClass $object) {
    echo $object->foo . '<br>';
    $object->foo = 'baz';
    echo $object->foo;   
}

test($myclass);

How can I use a JavaScript variable as a PHP variable?

PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.

What happens in a nutshell is this:

  • You click a link in your browser on your computer under your desk
  • The browser creates an HTTP request and sends it to a server on the Internet
  • The server checks if he can handle the request
  • If the request is for a PHP page, the PHP interpreter is started
  • The PHP interpreter will run all PHP code in the page you requested
  • The PHP interpreter will NOT run any JS code, because it has no clue about it
  • The server will send the page assembled by the interpreter back to your browser
  • Your browser will render the page and show it to you
  • JavaScript is executed on your computer

In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.

The only way to do what you are looking to do is either:

  • do a redirect to a PHP script or
  • do an AJAX call to a PHP script

with the values you want to be insert into the database.

Refresh Page C# ASP.NET

To refresh the whole page, but it works normally:

Response.Redirect(url,bool) 

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

Even though utf8_decode is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace on the field on the table. To correct the bad encoded characters from OP :

update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")

Where <table> is the name of the mysql table and <field> is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.

Remember to backup your table before trying to replace any characters with SQL!

[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]

Android-java- How to sort a list of objects by a certain value within the object

public class DateComparator implements Comparator<Marker> {
    @Override
    public int compare(Mark lhs, Mark rhs) {
        Double distance = Double.valueOf(lhs.getDistance());
        Double distance1 = Double.valueOf(rhs.getDistance());
        if (distance.compareTo(distance1) < 0) {
            return -1;
        } else if (distance.compareTo(distance1) > 0) {
            return 1;
        } else {
            return 0;
        }
    }
}

ArrayList(Marker) arraylist;

How To use:

Collections.sort(arraylist, new DateComparator());

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

Your connection to redis is failing. Try restarting your redis server, then starting up your client again by running these 3 commands:

sudo service redis-server restart
redis-server
redis-cli

Convert a Unicode string to a string in Python (containing extra symbols)

Here is an example:

>>> u = u'€€€'
>>> s = u.encode('utf8')
>>> s
'\xe2\x82\xac\xe2\x82\xac\xe2\x82\xac'

How to configure custom PYTHONPATH with VM and PyCharm?

Well you can do this by going to the interpreter's dialogue box. Click on the interpreter that you are using, and underneath it, you should see two tabs, one called Packages, and the other called Path.

Click on Path, and add your VM path to it.

Exception: "URI formats are not supported"

Try This

ImagePath = "http://localhost/profilepics/abc.png";
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
          HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();

Given a URL to a text file, what is the simplest way to read the contents of the text file?

Another way in Python 3 is to use the urllib3 package.

import urllib3

http = urllib3.PoolManager()
response = http.request('GET', target_url)
data = response.data.decode('utf-8')

This can be a better option than urllib since urllib3 boasts having

  • Thread safety.
  • Connection pooling.
  • Client-side SSL/TLS verification.
  • File uploads with multipart encoding.
  • Helpers for retrying requests and dealing with HTTP redirects.
  • Support for gzip and deflate encoding.
  • Proxy support for HTTP and SOCKS.
  • 100% test coverage.

Primary key or Unique index?

There are some disadvantages of CLUSTERED INDEXES vs UNIQUE INDEXES.

As already stated, a CLUSTERED INDEX physically orders the data in the table.

This mean that when you have a lot if inserts or deletes on a table containing a clustered index, everytime (well, almost, depending on your fill factor) you change the data, the physical table needs to be updated to stay sorted.

In relative small tables, this is fine, but when getting to tables that have GB's worth of data, and insertrs/deletes affect the sorting, you will run into problems.

What to do with commit made in a detached head

Create a branch where you are, then switch to master and merge it:

git branch my-temporary-work
git checkout master
git merge my-temporary-work

Intro to GPU programming

Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read. http://www.nvidia.com/object/cuda_home.html

Hello world would be to do any kind of calculation using GPU.

Hope that helps.

How many bytes does one Unicode character take?

From Wiki:

UTF-8, an 8-bit variable-width encoding which maximizes compatibility with ASCII;

UTF-16, a 16-bit, variable-width encoding;

UTF-32, a 32-bit, fixed-width encoding.

These are the three most popular different encoding.

  • In UTF-8 each character is encoded into 1 to 4 bytes ( the dominant encoding )
  • In UTF16 each character is encoded into 1 to two 16-bit words and
  • in UTF-32 every character is encoded as a single 32-bit word.

check null,empty or undefined angularjs

if($scope.test == null || $scope.test == undefined || $scope.test == "" ||    $scope.test.lenght == 0){

console.log("test is not defined");
}
else{
console.log("test is defined ",$scope.test); 
}

What do column flags mean in MySQL Workbench?

PK - Primary Key

NN - Not Null

BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)

UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)

UQ - Create/remove Unique Key

ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )

AI - Auto Increment

G - Generated column. i.e. value generated by a formula based on the other columns

How to run a PowerShell script

Using cmd (BAT) file:

@echo off
color 1F
echo.

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PrepareEnvironment.ps1"

:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL

If you need run as administrator:

  1. Make a shortcut pointed to the command prompt (I named it Administrative Command Prompt)
  2. Open the shortcut's properties and go to the Compatibility tab
  3. Under the Privilege Level section, make sure the checkbox next to "Run this program as an administrator" is checked

How can I center <ul> <li> into div

I have been looking for the same case and tried all answers by change the width of <li>.
Unfortunately all were failed to get the same distance on left and right of the <ul> box.

The closest match is this answer but it needs to adjust the change of width with padding

.container ul {
    ...
    padding: 10px 25px;
}

.container li {
  ...
  width: 100px;
}

See the result below, all distance between <li> also to the <ul> box are the same. enter image description here

You may check it on this jsFiddle:
http://jsfiddle.net/qwbexxog/14/

Count number of vector values in range with R

Use which:

 set.seed(1)
 x <- sample(10, 50, replace = TRUE)
 length(which(x > 3 & x < 5))
 # [1]  6

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Note: For MySQL 5.7+ please see answer from @Lahiru to this question. That contains more current information.

For MySQL < 5.7:

The default root password is blank (i.e. empty string) not root. So you can just login as:

mysql -u root

You should obviously change your root password after installation

mysqladmin -u root password [newpassword]

In most cases you should also set up individual user accounts before working extensively with the DB as well.

Run a single migration file

This are the steps to run again this migration file "20150927161307_create_users.rb"

  1. Run the console mode. (rails c)
  2. Copy and past the class which is in that file to the console.

    class CreateUsers < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.string :name
          t.string :email
          t.timestamps null: false   end
        end
      end
    end
    
  3. Create an instance of the class CreateUsers: c1 = CreateUsers.new

  4. Execute the method change of that instance: c1.change

How to get progress from XMLHttpRequest

If you have access to your apache install and trust third-party code, you can use the apache upload progress module (if you use apache; there's also a nginx upload progress module).

Otherwise, you'd have to write a script that you can hit out of band to request the status of the file (checking the filesize of the tmp file for instance).

There's some work going on in firefox 3 I believe to add upload progress support to the browser, but that's not going to get into all the browsers and be widely adopted for a while (more's the pity).

Member '<method>' cannot be accessed with an instance reference

I had the same issue - although a few years later, some may find a few pointers helpful:

Do not use ‘static’ gratuitously!

Understand what ‘static’ implies in terms of both run-time and compile time semantics (behavior) and syntax.

  • A static entity will be automatically constructed some time before
    its first use.

  • A static entity has one storage location allocated, and that is
    shared by all who access that entity.

  • A static entity can only be accessed through its type name, not
    through an instance of that type.

  • A static method does not have an implicit ‘this’ argument, as does an instance method. (And therefore a static method has less execution
    overhead – one reason to use them.)

  • Think about thread safety when using static entities.

Some details on static in MSDN:

How do I set cell value to Date and apply default Excel date format?

This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.

import org.apache.poi.xssf.usermodel.*; //import needed

XSSFWorkbook  wb = new XSSFWorkbook ();  // Create workbook
XSSFSheet sheet = wb.createSheet();      // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet


//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle         = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy")); 

//2. Apply the Date cell style to a cell

//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

JQuery Parsing JSON array

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});

Control the dashed border stroke length and distance between strokes

I just recently had the same problem. I have made this work around, hope it will help someone.

HTML + tailwind

<div class="dashed-border h-14 w-full relative rounded-lg">
    <div class="w-full h-full rounded-lg bg-page z-10 relative">
        Content goes here...
    <div>
</div>

CSS

.dashed-border::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: calc(100% + 4px);
  transform: translateY(-50%);
  background-image: linear-gradient(to right, #333 50%, transparent 50%);
  background-size: 16px;
  z-index: 0;
  border-radius: 0.5rem;
}
.dashed-border::after {
  content: '';
  position: absolute;
  left: 50%;
  top: 0;
  height: 100%;
  width: calc(100% + 4px);
  transform: translateX(-50%);
  background-image: linear-gradient(to bottom, #333 50%, transparent 50%);
  background-size: 4px 16px;
  z-index: 1;
  border-radius: 0.5rem;
}

Change the background color of a row in a JTable

Resumee of Richard Fearn's answer , to make each second line gray:

jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
        return c;
    }
});

How do I pass a class as a parameter in Java?

public void foo(Class c){
        try {
            Object ob = c.newInstance();
        } catch (InstantiationException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

How to invoke method using reflection

 import java.lang.reflect.*;


   public class method2 {
      public int add(int a, int b)
      {
         return a + b;
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Method meth = cls.getMethod(
              "add", partypes);
            method2 methobj = new method2();
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj 
              = meth.invoke(methobj, arglist);
            Integer retval = (Integer)retobj;
            System.out.println(retval.intValue());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

Also See

How can I keep a container running on Kubernetes?

Use Kubernetes Deployment and services.

Better way to call javascript function in a tag

Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.

Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.

The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.

Nested JSON objects - do I have to use arrays for everything?

Every object has to be named inside the parent object:

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

So you cant declare an object like this:

var obj = {property1, property2};

It has to be

var obj = {property1: 'value', property2: 'value'};

How to override the [] operator in Python?

You need to use the __getitem__ method.

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

And if you're going to be setting values you'll need to implement the __setitem__ method too, otherwise this will happen:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'

ListView with OnItemClickListener

setClickable as false to ImageButton like this

imagebutton.setClickable(false);

and then perform OnItemClickListener to listview.

What is the technology behind wechat, whatsapp and other messenger apps?

The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.

Here is the general explanation from the link

  • WhatsApp server is almost completely implemented in Erlang.

  • Server systems that do the backend message routing are done in Erlang.

  • Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.

  • Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.

  • WhatsApp server has started from ejabberd

  • Ejabberd is a famous open source Jabber server written in Erlang.

  • Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.

  • The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.

  • To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.

  • A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.

  • Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).

  • Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.

  • What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message

  • How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.

Default FirebaseApp is not initialized

First thing you need to add com.google.gms:google-services:x.x.x at root level build.gradle

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.1'
    classpath 'com.google.gms:google-services:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

}

After that you need to apply plugin: 'com.google.gms.google-services' at app/build.gradle

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'

compile 'com.google.android.gms:play-services-gcm:9.8.0'
compile 'com.google.android.gms:play-services-maps:9.8.0'
compile 'com.google.android.gms:play-services-location:9.8.0'
compile 'com.google.firebase:firebase-messaging:9.8.0'
testCompile 'junit:junit:4.12'
}


apply plugin: 'com.google.gms.google-services'

and if still you are getting problem then you need to add

FirebaseApp.initializeApp(this);

just before you are calling

FirebaseInstanceId.getInstance().getToken();

How to autowire RestTemplate using annotations

@Autowired
private RestOperations restTemplate;

You can only autowire interfaces with implementations.

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

codeigniter, result() vs. result_array()

result() returns Object type data. . . . result_array() returns Associative Array type data.

Sleep function in Windows, using C

SleepEx function (see http://msdn.microsoft.com/en-us/library/ms686307.aspx) is the best choise if your program directly or indirectly creates windows (for example use some COM objects). In the simples cases you can also use Sleep.

Compare two MySQL databases

From the feature comparison list... MySQL Workbench offers Schema Diff and Schema Synchronization in their community edition.

.NET Events - What are object sender & EventArgs e?

Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:

private void myCustomControl_Click(object sender, EventArgs e)
{
  ((MyCustomControl)sender).DoWhatever();
}

The 'sender' is just the object that was actioned (eg clicked).

The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.

Send POST request using NSURLSession

Motivation

Sometimes I have been getting some errors when you want to pass httpBody serialized to Data from Dictionary, which on most cases is due to the wrong encoding or malformed data due to non NSCoding conforming objects in the Dictionary.

Solution

Depending on your requirements one easy solution would be to create a String instead of Dictionary and convert it to Data. You have the code samples below written on Objective-C and Swift 3.0.

Objective-C

// Create the URLSession on the default configuration
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

// Setup the request with URL
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = @"api_key=APIKEY&[email protected]&password=password";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // Handle your response here
}];

// Fire the request
[dataTask resume];

Swift

// Create the URLSession on the default configuration
let defaultSessionConfiguration = URLSessionConfiguration.default
let defaultSession = URLSession(configuration: defaultSessionConfiguration)

// Setup the request with URL
let url = URL(string: "yourURL")
var urlRequest = URLRequest(url: url!)  // Note: This is a demo, that's why I use implicitly unwrapped optional

// Convert POST string parameters to data using UTF8 Encoding
let postParams = "api_key=APIKEY&[email protected]&password=password"
let postData = postParams.data(using: .utf8)

// Set the httpMethod and assign httpBody
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postData

// Create dataTask
let dataTask = defaultSession.dataTask(with: urlRequest) { (data, response, error) in
    // Handle your response here
}

// Fire the request
dataTask.resume()

if variable contains

If you have a lot of these to check you might want to store a list of the mappings and just loop over that, instead of having a bunch of if/else statements. Something like:

var CODE_TO_LOCATION = {
  'ST1': 'stoke central',
  'ST2': 'stoke north',
  // ...
};

function getLocation(text) {
  for (var code in CODE_TO_LOCATION) {
    if (text.indexOf(code) != -1) {
      return CODE_TO_LOCATION[code];
    }
  }
  return null;
}

This way you can easily add more code/location mappings. And if you want to handle more than one location you could just build up an array of locations in the function instead of just returning the first one you find.

Having Django serve downloadable files

Just mentioning the FileResponse object available in Django 1.10

Edit: Just ran into my own answer while searching for an easy way to stream files via Django, so here is a more complete example (to future me). It assumes that the FileField name is imported_file

views.py

from django.views.generic.detail import DetailView   
from django.http import FileResponse
class BaseFileDownloadView(DetailView):
  def get(self, request, *args, **kwargs):
    filename=self.kwargs.get('filename', None)
    if filename is None:
      raise ValueError("Found empty filename")
    some_file = self.model.objects.get(imported_file=filename)
    response = FileResponse(some_file.imported_file, content_type="text/csv")
    # https://docs.djangoproject.com/en/1.11/howto/outputting-csv/#streaming-large-csv-files
    response['Content-Disposition'] = 'attachment; filename="%s"'%filename
    return response

class SomeFileDownloadView(BaseFileDownloadView):
    model = SomeModel

urls.py

...
url(r'^somefile/(?P<filename>[-\w_\\-\\.]+)$', views.SomeFileDownloadView.as_view(), name='somefile-download'),
...

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

Form inside a form, is that alright?

Though you can have several <form> elements in one HTML page, you cannot nest them.

'cout' was not declared in this scope

Put the following code before int main():

using namespace std;

And you will be able to use cout.

For example:

#include<iostream>
using namespace std;
int main(){
    char t = 'f';
    char *t1;
    char **t2;
    cout<<t;        
    return 0;
}

Now take a moment and read up on what cout is and what is going on here: http://www.cplusplus.com/reference/iostream/cout/


Further, while its quick to do and it works, this is not exactly a good advice to simply add using namespace std; at the top of your code. For detailed correct approach, please read the answers to this related SO question.

What and where are the stack and heap?

Stack:

  • Stored in computer RAM just like the heap.
  • Variables created on the stack will go out of scope and are automatically deallocated.
  • Much faster to allocate in comparison to variables on the heap.
  • Implemented with an actual stack data structure.
  • Stores local data, return addresses, used for parameter passing.
  • Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep recursion, very large allocations).
  • Data created on the stack can be used without pointers.
  • You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
  • Usually has a maximum size already determined when your program starts.

Heap:

  • Stored in computer RAM just like the stack.
  • In C++, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[], or free.
  • Slower to allocate in comparison to variables on the stack.
  • Used on demand to allocate a block of data for use by the program.
  • Can have fragmentation when there are a lot of allocations and deallocations.
  • In C++ or C, data created on the heap will be pointed to by pointers and allocated with new or malloc respectively.
  • Can have allocation failures if too big of a buffer is requested to be allocated.
  • You would use the heap if you don't know exactly how much data you will need at run time or if you need to allocate a lot of data.
  • Responsible for memory leaks.

Example:

int foo()
{
  char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
  bool b = true; // Allocated on the stack.
  if(b)
  {
    //Create 500 bytes on the stack
    char buffer[500];

    //Create 500 bytes on the heap
    pBuffer = new char[500];

   }//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;

How to scroll to top of a div using jQuery?

Special thanks to Stoic for

   $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});

CSS centred header image

you don't need to set the width of header in css, just put the background image as center using this code:

background: url("images/logo.png") no-repeat top center;

or you can just use img tag and put align="center" in the div

How to remove blank lines from a Unix file

awk 'NF' filename

awk 'NF > 0' filename

sed -i '/^$/d' filename

awk '!/^$/' filename

awk '/./' filename

The NF also removes lines containing only blanks or tabs, the regex /^$/ does not.