Programs & Examples On #Subactivity

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

I suspect because of modules, which remove the need for the #import <Cocoa/Cocoa.h>.

As to where to put code that you would put in a prefix header, there is no code you should put in a prefix header. Put your imports into the files that need them. Put your definitions into their own files. Put your macros...nowhere. Stop writing macros unless there is no other way (such as when you need __FILE__). If you do need macros, put them in a header and include it.

The prefix header was necessary for things that are huge and used by nearly everything in the whole system (like Foundation.h). If you have something that huge and ubiquitous, you should rethink your architecture. Prefix headers make code reuse hard, and introduce subtle build problems if any of the files listed can change. Avoid them until you have a serious build time problem that you can demonstrate is dramatically improved with a prefix header.

In that case you can create one and pass it into clang, but it's incredibly rare that it's a good idea.


EDIT: To your specific question about a HUD you use in all your view controllers, yes, you should absolutely import it into every view controller that actually uses it. This makes the dependencies clear. When you reuse your view controller in a new project (which is common if you build your controllers well), you will immediately know what it requires. This is especially important for categories, which can make code very hard to reuse if they're implicit.

The PCH file isn't there to get rid of listing dependencies. You should still import UIKit.h or Foundation.h as needed, as the Xcode templates do. The reason for the PCH is to improve build times when dealing with really massive headers (like in UIKit).

How do I download a file with Angular2 or greater

For those using Redux Pattern

I added in the file-saver as @Hector Cuevas named in his answer. Using Angular2 v. 2.3.1, I didn't need to add in the @types/file-saver.

The following example is to download a journal as PDF.

The journal actions

public static DOWNLOAD_JOURNALS = '[Journals] Download as PDF';
public downloadJournals(referenceId: string): Action {
 return {
   type: JournalActions.DOWNLOAD_JOURNALS,
   payload: { referenceId: referenceId }
 };
}

public static DOWNLOAD_JOURNALS_SUCCESS = '[Journals] Download as PDF Success';
public downloadJournalsSuccess(blob: Blob): Action {
 return {
   type: JournalActions.DOWNLOAD_JOURNALS_SUCCESS,
   payload: { blob: blob }
 };
}

The journal effects

@Effect() download$ = this.actions$
    .ofType(JournalActions.DOWNLOAD_JOURNALS)
    .switchMap(({payload}) =>
        this._journalApiService.downloadJournal(payload.referenceId)
        .map((blob) => this._actions.downloadJournalsSuccess(blob))
        .catch((err) => handleError(err, this._actions.downloadJournalsFail(err)))
    );

@Effect() downloadJournalSuccess$ = this.actions$
    .ofType(JournalActions.DOWNLOAD_JOURNALS_SUCCESS)
    .map(({payload}) => saveBlobAs(payload.blob, 'journal.pdf'))

The journal service

public downloadJournal(referenceId: string): Observable<any> {
    const url = `${this._config.momentumApi}/api/journals/${referenceId}/download`;
    return this._http.getBlob(url);
}

The HTTP service

public getBlob = (url: string): Observable<any> => {
    return this.request({
        method: RequestMethod.Get,
        url: url,
        responseType: ResponseContentType.Blob
    });
};

The journal reducer Though this only sets the correct states used in our application I still wanted to add it in to show the complete pattern.

case JournalActions.DOWNLOAD_JOURNALS: {
  return Object.assign({}, state, <IJournalState>{ downloading: true, hasValidationErrors: false, errors: [] });
}

case JournalActions.DOWNLOAD_JOURNALS_SUCCESS: {
  return Object.assign({}, state, <IJournalState>{ downloading: false, hasValidationErrors: false, errors: [] });
}

I hope this is helpful.

Syncing Android Studio project with Gradle files

Old Answer

When trying to run the application, instead of selecting the directory highlighted here in blueenter image description here

I selected the subdirectory instead

enter image description here

and clicked "run".All the issues with Gradle are automatically resolved and the missing apk directory is automatically created.

New Solution

The Sync project with gradle files button disappeared from Android Studio for a while.Its back and you can find it here:

enter image description here

hit the button and wait for the task to complete

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Why is "cursor:pointer" effect in CSS not working

The solution that worked for me is using forward slash instead of backslash when 'calling' out from a local directory.

instead of backslash:

_x000D_
_x000D_
cursor: url("C:\Users\Ken\projects\JavascriptGames\images\bird.png"), auto;
_x000D_
_x000D_
_x000D_ Note: When I use backslash I am getting a net::ERR_FILE_NOT_FOUND

I changed it to forwardslash:

_x000D_
_x000D_
cursor: url("C:/Users/Ken/projects/JavascriptGames/images/bird.png"), auto;
_x000D_
_x000D_
_x000D_ Note: When I use forward slash, the custom cursor style executes successfully.

This behavior regarding backslashes and forward slashes could probably be explained in this StackOverflow answer: Strange backslash and behavior in CSS

How to install SimpleJson Package for Python

I would recommend EasyInstall, a package management application for Python.

Once you've installed EasyInstall, you should be able to go to a command window and type:

easy_install simplejson

This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like C:\Python25\Scripts).

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

declare:

final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            imgView.setImageBitmap(selectedBitmap);
        }
    }
}

It is pretty easy for me to implement and also shows darken areas.

Style input element to fill remaining width of its container

as much as everyone hates tables for layout, they do help with stuff like this, either using explicit table tags or using display:table-cell

<div style="width:300px; display:table">
    <label for="MyInput" style="display:table-cell; width:1px">label&nbsp;text</label>
    <input type="text" id="MyInput" style="display:table-cell; width:100%" />
</div>

Google Maps API v3: Can I setZoom after fitBounds?

I don't like to suggest it, but if you must try - first call

gmap.fitBounds(bounds);

Then create a new Thread/AsyncTask, have it sleep for 20-50ms or so and then call

gmap.setZoom( Math.max(6, gmap.getZoom()) );

from the UI thread (use a handler or the onPostExecute method for AsyncTask).

I don't know if it works, just a suggestion. Other than that you'd have to somehow calculate the zoom level from your points yourself, check if it's too low, correct it and then just call gmap.setZoom(correctedZoom)

Installing PDO driver on MySQL Linux server

If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!

Here's how I installed in Ubuntu-based image:

https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8

RUN docker-php-ext-install mysql mysqli pdo pdo_mysql

Building and running your application is just a 2 step process (considering you are in the current directory of the app):

$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp

What does enumerate() mean?

I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead. I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).

list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
    letter = list_of_letters[i]
    print (i, letter)

The output is:

0 a
1 b
2 c

I also used to do something, even sillier before I read about the enumerate function.

i = 0
for n in list_of_letters:
    print (i, n)
    i += 1

It produces the same output.

But with enumerate I just have to write:

list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
    print (i, letter)

Delete branches in Bitbucket

Step 1 : Login in Bitbucket

Step 2 : Select Your Repository in Repositories list. enter image description here

Step 3 : Select branches in left hand side menu. enter image description here

Step4 : Cursor point on branch click on three dots (...) Select Delete (See in Bellow Image) enter image description here

Passing an array/list into a Python function

When you define your function using this syntax:

def someFunc(*args):
    for x in args
        print x

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):
    for x in myList:
        print x

Then you can call it with this:

items = [1,2,3,4,5]

someFunc(items)

You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):
    for x in args
        print x

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

How can I parse a JSON file with PHP?

The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...

foreach($data as $object) {

        foreach($object as $value) {

            echo $value;

        }

    }

100% width Twitter Bootstrap 3 template

For Bootstrap 3, you would need to use a custom wrapper and set its width to 100%.

.container-full {
  margin: 0 auto;
  width: 100%;
}

Here is a working example on Bootply

If you prefer not to add a custom class, you can acheive a very wide layout (not 100%) by wrapping everything inside a col-lg-12 (wide layout demo)

Update for Bootstrap 3.1

The container-fluid class has returned in Bootstrap 3.1, so this can be used to create a full width layout (no additional CSS required)..

Bootstrap 3.1 demo

Capture key press without placing an input element on the page?

For modern JS, use event.key!

document.addEventListener("keypress", function onPress(event) {
    if (event.key === "z" && event.ctrlKey) {
        // Do something awesome
    }
});

NOTE: The old properties (.keyCode and .which) are Deprecated.

Mozilla Docs

Supported Browsers

Returning Month Name in SQL Server Query

for me DATENAME was not accessable due to company restrictions.... but this worked very easy too.

FORMAT(date, 'MMMM') AS month

Difference between nVidia Quadro and Geforce cards?

The difference is in view-port wire-frame rendering and double-sided polygon rendering, which is very common in professional CAD/3D software but not in games.

The difference is almost 10x-13x faster in single-fixed rendering pipeline (now very obsolete but some CAD software using it) rendering double sided polygons and wireframes:

enter image description here

Thats how entry level Quadro beats high-end GeForce. At least in the single-fixed pipeline using legacy calls like glLightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE). The trick is done with driver optimization (does not matter if its single-fixed pipeline Direct3D or OpenGL). And its true that on some GeForce cards some firmware/hardware hacking can unlock the features.

If double sided is implemented using shader code, the GeForce has to render the polygon twice giving the Quadro only 2x the speed difference (it's less in real-world). The wireframe rendering remains much much slower on GeForce even if implemented in a modern way.

Todays GeForce cards can render millions of polygons per second, drawing lines with faded polygons can result in 100x speed difference eliminating the Quadro benefit.

Quadro equivalent GTX cards have usually better clock speeds giving 2%-10% better performance in games.


So to sum up:

The Quadro rules the single-fixed legacy now obsolete rendering pipeline (which CAD uses), but by implementing modern rendering methods this can be significantly reduced (virtually no speed gain in Maya's Viewport 2.0, it uses GLSL effects - very similar to game engine).

Other reasons to get Quadro are double precision float computations for science, better warranty and display's support for professionals.

That's about it, price-vise the Quadros or FirePros are artificially overpriced.

while EOF in JAVA?

while(inFile.hasNext())

This is correct in java programming language

MySQL "NOT IN" query

Unfortunately it seems to be a issue with MySql usage of "NOT IN" clause, the screen-shoot below shows the sub-query option returning wrong results:

mysql> show variables like '%version%';
+-------------------------+------------------------------+
| Variable_name           | Value                        |
+-------------------------+------------------------------+
| innodb_version          | 1.1.8                        |
| protocol_version        | 10                           |
| slave_type_conversions  |                              |
| version                 | 5.5.21                       |
| version_comment         | MySQL Community Server (GPL) |
| version_compile_machine | x86_64                       |
| version_compile_os      | Linux                        |
+-------------------------+------------------------------+
7 rows in set (0.07 sec)

mysql> select count(*) from TABLE_A where TABLE_A.Pkey not in (select distinct TABLE_B.Fkey from TABLE_B );
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.07 sec)

mysql> select count(*) from TABLE_A left join TABLE_B on TABLE_A.Pkey = TABLE_B.Fkey where TABLE_B.Pkey is null;
+----------+
| count(*) |
+----------+
|      139 |
+----------+
1 row in set (0.06 sec)

mysql> select count(*) from TABLE_A where NOT EXISTS (select * FROM TABLE_B WHERE TABLE_B.Fkey = TABLE_A.Pkey );
+----------+
| count(*) |
+----------+
|      139 |
+----------+
1 row in set (0.06 sec)

mysql> 

How to prevent custom views from losing state across screen orientation changes

I found that this answer was causing some crashes on Android versions 9 and 10. I think it's a good approach but when I was looking at some Android code I found out it was missing a constructor. The answer is quite old so at the time there probably was no need for it. When I added the missing constructor and called it from the creator the crash was fixed.

So here is the edited code:

public class CustomView extends LinearLayout {

    private int stateToSave;

    ...

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        // your custom state
        ss.stateToSave = this.stateToSave;

        return ss;
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container)
    {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        // your custom state
        this.stateToSave = ss.stateToSave;
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
    {
        dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState {
        int stateToSave;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.stateToSave = in.readInt();
        }

        // This was the missing constructor
        @RequiresApi(Build.VERSION_CODES.N)
        SavedState(Parcel in, ClassLoader loader)
        {
            super(in, loader);
            this.stateToSave = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.stateToSave);
        }    
        
        public static final Creator<SavedState> CREATOR =
            new ClassLoaderCreator<SavedState>() {
          
            // This was also missing
            @Override
            public SavedState createFromParcel(Parcel in, ClassLoader loader)
            {
                return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(in, loader) : new SavedState(in);
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in, null);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

How to correct indentation in IntelliJ

Select Java editor settings for Intellij Settings Select values for Tabsize, Indent & Continuation Intent (I choose 4,4 & 4)

Then Ctrl + Alt + L to format your file (or your selection).

How to install a specific version of package using Composer?

Add double quotes to use caret operator in version number.

composer require middlewares/whoops "^0.4"

sed: print only matching group

The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.

For instance: echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7

Will result in output of: 2 3.4

-d sets the delimiter

-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

Use the DOM's getElementByid method:

document.getElementById("DATE").value = "your date";

A date can be made with the Date class:

d = new Date();

(Protip: install a javascript console such as in Chrome or Firefox' Firebug extension. It enables you to play with the DOM and Javascript)

Get current index from foreach loop

You can't, because IEnumerable doesn't have an index at all... if you are sure your enumerable has less than int.MaxValue elements (or long.MaxValue if you use a long index), you can:

  1. Don't use foreach, and use a for loop, converting your IEnumerable to a generic enumerable first:

    var genericList = list.Cast<object>();
    for(int i = 0; i < genericList.Count(); ++i)
    {
       var row = genericList.ElementAt(i);
       /* .... */
    }
    
  2. Have an external index:

    int i = 0;
    foreach(var row in list)
    {
       /* .... */
       ++i;
    }
    
  3. Get the index via Linq:

    foreach(var rowObject in list.Cast<object>().Select((r, i) => new {Row=r, Index=i}))
    {
      var row = rowObject.Row;
      var i = rowObject.Index;
      /* .... */    
    }
    

In your case, since your IEnumerable is not a generic one, I'd rather use the foreach with external index (second method)... otherwise, you may want to make the Cast<object> outside your loop to convert it to an IEnumerable<object>.

Your datatype is not clear from the question, but I'm assuming object since it's an items source (it could be DataGridRow)... you may want to check if it's directly convertible to a generic IEnumerable<object> without having to call Cast<object>(), but I'll make no such assumptions.


All this said:

The concept of an "index" is foreign to an IEnumerable. An IEnumerable can be potentially infinite. In your example, you are using the ItemsSource of a DataGrid, so more likely your IEnumerable is just a list of objects (or DataRows), with a finite (and hopefully less than int.MaxValue) number of members, but IEnumerable can represent anything that can be enumerated (and an enumeration can potentially never end).

Take this example:

public static IEnumerable InfiniteEnumerable()
{
  var rnd = new Random();
  while(true)
  {
    yield return rnd.Next();
  }
}

So if you do:

foreach(var row in InfiniteEnumerable())
{
  /* ... */
}

Your foreach will be infinite: if you used an int (or long) index, you'll eventually overflow it (and unless you use an unchecked context, it'll throw an exception if you keep adding to it: even if you used unchecked, the index would be meaningless also... at some point -when it overflows- the index will be the same for two different values).

So, while the examples given work for a typical usage, I'd rather not use an index at all if you can avoid it.

Align items in a stack panel?

This works perfectly for me. Just put the button first since you're starting on the right. If FlowDirection becomes a problem just add a StackPanel around it and specify FlowDirection="LeftToRight" for that portion. Or simply specify FlowDirection="LeftToRight" for the relevant control.

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" FlowDirection="RightToLeft">
    <Button Width="40" HorizontalAlignment="Right" Margin="3">Right</Button>
    <TextBlock Margin="5">Left</TextBlock>
    <StackPanel FlowDirection="LeftToRight">
        <my:DatePicker Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />    
    </StackPanel>
    <my:DatePicker FlowDirection="LeftToRight" Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />    
</StackPanel>

Get the value of bootstrap Datetimepicker in JavaScript

To call the Bootstrap-datetimepikcer supported functions, you should use the syntax:

$('#datetimepicker').data("DateTimePicker").FUNCTION()

So you can try the function:

$('#datetimepicker').data("DateTimePicker").date();

Documentation: http://eonasdan.github.io/bootstrap-datetimepicker/Functions/

List directory in Go

From your description, what you probably want is os.Readdirnames.

func (f *File) Readdirnames(n int) (names []string, err error)

Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.

...

If n <= 0, Readdirnames returns all the names from the directory in a single slice.

Snippet:

file, err := os.Open(path)
if err != nil {
    return err
}
defer file.Close()
names, err := file.Readdirnames(0)
if err != nil {
    return err
}
fmt.Println(names)

Credit to SquattingSlavInTracksuit's comment; I'd have suggested promoting their comment to an answer if I could.

How to export table data in MySql Workbench to csv?

You can select the rows from the table you want to export in the MySQL Workbench SQL Editor. You will find an Export button in the resultset that will allow you to export the records to a CSV file, as shown in the following image:

MySQL Workbench Export Resultset Button

Please also keep in mind that by default MySQL Workbench limits the size of the resultset to 1000 records. You can easily change that in the Preferences dialog:

MySQL Workbench Preferences Dialog

Hope this helps.

What is Node.js?

Well, I understand that

  • Node's goal is to provide an easy way to build scalable network programs.
  • Node is similar in design to and influenced by systems like Ruby's Event Machine or Python's Twisted.
  • Evented I/O for V8 javascript.

For me that means that you were correct in all three assumptions. The library sure looks promising!

PackagesNotFoundError: The following packages are not available from current channels:

I was trying to install fancyimpute package for imputation but there was not luck. But when i tried below commands, it got installed: Commands:

conda update conda
conda update anaconda
pip install fancyimpute 

(here i was trying to give command conda install fancyimpute which did't work)

What is offsetHeight, clientHeight, scrollHeight?

Offset Means "the amount or distance by which something is out of line". Margin or Borders are something which makes the actual height or width of an HTML element "out of line". It will help you to remember that :

  • offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar.

On the other hand, clientHeight is something which is you can say kind of the opposite of OffsetHeight. It doesn't include the border or margins. It does include the padding because it is something that resides inside of the HTML container, so it doesn't count as extra measurements like margin or border. So :

  • clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin.

ScrollHeight is all the scrollable area, so your scroll will never run over your margin or border, so that's why scrollHeight doesn't include margin or borders but yeah padding does. So:

  • scrollHeight value is equal to the minimum height the element would require in order to fit all the content in the viewport without using a vertical scrollbar. The height is measured in the same way as clientHeight: it includes the element's padding, but not its border, margin or horizontal scrollbar.

How to Kill A Session or Session ID (ASP.NET/C#)

Session["YourItem"] = "";

Works great in .net razor web pages.

Importing csv file into R - numeric values read as characters

I had a similar problem. Based on Joshua's premise that excel was the problem I looked at it and found that the numbers were formatted with commas between every third digit. Reformatting without commas fixed the problem.

What are the differences between a superkey and a candidate key?

Super key is the combination of fields by which the row is uniquely identified and the candidate key is the minimal super key.

ViewPager PagerAdapter not updating the View

Two and half years after the OP posed his question, this issue is still, well, still an issue. It's obvious Google's priority on this isn't particularly high, so rather than find a fix, I found a workaround. The big breakthrough for me was finding out what the real cause of the problem was (see the accepted answer in this post ). Once it was apparent that the issue was that any active pages are not properly refreshed, my workaround was obvious:

In my Fragment (the pages):

  • I took all the code which populates the form out of onCreateView and put it in a function called PopulateForm which may be called from anywhere, rather than by the framework. This function attempts to get the current View using getView, and if that is null, it just returns. It's important that PopulateForm contains only the code that displays - all the other code which creates FocusChange listeners and the like is still in OnCreate
  • Create a boolean which can be used as a flag indicating the form must be reloaded. Mine is mbReloadForm
  • Override OnResume() to call PopulateForm() if mbReloadForm is set.

In my Activity, where I do the loading of the pages:

  • Go to page 0 before changing anything. I'm using FragmentStatePagerAdapter, so I know that two or three pages are affected at most. Changing to page 0 ensures I only ever have the problem on pages 0, 1 and 2.
  • Before clearing the old list, take it's size(). This way you know how many pages are affected by the bug. If > 3, reduce it to 3 - if you're using a a different PagerAdapter, you'll have to see how many pages you have to deal with (maybe all?)
  • Reload the data and call pageAdapter.notifyDataSetChanged()
  • Now, for each of the affected pages, see if the page is active by using pager.getChildAt(i) - this tells you if you have a view. If so, call pager.PopulateView(). If not, set the ReloadForm flag.

After this, when you reload a second set of pages, the bug will still cause some to display the old data. However, they will now be refreshed and you will see the new data - your users won't know the page was ever incorrect because this refreshing will happen before they see the page.

Hope this helps someone!

Get data type of field in select statement in ORACLE

I found a not-very-intuitive way to do this by using DUMP()

SELECT DUMP(A.NAME), 
       DUMP(A.surname), 
       DUMP(B.ordernum) 
FROM   customer A 
       JOIN orders B 
         ON A.id = B.id

It will return something like:

'Typ=1 Len=2: 0,48' for each column.

Type=1 means VARCHAR2/NVARCHAR2
Type=2 means NUMBER/FLOAT
Type=12 means DATE, etc.

You can refer to this oracle doc for information Datatype Code
or this for a simple mapping Oracle Type Code Mappings

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I'm the creator of Restangular.

You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).

Check out this plunkr example:

http://plnkr.co/edit/d6yDka?p=preview

You could also see the README and check the documentation here https://github.com/mgonto/restangular

If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)

Hope it helps!

Prevent form submission on Enter key press

<div class="nav-search" id="nav-search">
        <form class="form-search">
            <span class="input-icon">
                <input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
                <i class="ace-icon fa fa-search nav-search-icon"></i>
            </span>
            <input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
        </form>

</div>

<script type="text/javascript">
    $("#search_value").on('keydown', function(e) {
        if (e.which == 13) {
             $("#search").trigger('click');
            return false;
        }
    });
    $("#search").on('click',function(){
        alert('You press enter');
    });
</script>

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.

"Release 0.8.7 - May 13 2016

-Fix for issue when inserting read-only images on Windows. Issue #352.

-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.

-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."

Selecting data from two different servers in SQL Server

As @Super9 told about OPENDATASOURCE using SQL Server Authentication with data provider SQLOLEDB . I am just posting here a code snippet for one table is in the current sever database where the code is running and another in other server '192.166.41.123'

SELECT top 2 * from dbo.tblHamdoonSoft  tbl1 inner JOIN  
OpenDataSource('SQLOLEDB','Data Source=192.166.41.123;User ID=sa;Password=hamdoonsoft')
.[TestDatabase].[dbo].[tblHamdoonSoft1] tbl2 on tbl1.id = tbl2.id

How can I force clients to refresh JavaScript files?

FRONT-END OPTION

I made this code specifically for those who can't change any settings on the backend. In this case the best way to prevent a very long cache is with:

new Date().getTime()

However, for most programmers the cache can be a few minutes or hours so the simple code above ends up forcing all users to download "the each page browsed". To specify how long this item will remain without reloading I made this code and left several examples below:

// cache-expires-after.js v1
function cacheExpiresAfter(delay = 1, prefix = '', suffix = '') { // seconds
    let now = new Date().getTime().toString();
    now = now.substring(now.length - 11, 10); // remove decades and milliseconds
    now = parseInt(now / delay).toString();
    return prefix + now + suffix;
};

// examples (of the delay argument):
// the value changes every 1 second
var cache = cacheExpiresAfter(1);
// see the sync
setInterval(function(){
    console.log(cacheExpiresAfter(1), new Date().getSeconds() + 's');
}, 1000);

// the value changes every 1 minute
var cache = cacheExpiresAfter(60);
// see the sync
setInterval(function(){
    console.log(cacheExpiresAfter(60), new Date().getMinutes() + 'm:' + new Date().getSeconds() + 's');
}, 1000);

// the value changes every 5 minutes
var cache = cacheExpiresAfter(60 * 5); // OR 300

// the value changes every 1 hour
var cache = cacheExpiresAfter(60 * 60); // OR 3600

// the value changes every 3 hours
var cache = cacheExpiresAfter(60 * 60 * 3); // OR 10800

// the value changes every 1 day
var cache = cacheExpiresAfter(60 * 60 * 24); // OR 86400

// usage example:
let head = (document.head || document.getElementsByTagName('head')[0]);
let script = document.createElement('script');
script.setAttribute('src', '//unpkg.com/[email protected]/dist/sweetalert.min.js' + cacheExpiresAfter(60 * 5, '?'));
head.append(script);

// this works?
let waitSwal = setInterval(function() {
    if (window.swal) {
        clearInterval(waitSwal);
        swal('Script successfully injected', script.outerHTML);
    };
}, 100);

return string with first match Regex

You shouldn't be using .findall() at all - .search() is what you want. It finds the leftmost match, which is what you want (or returns None if no match exists).

m = re.search(pattern, text)
result = m.group(0) if m else ""

Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search() on its own finds a match (it returns None if it didn't, or an SRE_Match object if it did).

DateTime fields from SQL Server display incorrectly in Excel

i've faced the same problem when copying data from ssms to excel. the date format got messed up. at last i changed my laptop's system date format to yyyy-mm-dd from yyyy/mm/dd. everything works just fine.

How to access iOS simulator camera

It's not possible to access camera of your development machine to be used as simulator camera. Camera functionality is not available in any iOS version and any Simulator. You will have to use device for testing camera purpose.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

Create a function with optional call variables

Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."

By default, all parameters are optional. The most basic approach is to simply check each one for $null, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.

If you want to learn about all of the special support that Powershell can give you, check out these links:

about_Functions

about_Functions_Advanced

about_Functions_Advanced_Parameters

Could not open a connection to your authentication agent

The basic solution to run ssh-agent is answered in many answers. However runing ssh-agent many times (per each opened terminal or per remote login) will create a many copies ot ssh-agent running in memory. The scripts which is suggested to avoid that problem is long and need to write and/or copy separated file or need to write too many strings in ~/.profile or ~/.schrc. Let me suggest simple two string solution:

For sh, bash, etc:

# ~/.profile
if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -s > ~/.ssh-agent.sh; fi
. ~/.ssh-agent.sh

For csh, tcsh, etc:

# ~/.schrc
sh -c 'if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -c > ~/.ssh-agent.tcsh; fi'
eval `cat ~/.ssh-agent.tcsh`

What is here:

  • search the process ssh-agent by name and by current user
  • create appropriate shell script file by calling ssh-agent and run ssh-agent itself if no current user ssh-agent process found
  • evaluate created shell script which configure appropriate environment

It is not necessary to protect created shell script ~/.ssh-agent.tcsh or ~/.ssh-agent.sh from another users access because: at-first communication with ssh-agent is processed through protected socket which is not accessible to another users, and at-second another users can found ssh-agent socket simple by enumeration files in /tmp/ directory. As far as about access to ssh-agent process it is the same things.

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

try to clear workspace.

rm -rf ' ~/Library/Application\ Support/"your programm name" '

Remove Elements from a HashSet while Iterating

Here's the more modern streams approach:

myIntegerSet.stream().filter((it) -> it % 2 != 0).collect(Collectors.toSet())

However, this makes a new set, so memory constraints might be an issue if it's a really huge set.

EDIT: previous version of this answer suggested Apache CollectionUtils but that was before steams came about.

What is the difference between 'E', 'T', and '?' for Java generics?

The previous answers explain type parameters (T, E, etc.), but don't explain the wildcard, "?", or the differences between them, so I'll address that.

First, just to be clear: the wildcard and type parameters are not the same. Where type parameters define a sort of variable (e.g., T) that represents the type for a scope, the wildcard does not: the wildcard just defines a set of allowable types that you can use for a generic type. Without any bounding (extends or super), the wildcard means "use any type here".

The wildcard always come between angle brackets, and it only has meaning in the context of a generic type:

public void foo(List<?> listOfAnyType) {...}  // pass a List of any type

never

public <?> ? bar(? someType) {...}  // error. Must use type params here

or

public class MyGeneric ? {      // error
    public ? getFoo() { ... }   // error
    ...
}

It gets more confusing where they overlap. For example:

List<T> fooList;  // A list which will be of type T, when T is chosen.
                  // Requires T was defined above in this scope
List<?> barList;  // A list of some type, decided elsewhere. You can do
                  // this anywhere, no T required.

There's a lot of overlap in what's possible with method definitions. The following are, functionally, identical:

public <T> void foo(List<T> listOfT) {...}
public void bar(List<?> listOfSomething)  {...}

So, if there's overlap, why use one or the other? Sometimes, it's honestly just style: some people say that if you don't need a type param, you should use a wildcard just to make the code simpler/more readable. One main difference I explained above: type params define a type variable (e.g., T) which you can use elsewhere in the scope; the wildcard doesn't. Otherwise, there are two big differences between type params and the wildcard:

Type params can have multiple bounding classes; the wildcard cannot:

public class Foo <T extends Comparable<T> & Cloneable> {...}

The wildcard can have lower bounds; type params cannot:

public void bar(List<? super Integer> list) {...}

In the above the List<? super Integer> defines Integer as a lower bound on the wildcard, meaning that the List type must be Integer or a super-type of Integer. Generic type bounding is beyond what I want to cover in detail. In short, it allows you to define which types a generic type can be. This makes it possible to treat generics polymorphically. E.g. with:

public void foo(List<? extends Number> numbers) {...}

You can pass a List<Integer>, List<Float>, List<Byte>, etc. for numbers. Without type bounding, this won't work -- that's just how generics are.

Finally, here's a method definition which uses the wildcard to do something that I don't think you can do any other way:

public static <T extends Number> void adder(T elem, List<? super Number> numberSuper) {
    numberSuper.add(elem);
}

numberSuper can be a List of Number or any supertype of Number (e.g., List<Object>), and elem must be Number or any subtype. With all the bounding, the compiler can be certain that the .add() is typesafe.

'heroku' does not appear to be a git repository

I got the same error and it turned out I was in the wrong directory. It's a simple mistake to make so double check that you are in the root and then run heroku create and heroku git push master again. Of course you must have done git init, as mentioned in StickMaNX answer above, already before the heroku steps.

Is it possible to view RabbitMQ message contents directly from the command line?

If you want multiple messages from a queue, say 10 messages, the command to use is:

rabbitmqadmin get queue=<QueueName> ackmode=ack_requeue_true count=10

If you don't want the messages requeued, just change ackmode to ack_requeue_false.

MySQL INNER JOIN select only one row from second table

You need to have a subquery to get their latest date per user ID.

SELECT  a.*, c.*
FROM users a 
    INNER JOIN payments c
        ON a.id = c.user_ID
    INNER JOIN
    (
        SELECT user_ID, MAX(date) maxDate
        FROM payments
        GROUP BY user_ID
    ) b ON c.user_ID = b.user_ID AND
            c.date = b.maxDate
WHERE a.package = 1

proper way to sudo over ssh

Sudo over SSH passing a password, no tty required:

You can use sudo over ssh without forcing ssh to have a pseudo-tty (without the use of the ssh "-t" switch) by telling sudo not to require an interactive password and to just grab the password off stdin. You do this by using the "-S" switch on sudo. This makes sudo listen for the password on stdin, and stop listening when it sees a newline.

Example 1 - Simple Remote Command

In this example, we send a simple whoami command:

$ ssh user@server cat \| sudo --prompt="" -S -- whoami << EOF
> <remote_sudo_password>
root

We're telling sudo not to issue a prompt, and to take its input from stdin. This makes the sudo password passing completely silent so the only response you get back is the output from whoami.

This technique has the benefit of allowing you to run programs through sudo over ssh that themselves require stdin input. This is because sudo is consuming the password over the first line of stdin, then letting whatever program it runs continue to grab stdin.

Example 2 - Remote Command That Requires Its Own stdin

In the following example, the remote command "cat" is executed through sudo, and we are providing some extra lines through stdin for the remote cat to display.

$ ssh user@server cat \| sudo --prompt="" -S -- "cat" << EOF
> <remote_sudo_password>
> Extra line1
> Extra line2
> EOF
Extra line1
Extra line2

The output demonstrates that the <remote_sudo_password> line is being consumed by sudo, and that the remotely executed cat is then displaying the extra lines.

An example of where this would be beneficial is if you want to use ssh to pass a password to a privileged command without using the command line. Say, if you want to mount a remote encrypted container over ssh.

Example 3 - Mounting a Remote VeraCrypt Container

In this example script, we are remotely mounting a VeraCrypt container through sudo without any extra prompting text:

#!/bin/sh
ssh user@server cat \| sudo --prompt="" -S -- "veracrypt --non-interactive --stdin --keyfiles=/path/to/test.key /path/to/test.img /mnt/mountpoint" << EOF
SudoPassword
VeraCryptContainerPassword
EOF

It should be noted that in all the command-line examples above (everything except the script) the << EOF construct on the command line will cause the everything typed, including the password, to be recorded in the local machine's .bash_history. It is therefore highly recommended that for real-world use you either use do it entirely through a script, like the veracrypt example above, or, if on the command line then put the password in a file and redirect that file through ssh.

Example 1a - Example 1 Without Local Command-Line Password

The first example would thus become:

$ cat text_file_with_sudo_password | ssh user@server cat \| sudo --prompt="" -S -- whoami
root

Example 2a - Example 2 Without Local Command-Line Password

and the second example would become:

$ cat text_file_with_sudo_password - << EOF | ssh va1der.net cat \| sudo --prompt="" -S -- cat
> Extra line1
> Extra line2
> EOF
Extra line1
Extra line2

Putting the password in a separate file is unnecessary if you are putting the whole thing in a script, since the contents of scripts do not end up in your history. It still may be useful, though, in case you want to allow users who should not see the password to execute the script.

Converting File to MultiPartFile

MultipartFile multipartFile = new MockMultipartFile("test.xlsx", new FileInputStream(new File("/home/admin/test.xlsx")));

This code works fine for me. May be you can have a try.

Postgresql GROUP_CONCAT equivalent?

Hope below Oracle query will work.

Select First_column,LISTAGG(second_column,',') 
    WITHIN GROUP (ORDER BY second_column) as Sec_column, 
    LISTAGG(third_column,',') 
    WITHIN GROUP (ORDER BY second_column) as thrd_column 
FROM tablename 
GROUP BY first_column

Is it safe to store a JWT in localStorage with ReactJS?

It is safe to store your token in localStorage as long as you encrypt it. Below is a compressed code snippet showing one of many ways you can do it.

    import SimpleCrypto from 'simple-crypto-js';

    const saveToken = (token = '') => {
          const encryptInit = new SimpleCrypto('PRIVATE_KEY_STORED_IN_ENV_FILE');
          const encryptedToken = encryptInit.encrypt(token);

          localStorage.setItem('token', encryptedToken);
     }

Then, before using your token decrypt it using PRIVATE_KEY_STORED_IN_ENV_FILE

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SSMS, "Query" menu item... "Results to"... "Results to File"

Shortcut = CTRL+shift+F

You can set it globally too

"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down

Edit: after comment

In SSMS, "Query" menu item... "SQLCMD" mode

This allows you to run "command line" like actions.

A quick test in my SSMS 2008

:OUT c:\foo.txt
SELECT * FROM sys.objects

Edit, Sep 2012

:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects

Why do some functions have underscores "__" before and after the function name?

Added an example to understand the use of __ in python. Here is the list of All __

https://docs.python.org/3/genindex-all.html#_

Certain classes of identifiers (besides keywords) have special meanings. Any use of * names, in any other context, that does not follow explicitly documented use, is subject to breakage without warning

Access restriction using __

"""
Identifiers:
-  Contain only (A-z, 0-9, and _ )
-  Start with a lowercase letter or _.
-  Single leading _ :  private
-  Double leading __ :  strong private
-  Start & End  __ : Language defined Special Name of Object/ Method
-  Class names start with an uppercase letter.
-

"""


class BankAccount(object):
    def __init__(self, name, money, password):
        self.name = name            # Public
        self._money = money         # Private : Package Level
        self.__password = password  # Super Private

    def earn_money(self, amount):
        self._money += amount
        print("Salary Received: ", amount, " Updated Balance is: ", self._money)

    def withdraw_money(self, amount):
        self._money -= amount
        print("Money Withdraw: ", amount, " Updated Balance is: ", self._money)

    def show_balance(self):
        print(" Current Balance is: ", self._money)


account = BankAccount("Hitesh", 1000, "PWD")  # Object Initalization

# Method Call
account.earn_money(100)

# Show Balance
print(account.show_balance())

print("PUBLIC ACCESS:", account.name)  # Public Access

# account._money is accessible because it is only hidden by convention
print("PROTECTED ACCESS:", account._money)  # Protected Access

# account.__password will throw error but account._BankAccount__password will not
# because __password is super private
print("PRIVATE ACCESS:", account._BankAccount__password)

# Method Call
account.withdraw_money(200)

# Show Balance
print(account.show_balance())

# account._money is accessible because it is only hidden by convention
print(account._money)  # Protected Access

Taking multiple inputs from user in python

How about something like this?

user_input = raw_input("Enter three numbers separated by commas: ")

input_list = user_input.split(',')
numbers = [float(x.strip()) for x in input_list]

(You would probably want some error handling too)

Copy mysql database from remote server to local computer

Check syntax and execute one command at a time, then verify output.

mysqldump -u remoteusername -p remotepassword -h your.site.com databasename > dump.sql

mysql -u localusername -p localpassword databasename < dump.sql

Once you've matched all passwords, you can use pipe.

Java: Simplest way to get last word in a string

String testString = "This is a sentence";
String[] parts = testString.split(" ");
String lastWord = parts[parts.length - 1];
System.out.println(lastWord); // "sentence"

Sending commands and strings to Terminal.app with Applescript

How about this? There's no need for key codes (at least in Lion, not sure about earlier), and a subroutine simplifies the main script.

The below script will ssh to localhost as user "me", enter password "myPassw0rd" after a 1 second delay, issue ls, delay 2 seconds, and then exit.

tell application "Terminal"
    activate
    my execCmd("ssh me@localhost", 1)
    my execCmd("myPassw0rd", 0)
    my execCmd("ls", 2)
    my execCmd("exit", 0)
end tell
on execCmd(cmd, pause)
    tell application "System Events"
        tell application process "Terminal"
            set frontmost to true
            keystroke cmd
            keystroke return
        end tell
    end tell
    delay pause
end execCmd

Set UIButton title UILabel font size programmatically

You can also set the font size, and the font style using something like this. It's a little more than what you're asking for but hey, what the heck...

[myButton.titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:13.0]];

And… if you're feeling frisky a list of available fonts can be found by implementing this code and then checking the output in your xCode debugger.

Code:

NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
for (indFamily=0; indFamily<[familyNames count]; ++indFamily)
{
    NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
    fontNames = [[NSArray alloc] initWithArray:
            [UIFont fontNamesForFamilyName:
            [familyNames objectAtIndex:indFamily]]];
    for (indFont=0; indFont<[fontNames count]; ++indFont)
    {
        NSLog(@"    Font name: %@", [fontNames objectAtIndex:indFont]);
    }
}

Example:

2012-04-02 11:36:34.395 MyApp[3579:707] Family name: Thonburi
2012-04-02 11:36:34.398 MyApp[3579:707]     Font name: Thonburi-Bold
2012-04-02 11:36:34.402 MyApp[3579:707]     Font name: Thonburi
2012-04-02 11:36:34.405 MyApp[3579:707] Family name: Snell Roundhand
2012-04-02 11:36:34.408 MyApp[3579:707]     Font name: SnellRoundhand-Bold
2012-04-02 11:36:34.411 MyApp[3579:707]     Font name: SnellRoundhand-Black
2012-04-02 11:36:34.415 MyApp[3579:707]     Font name: SnellRoundhand
2012-04-02 11:36:34.418 MyApp[3579:707] Family name: Academy Engraved LET
2012-04-02 11:36:34.421 MyApp[3579:707]     Font name: AcademyEngravedLetPlain
2012-04-02 11:36:34.424 MyApp[3579:707] Family name: Marker Felt
2012-04-02 11:36:34.427 MyApp[3579:707]     Font name: MarkerFelt-Wide
2012-04-02 11:36:34.430 MyApp[3579:707]     Font name: MarkerFelt-Thin
2012-04-02 11:36:34.434 MyApp[3579:707] Family name: Geeza Pro
2012-04-02 11:36:34.437 MyApp[3579:707]     Font name: GeezaPro-Bold
2012-04-02 11:36:34.441 MyApp[3579:707]     Font name: GeezaPro
2012-04-02 11:36:34.445 MyApp[3579:707] Family name: Arial Rounded MT Bold
2012-04-02 11:36:34.448 MyApp[3579:707]     Font name: ArialRoundedMTBold
2012-04-02 11:36:34.451 MyApp[3579:707] Family name: Trebuchet MS
2012-04-02 11:36:34.455 MyApp[3579:707]     Font name: TrebuchetMS
2012-04-02 11:36:34.458 MyApp[3579:707]     Font name: TrebuchetMS-Bold
2012-04-02 11:36:34.461 MyApp[3579:707]     Font name: TrebuchetMS-Italic
2012-04-02 11:36:34.464 MyApp[3579:707]     Font name: Trebuchet-BoldItalic
2012-04-02 11:36:34.467 MyApp[3579:707] Family name: Arial
2012-04-02 11:36:34.471 MyApp[3579:707]     Font name: Arial-BoldMT
2012-04-02 11:36:34.474 MyApp[3579:707]     Font name: ArialMT
2012-04-02 11:36:34.477 MyApp[3579:707]     Font name: Arial-ItalicMT
2012-04-02 11:36:34.480 MyApp[3579:707]     Font name: Arial-BoldItalicMT
2012-04-02 11:36:34.483 MyApp[3579:707] Family name: Marion
2012-04-02 11:36:34.487 MyApp[3579:707]     Font name: Marion-Regular
2012-04-02 11:36:34.491 MyApp[3579:707]     Font name: Marion-Bold
2012-04-02 11:36:34.494 MyApp[3579:707]     Font name: Marion-Italic
2012-04-02 11:36:34.503 MyApp[3579:707] Family name: Gurmukhi MN
2012-04-02 11:36:34.507 MyApp[3579:707]     Font name: GurmukhiMN
2012-04-02 11:36:34.511 MyApp[3579:707]     Font name: GurmukhiMN-Bold
2012-04-02 11:36:34.514 MyApp[3579:707] Family name: Malayalam Sangam MN
2012-04-02 11:36:34.518 MyApp[3579:707]     Font name: MalayalamSangamMN-Bold
2012-04-02 11:36:34.522 MyApp[3579:707]     Font name: MalayalamSangamMN
2012-04-02 11:36:34.525 MyApp[3579:707] Family name: Bradley Hand
2012-04-02 11:36:34.529 MyApp[3579:707]     Font name: BradleyHandITCTT-Bold
2012-04-02 11:36:34.532 MyApp[3579:707] Family name: Kannada Sangam MN
2012-04-02 11:36:34.536 MyApp[3579:707]     Font name: KannadaSangamMN
2012-04-02 11:36:34.540 MyApp[3579:707]     Font name: KannadaSangamMN-Bold
2012-04-02 11:36:34.544 MyApp[3579:707] Family name: Bodoni 72 Oldstyle
2012-04-02 11:36:34.548 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-Book
2012-04-02 11:36:34.552 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-Bold
2012-04-02 11:36:34.555 MyApp[3579:707]     Font name: BodoniSvtyTwoOSITCTT-BookIt
2012-04-02 11:36:34.559 MyApp[3579:707] Family name: Cochin
2012-04-02 11:36:34.562 MyApp[3579:707]     Font name: Cochin
2012-04-02 11:36:34.566 MyApp[3579:707]     Font name: Cochin-BoldItalic
2012-04-02 11:36:34.570 MyApp[3579:707]     Font name: Cochin-Italic
2012-04-02 11:36:34.573 MyApp[3579:707]     Font name: Cochin-Bold
2012-04-02 11:36:34.577 MyApp[3579:707] Family name: Sinhala Sangam MN
2012-04-02 11:36:34.581 MyApp[3579:707]     Font name: SinhalaSangamMN
2012-04-02 11:36:34.584 MyApp[3579:707]     Font name: SinhalaSangamMN-Bold
2012-04-02 11:36:34.588 MyApp[3579:707] Family name: Hiragino Kaku Gothic ProN
2012-04-02 11:36:34.592 MyApp[3579:707]     Font name: HiraKakuProN-W6
2012-04-02 11:36:34.596 MyApp[3579:707]     Font name: HiraKakuProN-W3
2012-04-02 11:36:34.599 MyApp[3579:707] Family name: Papyrus
2012-04-02 11:36:34.603 MyApp[3579:707]     Font name: Papyrus-Condensed
2012-04-02 11:36:34.607 MyApp[3579:707]     Font name: Papyrus
2012-04-02 11:36:34.614 MyApp[3579:707] Family name: Verdana
2012-04-02 11:36:34.620 MyApp[3579:707]     Font name: Verdana
2012-04-02 11:36:34.626 MyApp[3579:707]     Font name: Verdana-Bold
2012-04-02 11:36:34.674 MyApp[3579:707]     Font name: Verdana-BoldItalic
2012-04-02 11:36:34.690 MyApp[3579:707]     Font name: Verdana-Italic
2012-04-02 11:36:34.730 MyApp[3579:707] Family name: Zapf Dingbats
2012-04-02 11:36:34.748 MyApp[3579:707]     Font name: ZapfDingbatsITC
2012-04-02 11:36:34.752 MyApp[3579:707] Family name: Courier
2012-04-02 11:36:34.757 MyApp[3579:707]     Font name: Courier-Bold
2012-04-02 11:36:34.762 MyApp[3579:707]     Font name: Courier
2012-04-02 11:36:34.769 MyApp[3579:707]     Font name: Courier-BoldOblique
2012-04-02 11:36:34.778 MyApp[3579:707]     Font name: Courier-Oblique
2012-04-02 11:36:34.786 MyApp[3579:707] Family name: Hoefler Text
2012-04-02 11:36:34.793 MyApp[3579:707]     Font name: HoeflerText-Black
2012-04-02 11:36:34.802 MyApp[3579:707]     Font name: HoeflerText-Italic
2012-04-02 11:36:34.810 MyApp[3579:707]     Font name: HoeflerText-Regular
2012-04-02 11:36:34.819 MyApp[3579:707]     Font name: HoeflerText-BlackItalic
2012-04-02 11:36:34.827 MyApp[3579:707] Family name: Euphemia UCAS
2012-04-02 11:36:34.836 MyApp[3579:707]     Font name: EuphemiaUCAS-Bold
2012-04-02 11:36:34.843 MyApp[3579:707]     Font name: EuphemiaUCAS
2012-04-02 11:36:34.848 MyApp[3579:707]     Font name: EuphemiaUCAS-Italic
2012-04-02 11:36:34.853 MyApp[3579:707] Family name: Helvetica
2012-04-02 11:36:34.857 MyApp[3579:707]     Font name: Helvetica-LightOblique
2012-04-02 11:36:34.863 MyApp[3579:707]     Font name: Helvetica
2012-04-02 11:36:34.873 MyApp[3579:707]     Font name: Helvetica-Oblique
2012-04-02 11:36:34.876 MyApp[3579:707]     Font name: Helvetica-BoldOblique
2012-04-02 11:36:34.880 MyApp[3579:707]     Font name: Helvetica-Bold
2012-04-02 11:36:34.884 MyApp[3579:707]     Font name: Helvetica-Light
2012-04-02 11:36:34.887 MyApp[3579:707] Family name: Hiragino Mincho ProN
2012-04-02 11:36:34.892 MyApp[3579:707]     Font name: HiraMinProN-W3
2012-04-02 11:36:34.898 MyApp[3579:707]     Font name: HiraMinProN-W6
2012-04-02 11:36:34.902 MyApp[3579:707] Family name: Bodoni Ornaments
2012-04-02 11:36:34.905 MyApp[3579:707]     Font name: BodoniOrnamentsITCTT
2012-04-02 11:36:34.923 MyApp[3579:707] Family name: Apple Color Emoji
2012-04-02 11:36:34.938 MyApp[3579:707]     Font name: AppleColorEmoji
2012-04-02 11:36:34.942 MyApp[3579:707] Family name: Optima
2012-04-02 11:36:34.946 MyApp[3579:707]     Font name: Optima-ExtraBlack
2012-04-02 11:36:34.950 MyApp[3579:707]     Font name: Optima-Italic
2012-04-02 11:36:34.954 MyApp[3579:707]     Font name: Optima-Regular
2012-04-02 11:36:34.965 MyApp[3579:707]     Font name: Optima-BoldItalic
2012-04-02 11:36:34.969 MyApp[3579:707]     Font name: Optima-Bold
2012-04-02 11:36:34.972 MyApp[3579:707] Family name: Gujarati Sangam MN
2012-04-02 11:36:34.985 MyApp[3579:707]     Font name: GujaratiSangamMN
2012-04-02 11:36:34.989 MyApp[3579:707]     Font name: GujaratiSangamMN-Bold
2012-04-02 11:36:34.993 MyApp[3579:707] Family name: Devanagari Sangam MN
2012-04-02 11:36:34.998 MyApp[3579:707]     Font name: DevanagariSangamMN
2012-04-02 11:36:35.002 MyApp[3579:707]     Font name: DevanagariSangamMN-Bold
2012-04-02 11:36:35.006 MyApp[3579:707] Family name: Times New Roman
2012-04-02 11:36:35.017 MyApp[3579:707]     Font name: TimesNewRomanPS-ItalicMT
2012-04-02 11:36:35.021 MyApp[3579:707]     Font name: TimesNewRomanPS-BoldMT
2012-04-02 11:36:35.032 MyApp[3579:707]     Font name: TimesNewRomanPSMT
2012-04-02 11:36:35.037 MyApp[3579:707]     Font name: TimesNewRomanPS-BoldItalicMT
2012-04-02 11:36:35.041 MyApp[3579:707] Family name: Kailasa
2012-04-02 11:36:35.045 MyApp[3579:707]     Font name: Kailasa
2012-04-02 11:36:35.050 MyApp[3579:707]     Font name: Kailasa-Bold
2012-04-02 11:36:35.053 MyApp[3579:707] Family name: Telugu Sangam MN
2012-04-02 11:36:35.064 MyApp[3579:707]     Font name: TeluguSangamMN-Bold
2012-04-02 11:36:35.068 MyApp[3579:707]     Font name: TeluguSangamMN
2012-04-02 11:36:35.071 MyApp[3579:707] Family name: Heiti SC
2012-04-02 11:36:35.099 MyApp[3579:707]     Font name: STHeitiSC-Medium
2012-04-02 11:36:35.107 MyApp[3579:707]     Font name: STHeitiSC-Light
2012-04-02 11:36:35.111 MyApp[3579:707] Family name: Futura
2012-04-02 11:36:35.115 MyApp[3579:707]     Font name: Futura-Medium
2012-04-02 11:36:35.119 MyApp[3579:707]     Font name: Futura-CondensedExtraBold
2012-04-02 11:36:35.122 MyApp[3579:707]     Font name: Futura-CondensedMedium
2012-04-02 11:36:35.135 MyApp[3579:707]     Font name: Futura-MediumItalic
2012-04-02 11:36:35.155 MyApp[3579:707] Family name: Bodoni 72
2012-04-02 11:36:35.160 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-BookIta
2012-04-02 11:36:35.164 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-Book
2012-04-02 11:36:35.168 MyApp[3579:707]     Font name: BodoniSvtyTwoITCTT-Bold
2012-04-02 11:36:35.171 MyApp[3579:707] Family name: Baskerville
2012-04-02 11:36:35.183 MyApp[3579:707]     Font name: Baskerville-SemiBoldItalic
2012-04-02 11:36:35.187 MyApp[3579:707]     Font name: Baskerville-Bold
2012-04-02 11:36:35.197 MyApp[3579:707]     Font name: Baskerville-Italic
2012-04-02 11:36:35.245 MyApp[3579:707]     Font name: Baskerville-BoldItalic
2012-04-02 11:36:35.253 MyApp[3579:707]     Font name: Baskerville-SemiBold
2012-04-02 11:36:35.258 MyApp[3579:707]     Font name: Baskerville
2012-04-02 11:36:35.262 MyApp[3579:707] Family name: Chalkboard SE
2012-04-02 11:36:35.266 MyApp[3579:707]     Font name: ChalkboardSE-Regular
2012-04-02 11:36:35.269 MyApp[3579:707]     Font name: ChalkboardSE-Bold
2012-04-02 11:36:35.279 MyApp[3579:707]     Font name: ChalkboardSE-Light
2012-04-02 11:36:35.284 MyApp[3579:707] Family name: Heiti TC
2012-04-02 11:36:35.288 MyApp[3579:707]     Font name: STHeitiTC-Medium
2012-04-02 11:36:35.299 MyApp[3579:707]     Font name: STHeitiTC-Light
2012-04-02 11:36:35.305 MyApp[3579:707] Family name: Copperplate
2012-04-02 11:36:35.310 MyApp[3579:707]     Font name: Copperplate
2012-04-02 11:36:35.313 MyApp[3579:707]     Font name: Copperplate-Light
2012-04-02 11:36:35.317 MyApp[3579:707]     Font name: Copperplate-Bold
2012-04-02 11:36:35.320 MyApp[3579:707] Family name: Party LET
2012-04-02 11:36:35.334 MyApp[3579:707]     Font name: PartyLetPlain
2012-04-02 11:36:35.338 MyApp[3579:707] Family name: American Typewriter
2012-04-02 11:36:35.351 MyApp[3579:707]     Font name: AmericanTypewriter-CondensedLight
2012-04-02 11:36:35.357 MyApp[3579:707]     Font name: AmericanTypewriter-Light
2012-04-02 11:36:35.361 MyApp[3579:707]     Font name: AmericanTypewriter-Bold
2012-04-02 11:36:35.364 MyApp[3579:707]     Font name: AmericanTypewriter
2012-04-02 11:36:35.368 MyApp[3579:707]     Font name: AmericanTypewriter-CondensedBold
2012-04-02 11:36:35.372 MyApp[3579:707]     Font name: AmericanTypewriter-Condensed
2012-04-02 11:36:35.384 MyApp[3579:707] Family name: AppleGothic
2012-04-02 11:36:35.400 MyApp[3579:707]     Font name: AppleGothic
2012-04-02 11:36:35.406 MyApp[3579:707] Family name: Bangla Sangam MN
2012-04-02 11:36:35.411 MyApp[3579:707]     Font name: BanglaSangamMN-Bold
2012-04-02 11:36:35.414 MyApp[3579:707]     Font name: BanglaSangamMN
2012-04-02 11:36:35.418 MyApp[3579:707] Family name: Noteworthy
2012-04-02 11:36:35.422 MyApp[3579:707]     Font name: Noteworthy-Light
2012-04-02 11:36:35.432 MyApp[3579:707]     Font name: Noteworthy-Bold
2012-04-02 11:36:35.436 MyApp[3579:707] Family name: Zapfino
2012-04-02 11:36:35.443 MyApp[3579:707]     Font name: Zapfino
2012-04-02 11:36:35.448 MyApp[3579:707] Family name: Tamil Sangam MN
2012-04-02 11:36:35.452 MyApp[3579:707]     Font name: TamilSangamMN
2012-04-02 11:36:35.456 MyApp[3579:707]     Font name: TamilSangamMN-Bold
2012-04-02 11:36:35.459 MyApp[3579:707] Family name: DB LCD Temp
2012-04-02 11:36:35.463 MyApp[3579:707]     Font name: DBLCDTempBlack
2012-04-02 11:36:35.467 MyApp[3579:707] Family name: Arial Hebrew
2012-04-02 11:36:35.471 MyApp[3579:707]     Font name: ArialHebrew
2012-04-02 11:36:35.475 MyApp[3579:707]     Font name: ArialHebrew-Bold
2012-04-02 11:36:35.479 MyApp[3579:707] Family name: Chalkduster
2012-04-02 11:36:35.482 MyApp[3579:707]     Font name: Chalkduster
2012-04-02 11:36:35.486 MyApp[3579:707] Family name: Georgia
2012-04-02 11:36:35.490 MyApp[3579:707]     Font name: Georgia-Italic
2012-04-02 11:36:35.493 MyApp[3579:707]     Font name: Georgia-BoldItalic
2012-04-02 11:36:35.497 MyApp[3579:707]     Font name: Georgia-Bold
2012-04-02 11:36:35.501 MyApp[3579:707]     Font name: Georgia
2012-04-02 11:36:35.504 MyApp[3579:707] Family name: Helvetica Neue
2012-04-02 11:36:35.508 MyApp[3579:707]     Font name: HelveticaNeue-Bold
2012-04-02 11:36:35.511 MyApp[3579:707]     Font name: HelveticaNeue-CondensedBlack
2012-04-02 11:36:35.515 MyApp[3579:707]     Font name: HelveticaNeue-Medium
2012-04-02 11:36:35.518 MyApp[3579:707]     Font name: HelveticaNeue
2012-04-02 11:36:35.522 MyApp[3579:707]     Font name: HelveticaNeue-Light
2012-04-02 11:36:35.526 MyApp[3579:707]     Font name: HelveticaNeue-CondensedBold
2012-04-02 11:36:35.529 MyApp[3579:707]     Font name: HelveticaNeue-LightItalic
2012-04-02 11:36:35.532 MyApp[3579:707]     Font name: HelveticaNeue-UltraLightItalic
2012-04-02 11:36:35.536 MyApp[3579:707]     Font name: HelveticaNeue-UltraLight
2012-04-02 11:36:35.540 MyApp[3579:707]     Font name: HelveticaNeue-BoldItalic
2012-04-02 11:36:35.543 MyApp[3579:707]     Font name: HelveticaNeue-Italic
2012-04-02 11:36:35.547 MyApp[3579:707] Family name: Gill Sans
2012-04-02 11:36:35.551 MyApp[3579:707]     Font name: GillSans-LightItalic
2012-04-02 11:36:35.555 MyApp[3579:707]     Font name: GillSans-BoldItalic
2012-04-02 11:36:35.558 MyApp[3579:707]     Font name: GillSans-Italic
2012-04-02 11:36:35.562 MyApp[3579:707]     Font name: GillSans
2012-04-02 11:36:35.565 MyApp[3579:707]     Font name: GillSans-Bold
2012-04-02 11:36:35.569 MyApp[3579:707]     Font name: GillSans-Light
2012-04-02 11:36:35.572 MyApp[3579:707] Family name: Palatino
2012-04-02 11:36:35.576 MyApp[3579:707]     Font name: Palatino-Roman
2012-04-02 11:36:35.580 MyApp[3579:707]     Font name: Palatino-Bold
2012-04-02 11:36:35.583 MyApp[3579:707]     Font name: Palatino-BoldItalic
2012-04-02 11:36:35.587 MyApp[3579:707]     Font name: Palatino-Italic
2012-04-02 11:36:35.591 MyApp[3579:707] Family name: Courier New
2012-04-02 11:36:35.594 MyApp[3579:707]     Font name: CourierNewPSMT
2012-04-02 11:36:35.598 MyApp[3579:707]     Font name: CourierNewPS-BoldMT
2012-04-02 11:36:35.601 MyApp[3579:707]     Font name: CourierNewPS-BoldItalicMT
2012-04-02 11:36:35.605 MyApp[3579:707]     Font name: CourierNewPS-ItalicMT
2012-04-02 11:36:35.608 MyApp[3579:707] Family name: Oriya Sangam MN
2012-04-02 11:36:35.612 MyApp[3579:707]     Font name: OriyaSangamMN-Bold
2012-04-02 11:36:35.616 MyApp[3579:707]     Font name: OriyaSangamMN
2012-04-02 11:36:35.619 MyApp[3579:707] Family name: Didot
2012-04-02 11:36:35.623 MyApp[3579:707]     Font name: Didot-Italic
2012-04-02 11:36:35.627 MyApp[3579:707]     Font name: Didot
2012-04-02 11:36:35.630 MyApp[3579:707]     Font name: Didot-Bold
2012-04-02 11:36:35.634 MyApp[3579:707] Family name: Bodoni 72 Smallcaps
2012-04-02 11:36:35.638 MyApp[3579:707]     Font name: BodoniSvtyTwoSCITCTT-Book

How to open .dll files to see what is written inside?

You cannot get the exact code, but you can get a decompiled version of it.

The most popular (and best) tool is Reflector, but there are also other .Net decompilers (such as Dis#).

You can also decompile the IL using ILDASM, which comes bundled with the .Net Framework SDK Tools.

How to verify if nginx is running or not?

This is probably system-dependent, but this is the simplest way I've found.

if [ -e /var/run/nginx.pid ]; then echo "nginx is running"; fi

That's the best solution for scripting.

Convert Char to String in C

I use this to convert char to string (an example) :

char c = 'A';
char str1[2] = {c , '\0'};
char str2[5] = "";
strcpy(str2,str1);

How to watch and compile all TypeScript sources?

Create a file named tsconfig.json in your project root and include following lines in it:

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "module": "commonjs",
        "target": "ES5",
        "outDir": "ts-built",
        "rootDir": "src"
    }
}

Please note that outDir should be the path of the directory to receive compiled JS files, and rootDir should be the path of the directory containing your source (.ts) files.

Open a terminal and run tsc -w, it'll compile any .ts file in src directory into .js and store them in ts-built directory.

Efficient way to return a std::vector in c++

vector<string> getseq(char * db_file)

And if you want to print it on main() you should do it in a loop.

int main() {
     vector<string> str_vec = getseq(argv[1]);
     for(vector<string>::iterator it = str_vec.begin(); it != str_vec.end(); it++) {
         cout << *it << endl;
     }
}

Tests not running in Test Explorer

For me solution was to change the Resharper Unit Testing settings "Default platform architecture" to "x64"

enter image description here

bash: mkvirtualenv: command not found

Since I just went though a drag, I'll try to write the answer I'd have wished for two hours ago. This is for people who don't just want the copy&paste solution

First: Do you wonder why copying and pasting paths works for some people while it doesn't work for others?** The main reason, solutions differ are different python versions, 2.x or 3.x. There are actually distinct versions of virtualenv and virtualenvwrapper that work with either python 2 or 3. If you are on python 2 install like so:

sudo pip install virutalenv
sudo pip install virtualenvwrapper

If you are planning to use python 3 install the related python 3 versions

sudo pip3 install virtualenv
sudo pip3 install virtualenvwrapper

You've successfully installed the packages for your python version and are all set, right? Well, try it. Type workon into your terminal. Your terminal will not be able to find the command (workon is a command of virtualenvwrapper). Of course it won't. Workon is an executable that will only be available to you once you load/source the file virtualenvwrapper.sh. But the official installation guide has you covered on this one, right?. Just open your .bash_profile and insert the following, it says in the documentation:

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

Especially the command source /usr/local/bin/virtualenvwrapper.sh seems helpful since the command seems to load/source the desired file virtualenvwrapper.sh that contains all the commands you want to work with like workon and mkvirtualenv. But yeah, no. When following the official installation guide, you are very likely to receive the error from the initial post: mkvirtualenv: command not found. Still no command is being found and you are still frustrated. So whats the problem here? The problem is that virtualenvwrapper.sh is not were you are looking for it right now. Short reminder ... you are looking here:

source /usr/local/bin/virtualenvwrapper.sh

But there is a pretty straight forward way to finding the desired file. Just type

which virtualenvwrapper

to your terminal. This will search your PATH for the file, since it is very likely to be in some folder that is included in the PATH of your system.

If your system is very exotic, the desired file will hide outside of a PATH folder. In that case you can find the path to virtalenvwrapper.sh with the shell command find / -name virtualenvwrapper.sh

Your result may look something like this: /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh Congratulations. You have found your missing file!. Now all you have to do is changing one command in your .bash_profile. Just change:

source "/usr/local/bin/virtualenvwrapper.sh"

to:

"/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh"

Congratulations. Virtualenvwrapper does now work on your system. But you can do one more thing to enhance your solution. If you've found the file virtualenvwrapper.sh with the command which virtualenvwrapper.sh you know that it is inside of a folder of the PATH. So if you just write the filename, your file system will assume the file is inside of a PATH folder. So you you don't have to write out the full path. Just type:

source "virtualenvwrapper.sh"

Thats it. You are no longer frustrated. You have solved your problem. Hopefully.

Java: Date from unix timestamp

Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());

Parsing huge logfiles in Node.js - read in line-by-line

I have made a node module to read large file asynchronously text or JSON. Tested on large files.

var fs = require('fs')
, util = require('util')
, stream = require('stream')
, es = require('event-stream');

module.exports = FileReader;

function FileReader(){

}

FileReader.prototype.read = function(pathToFile, callback){
    var returnTxt = '';
    var s = fs.createReadStream(pathToFile)
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        //console.log('reading line: '+line);
        returnTxt += line;        

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(){
        console.log('Error while reading file.');
    })
    .on('end', function(){
        console.log('Read entire file.');
        callback(returnTxt);
    })
);
};

FileReader.prototype.readJSON = function(pathToFile, callback){
    try{
        this.read(pathToFile, function(txt){callback(JSON.parse(txt));});
    }
    catch(err){
        throw new Error('json file is not valid! '+err.stack);
    }
};

Just save the file as file-reader.js, and use it like this:

var FileReader = require('./file-reader');
var fileReader = new FileReader();
fileReader.readJSON(__dirname + '/largeFile.json', function(jsonObj){/*callback logic here*/});

ImportError: No module named model_selection

I encountered this problem when I import GridSearchCV.

Just changed sklearn.model_selection to sklearn.grid_search.

How to specify test directory for mocha?

If in node.js, some new configurations as of Mocha v6:

Option 1: Create .mocharc.json in project's root directory:

{
  "spec": "path/to/test/files"
}

Option 2: add mocha property in project's package.json:

{
  ...

  "mocha": {
    "spec": "path/to/test/files"
  }
}

More options are here.

How to create a JavaScript callback for knowing when an image is loaded?

You can use the .complete property of the Javascript image class.

I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:

var gAllImages = [];

function makeThumbDivs(thumbnailsBegin, thumbnailsEnd)
{
    gAllImages = [];

    for (var i = thumbnailsBegin; i < thumbnailsEnd; i++) 
    {
        var theImage = new Image();
        theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]);
        gAllImages.push(theImage);

        setTimeout('checkForAllImagesLoaded()', 5);
        window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd;

        // make a new div containing that image
        makeASingleThumbDiv(globals.gAllPageGUIDs[i]);
    }
}

function checkForAllImagesLoaded()
{
    for (var i = 0; i < gAllImages.length; i++) {
        if (!gAllImages[i].complete) {
            var percentage = i * 100.0 / (gAllImages.length);
            percentage = percentage.toFixed(0).toString() + ' %';

            userMessagesController.setMessage("loading... " + percentage);
            setTimeout('checkForAllImagesLoaded()', 20);
            return;
        }
    }

    userMessagesController.setMessage(globals.defaultTitle);
}

How to place a JButton at a desired location in a JFrame using Java

I have figured it out lol. for the button do .setBounds(0, 0, 220, 30) The .setBounds layout is like this (int x, int y, int width, int height)

Multi-key dictionary in c#?

I wrote and have used this with success.

public class MultiKeyDictionary<K1, K2, V> : Dictionary<K1, Dictionary<K2, V>>  {

    public V this[K1 key1, K2 key2] {
        get {
            if (!ContainsKey(key1) || !this[key1].ContainsKey(key2))
                throw new ArgumentOutOfRangeException();
            return base[key1][key2];
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new Dictionary<K2, V>();
            this[key1][key2] = value;
        }
    }

    public void Add(K1 key1, K2 key2, V value) {
            if (!ContainsKey(key1))
                this[key1] = new Dictionary<K2, V>();
            this[key1][key2] = value;
    }

    public bool ContainsKey(K1 key1, K2 key2) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2);
    }

    public new IEnumerable<V> Values {
        get {
            return from baseDict in base.Values
                   from baseKey in baseDict.Keys
                   select baseDict[baseKey];
        }
    } 

}


public class MultiKeyDictionary<K1, K2, K3, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, V>> {
    public V this[K1 key1, K2 key2, K3 key3] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, V>();
            this[key1][key2, key3] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, V>();
            this[key1][key2, key3, key4] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, V>();
            this[key1][key2, key3, key4, key5] = value;
        }
    }

    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, V>();
            this[key1][key2, key3, key4, key5, key6] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, V>();
            this[key1][key2, key3, key4, key5, key6, key7] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9, key10);
    }
}

public class MultiKeyDictionary<K1, K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V> : Dictionary<K1, MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V>> {
    public V this[K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10, K11 key11] {
        get {
            return ContainsKey(key1) ? this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10, key11] : default(V);
        }
        set {
            if (!ContainsKey(key1))
                this[key1] = new MultiKeyDictionary<K2, K3, K4, K5, K6, K7, K8, K9, K10, K11, V>();
            this[key1][key2, key3, key4, key5, key6, key7, key8, key9, key10, key11] = value;
        }
    }
    public bool ContainsKey(K1 key1, K2 key2, K3 key3, K4 key4, K5 key5, K6 key6, K7 key7, K8 key8, K9 key9, K10 key10, K11 key11) {
        return base.ContainsKey(key1) && this[key1].ContainsKey(key2, key3, key4, key5, key6, key7, key8, key9, key10, key11);
    }
}

Label word wrapping

If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:

  1. Put the label inside a panel
  2. Handle the ClientSizeChanged event for the panel, making the label fill the space:

    private void Panel2_ClientSizeChanged(object sender, EventArgs e)
    {
        label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
    }
    
  3. Set Auto-Size for the label to true

  4. Set Dock for the label to Fill

Convert a space delimited string to list

states.split() will return

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

If you need one random from them, then you have to use the random module:

import random

states = "... ..."

random_state = random.choice(states.split())

Bootstrap 3 Align Text To Bottom of Div

The easiest way I have tested just add a <br> as in the following:

<div class="col-sm-6">
    <br><h3><p class="text-center">Some Text</p></h3>
</div>

The only problem is that a extra line break (generated by that <br>) is generated when the screen gets smaller and it stacks. But it is quick and simple.

How can I post an array of string to ASP.NET MVC Controller without a form?

In .NET4.5, MVC 5

Javascript:

object in JS: enter image description here

mechanism that does post.

    $('.button-green-large').click(function() {
        $.ajax({
            url: 'Quote',
            type: "POST",
            dataType: "json",
            data: JSON.stringify(document.selectedProduct),
            contentType: 'application/json; charset=utf-8',
        });
    });

C#

Objects:

public class WillsQuoteViewModel
{
    public string Product { get; set; }

    public List<ClaimedFee> ClaimedFees { get; set; }
}

public partial class ClaimedFee //Generated by EF6
{
    public long Id { get; set; }
    public long JourneyId { get; set; }
    public string Title { get; set; }
    public decimal Net { get; set; }
    public decimal Vat { get; set; }
    public string Type { get; set; }

    public virtual Journey Journey { get; set; }
}

Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}

Object received:

enter image description here

Hope this saves you some time.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers

ReportViewer Client Print Control "Unable to load client print control"?

In my case when I get this message IE suggest me to install add-on from Microsoft. After install problem solved.

My software:
IE9 but work also on older
SQL SERVER 2008 R2

Does PHP have threading?

There is the rather obscure, and soon to be deprecated, feature called ticks. The only thing I have ever used it for, is to allow a script to capture SIGKILL (Ctrl+C) and close down gracefully.

Get keys from HashMap in Java

Check this.

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

(Use java.util.Objects.equals because HashMap can contain null)

Using JDK8+

/**
 * Find any key matching a value.
 *
 * @param value The value to be matched. Can be null.
 * @return Any key matching the value in the team.
 */
private Optional<String> findKey(Integer value){
    return team1
        .entrySet()
        .stream()
        .filter(e -> Objects.equals(e.getValue(), value))
        .map(Map.Entry::getKey)
        .findAny();
}

/**
 * Find all keys matching a value.
 *
 * @param value The value to be matched. Can be null.
 * @return all keys matching the value in the team.
 */
private List<String> findKeys(Integer value){
    return team1
        .entrySet()
        .stream()
        .filter(e -> Objects.equals(e.getValue(), value))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
}

More "generic" and as safe as possible

/**
 * Find any key matching the value, in the given map.
 *
 * @param mapOrNull Any map, null is considered a valid value.
 * @param value     The value to be searched.
 * @param <K>       Type of the key.
 * @param <T>       Type of the value.
 * @return An optional containing a key, if found.
 */
public static <K, T> Optional<K> findKey(Map<K, T> mapOrNull, T value) {
    return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()
            .stream()
            .filter(e -> Objects.equals(e.getValue(), value))
            .map(Map.Entry::getKey)
            .findAny());
}

Or if you are on JDK7.

private String findKey(Integer value){
    for(String key : team1.keySet()){
        if(Objects.equals(team1.get(key), value)){
            return key; //return the first found
        }
    }
    return null;
}

private List<String> findKeys(Integer value){
   List<String> keys = new ArrayList<String>();
   for(String key : team1.keySet()){
        if(Objects.equals(team1.get(key), value)){
             keys.add(key);
      }
   }
   return keys;
}

Registry key Error: Java version has value '1.8', but '1.7' is required

You have to define your jdk folder in variable JAVA_HOME, add %JAVA_HOME% to your variable path

Delete or change name of your java.exe, javaw.exe and javaws in your folder system32

execute cmd.exe, java -version now take the new version that you define in JAVA_HOME.

How to change screen resolution of Raspberry Pi

If you are like me using a TFT that is connected via SPI (e. g. PiTFT 2.8" 320x240) driven by FBTFT in combination with fbcp to utilise hardware accelerated video decoding (using omxplayer) like it is descriped here. You should add the following into the /boot/config.txt to force the output to HDMI and set the resolution to 320x240:

hdmi_force_hotplug=1
hdmi_cvt=320 240 60 1 0 0 0
hdmi_group=2
hdmi_mode=87

Assigning default value while creating migration file

t.integer :retweets_count, :default => 0

... should work.

See the Rails guide on migrations

Measuring code execution time

Example for how one might use the Stopwatch class in VB.NET.

Dim Stopwatch As New Stopwatch

Stopwatch.Start()
            ''// Test Code
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)

Stopwatch.Restart()            
           ''// Test Again

Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)

Updating the list view when the adapter data changes

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this, 
                           android.R.layout.simple_list_item_1, 
                           listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_1, 
                                   listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

What version of javac built my jar?

I as well wrote my own bash script to dump the Java version required by all the jars passed at the command line... Mine is a bit rough, but works for me ;-)

example usage

$ jar_dump_version_of_jvm_required.sh *.jar
JVM VERSION REQUIRED: 46.0, /private/tmp/jars/WEB-INF/lib/json-simple-1.1.jar
JVM VERSION REQUIRED: 49.0, /private/tmp/jars/WEB-INF/lib/json-smart-1.1.1.jar
JVM VERSION REQUIRED: 50.0, /private/tmp/jars/WEB-INF/lib/jsontoken-1.0.jar
JVM VERSION REQUIRED: 50.0, /private/tmp/jars/WEB-INF/lib/jsr166y-1.7.0.jar

jar_dump_version_of_jvm_required.sh

#!/bin/bash

DIR=$(PWD)
function show_help()
{
  ME=$(basename $0)
  IT=$(cat <<EOF

  Dumps the version of the JVM required to run the classes in a jar file

  usage: $ME JAR_FILE

  e.g. 

  $ME myFile.jar    ->  VERSION: 50.0     myFile.jar

  Java versions are:
  54 = Java 10
  53 = Java 9
  52 = Java 8
  51 = Java 7
  50 = Java 6
  49 = Java 5
  48 = Java 1.4
  47 = Java 1.3
  46 = Java 1.2
  45.3 = Java 1.1

EOF
  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

function unzipJarToTmp()
{
  JAR=$1
  CLASS_FILE=$(jar -tf "$JAR" | grep \.class$ | grep -v '\$' | head -n1 | awk '{print $NF}')
  OUT_FILE="$CLASS_FILE"
  #echo "J=$JAR C=$CLASS_FILE O=$OUT_FILE"
  jar xf "$JAR" "$CLASS_FILE"

  MAJOR=$(javap -v "$OUT_FILE" 2>&1 | grep major | awk -F' ' '{print $3'})
  MINOR=$(javap -v "$OUT_FILE" 2>&1 | grep minor | awk -F' ' '{print $3'})
  if [ -z "$MAJOR" ]
  then
    echo "JVM VERSION REQUIRED: NA as no classes in $JAR"
  else
    echo "JVM VERSION REQUIRED: $MAJOR.$MINOR, $JAR"
  fi
}

# loop over cmd line args
for JAR in "$@"
do
  cd "$DIR"
  JAR_UID=$(basename "$JAR" | sed s/.jar//g)
  TMPDIR=/tmp/jar_dump/$JAR_UID/
  mkdir -p "$TMPDIR"
  JAR_ABS_PATH=$(realpath $JAR)

  cd "$TMPDIR"

  #echo "$JAR_ABS_PATH"
  unzipJarToTmp "$JAR_ABS_PATH"
  #sleep 2
done

PHP: Inserting Values from the Form into MySQL

<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");

?>



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
 //$("form").submit(function(e){

     $("#btn1").click(function(e){
     e.preventDefault();
    // alert('here');
        $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');

    });
    //}
});
</script>

</head>

<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file"  name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>

<tr><td>Address:</td><td><textarea  cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input  type="number"  maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio"  name="r1" value="Male" checked="checked"/>Male<input type="radio"  name="r1" value="feale"/>Female</td></tr>
<tr><td><input  id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){


move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);

                     $fname = $_FILES['e5']['name'][$key];
                     $imgarryimp[]=$fname;
                     //echo $fname;

                     if(strlen($fname)>0)
                      {
                         $img = $fname;
                      }
                      $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
}
exit;





                      // echo $values;exit;
                      //foreach($_POST['e1'] as $row) 
    //{ 

    $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
    //}
    //exit;


}
?>

</form>

<table>
<?php 
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>

</body>
</html>

How to detect scroll direction

I managed to figure it out in the end, so if anyone is looking for the answer:

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.originalEvent.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.originalEvent.wheelDelta < 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Android: Create a toggle button with image and no text

create toggle_selector.xml in res/drawable

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
  <item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>

apply the selector to your toggle button

<ToggleButton
            android:id="@+id/chkState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOff=""
            android:textOn=""/>

Note: for removing the text i used following in above code

textOff=""
textOn=""

How do I put a clear button inside my HTML text input box like the iPhone does?

Of course the best approach is to use the ever-more-supported <input type="search" />.

Anyway for a bit of coding fun I thought that it could be achieved also using the form's reset button, and this is the working result (it is worth noting that you cannot have other inputs in the form but the search field with this approach, or the reset button will erase them too), no javascript needed:

_x000D_
_x000D_
form{
    position: relative;
    width: 200px;
}

form input {
    width: 100%;
    padding-right: 20px;
    box-sizing: border-box;
}

form input:placeholder-shown + button{
  opacity: 0;
  pointer-events: none;
} 

form button {
    position: absolute;
    border: none;
    display: block;
    width: 15px;
    height: 15px;
    line-height: 16px;
    font-size: 12px;
    border-radius: 50%;
    top: 0;
    bottom: 0;
    right: 5px;
    margin: auto;
    background: #ddd;
    padding: 0;
    outline: none;
    cursor: pointer;
    transition: .1s;
}
_x000D_
<form>
        <input type="text" placeholder=" " />
        <button type="reset">&times;</button>
</form>
_x000D_
_x000D_
_x000D_

stringstream, string, and char* conversion confusion

stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.

You could copy that temporary string object to some other string object and take the C string from that one:

const std::string tmp = stringstream.str();
const char* cstr = tmp.c_str();

Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression:

use_c_str( stringstream.str().c_str() );

Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference:

{
  const std::string& tmp = stringstream.str();   
  const char* cstr = tmp.c_str();
}

IMO that's the best solution. Unfortunately it's not very well known.

How to check if pytorch is using the GPU?

From practical standpoint just one minor digression:

import torch
dev = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

This dev now knows if cuda or cpu.

And there is a difference how you deal with model and with tensors when moving to cuda. It is a bit strange at first.

import torch
import torch.nn as nn
dev = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
t1 = torch.randn(1,2)
t2 = torch.randn(1,2).to(dev)
print(t1)  # tensor([[-0.2678,  1.9252]])
print(t2)  # tensor([[ 0.5117, -3.6247]], device='cuda:0')
t1.to(dev) 
print(t1)  # tensor([[-0.2678,  1.9252]]) 
print(t1.is_cuda) # False
t1 = t1.to(dev)
print(t1)  # tensor([[-0.2678,  1.9252]], device='cuda:0') 
print(t1.is_cuda) # True

class M(nn.Module):
    def __init__(self):        
        super().__init__()        
        self.l1 = nn.Linear(1,2)

    def forward(self, x):                      
        x = self.l1(x)
        return x
model = M()   # not on cuda
model.to(dev) # is on cuda (all parameters)
print(next(model.parameters()).is_cuda) # True

This all is tricky and understanding it once, helps you to deal fast with less debugging.

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

Check Whether a User Exists

Create system user some_user if it doesn't exist

if [[ $(getent passwd some_user) = "" ]]; then
    sudo adduser --no-create-home --force-badname --disabled-login --disabled-password --system some_user
fi

How do I remove the passphrase for the SSH key without having to create a new key?

You might want to add the following to your .bash_profile (or equivalent), which starts ssh-agent on login.

if [ -f ~/.agent.env ] ; then
    . ~/.agent.env > /dev/null
    if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then
        echo "Stale agent file found. Spawning new agent… "
        eval `ssh-agent | tee ~/.agent.env`
        ssh-add
    fi 
else
    echo "Starting ssh-agent"
    eval `ssh-agent | tee ~/.agent.env`
    ssh-add
fi

On some Linux distros (Ubuntu, Debian) you can use:

ssh-copy-id -i ~/.ssh/id_dsa.pub username@host

This will copy the generated id to a remote machine and add it to the remote keychain.

You can read more here and here.

Fragment Inside Fragment

Hi I solved this problem by putting per Fragment into distinct layout.And I made just related Layout visible and made the others visibilities gone.

I mean:

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

     <LinearLayout android:id="@+id/linearLayout1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:orientation="horizontal">
           <Button android:layout_width="wrap_content"
                   android:id="@+id/button1"
                   android:layout_height="wrap_content"
                   android:text="Button1"></Button>
           <Button android:text="Button2"
                   android:id="@+id/button2"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"></Button>
           <Button android:text="Button3"
                   android:id="@+id/button3"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"></Button>
           <Button android:text="Button4"
                   android:id="@+id/button4"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"></Button>
   </LinearLayout>
   <LinearLayout android:layout_width="full_screen"
              android:layout_height="0dp"
              android:layout_weight="1"
              android:id="action_For_Button1"
              android:visibility="visible">
                    <Fragment android:layout_width="full_screen"
                              android:layout_height="full_screen"
                              android:id="fragment1"
                                        .
                                        .
                                        .
             / >
     </LinearLayout>

     <LinearLayout android:layout_width="full_screen"
              android:layout_height="0dp"
              android:id="action_For_Button1"
              android:layout_weight="1"
              android:visibility="gone">
                       <Fragment android:layout_width="full_screen"
                                 android:layout_height="full_screen"
                                 android:id="fragment2"
                                           .
                                           .
                                           .
             / >
        </LinearLayout>
                     .
                     .
                     .
        </LinearLayout>

I assumed that you will open your page as button 1 is clicked.You can control your fragment's visibilities on click action.You can make related Layout visible and the others gone and by Fragment Manager you can take your fragment.This approach worked for me.And since view that has visibility:gone is invisible, and it doesn't take any space for layout purposes I think this approach does not cause any space problem.

P.S:I just tried to explain my solution code may have syntax mistakes or uncompleted structure.

Can't connect to local MySQL server through socket '/tmp/mysql.sock

For me the problem was I wasn't running MySQL Server. Run server first and then execute mysql.

$ mysql.server start
$ mysql -h localhost -u root -p

gdb: "No symbol table is loaded"

First of all, what you have is a fully compiled program, not an object file, so drop the .o extension. Now, pay attention to what the error message says, it tells you exactly how to fix your problem: "No symbol table is loaded. Use the "file" command."

(gdb) exec-file test
(gdb) b 2
No symbol table is loaded.  Use the "file" command.
(gdb) file test
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Or just pass the program on the command line.

$ gdb test
GNU gdb (GDB) 7.4
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
Reading symbols from /home/user/test/test...done.
(gdb) b 2
Breakpoint 1 at 0x80483ea: file test.c, line 2.
(gdb) 

Finalize vs Dispose

The finalizer is for implicit cleanup - you should use this whenever a class manages resources that absolutely must be cleaned up as otherwise you would leak handles / memory etc...

Correctly implementing a finalizer is notoriously difficult and should be avoided wherever possible - the SafeHandle class (avaialble in .Net v2.0 and above) now means that you very rarely (if ever) need to implement a finalizer any more.

The IDisposable interface is for explicit cleanup and is much more commonly used - you should use this to allow users to explicitly release or cleanup resources whenever they have finished using an object.

Note that if you have a finalizer then you should also implement the IDisposable interface to allow users to explicitly release those resources sooner than they would be if the object was garbage collected.

See DG Update: Dispose, Finalization, and Resource Management for what I consider to be the best and most complete set of recommendations on finalizers and IDisposable.

Formatting numbers (decimal places, thousands separators, etc) with CSS

Another solution with pure CSS+HTML and the pseudo-class :lang().

Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:

<html lang="es">
  Spanish: 1<span class="thousands-separator">200</span><span class="thousands-separator">000</span><span class="decimal-separator">.</span>50
</html>

Use the lang pseudo-class to format the number.

/* Spanish */
.thousands-separator:lang(es):before{
  content: ".";
}
.decimal-separator:lang(es){
  visibility: hidden;
  position: relative;
}
.decimal-separator:lang(es):before{
  position: absolute;
  visibility: visible;
  content: ",";
}

/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
  content: ",";
}

Codepen: https://codepen.io/danielblazquez/pen/qBqVjGy

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

How do I count occurrence of duplicate items in array

$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

How to make a select with array contains value clause in psql

Note that this may also work:

SELECT * FROM table WHERE s=ANY(array)

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

How to change current working directory using a batch file

A simpler syntax might be

pushd %root%

Convert Json String to C# Object List

using dynamic variable in C# is the simplest.

Newtonsoft.Json.Linq has class JValue that can be used. Below is a sample code which displays Question id and text from the JSON string you have.

        string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"TypeId\":1,\"TypeName\":\"MCQ\",\"Model\":{\"options\":[{\"text\":\"Rahul\",\"selectedMarks\":\"0\"},{\"text\":\"Pratik\",\"selectedMarks\":\"9\"},{\"text\":\"Rohit\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":true,\"selectedOption\":\"1\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"02\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"\",\"S8\":\"\",\"S9\":\"Pratik\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"TypeId\":3,\"TypeName\":\"True-False\",\"Model\":{\"options\":[{\"text\":\"True\",\"selectedMarks\":\"7\"},{\"text\":\"False\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":false,\"selectedOption\":\"3\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"01\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"True\",\"S8\":\"\",\"S9\":\"\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"}]";
        dynamic myObject = JValue.Parse(jsonString);
        foreach (dynamic questions in myObject)
        {
            Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
        }
        Console.Read();

Output from the code => Output from the code

How to get the value of an input field using ReactJS?

There are three answers here, depending on the version of React you're (forced to) work(ing) with, and whether you want to use hooks.

First things first:

It's important to understand how React works, so you can do things properly (protip: it's is super worth running through the React tutorial exercise on the React website. It's well written, and covers all the basics in a way that actually explains how to do things). "Properly" here means that you're writing an application interface that happens to be rendered in a browser; all the interface work happens in React, not in "what you're used to if you're writing a web page" (this is why React apps are "apps", not "web pages").

React applications are rendered based off of two things:

  1. the component's properties as declared by whichever parent creates an instance of that component, which the parent can modify throughout its lifecycle, and
  2. the component's own internal state, which it can modify itself throughout its own lifecycle.

What you're expressly not doing when you use React is generating HTML elements and then using those: when you tell React to use an <input>, for instance, you are not creating an HTML input element, you are telling React to create a React input object that happens to render as an HTML input element, and whose event handling looks at, but is not controlled by, the HTML element's input events.

When using React, what you're doing is generating application UI elements that present the user with (often manipulable) data, with user interaction changing the Component's state, which may cause a rerender of part of your application interface to reflect the new state. In this model, the state is always the final authority, not "whatever UI library is used to render it", which on the web is the browser's DOM. The DOM is almost an afterthought in this programming model: it's just the particular UI framework that React happens to be using.

So in the case of an input element, the logic is:

  1. You type in the input element,
  2. nothing happens to your input element yet, the event got intercepted by React and killed off immediately,
  3. React forwards the event to the function you've set up for event handling,
  4. that function may schedule a state update,
  5. if it does, React runs that state update (asynchronously!) and will trigger a render call after the update, but only if the state update changed the state.
  6. only after this render has taken place will the UI show that you "typed a letter".

All of that happens in a matter of milliseconds, if not less, so it looks like you typed into the input element in the same way you're used to from "just using an input element on a page", but that's absolutely not what happened.

So, with that said, on to how to get values from elements in React:

React 15 and below, with ES5

To do things properly, your component has a state value, which is shown via an input field, and we can update it by making that UI element send change events back into the component:

var Component = React.createClass({
  getInitialState: function() {
    return {
      inputValue: ''
    };
  },

  render: function() {
    return (
      //...
      <input value={this.state.inputValue} onChange={this.updateInputValue}/>
      //...
    );
  },

  updateInputValue: function(evt) {
    this.setState({
      inputValue: evt.target.value
    });
  }
});

So we tell React to use the updateInputValue function to handle the user interaction, use setState to schedule the state update, and the fact that render taps into this.state.inputValue means that when it rerenders after updating the state, the user will see the update text based on what they typed.

addendum based on comments

Given that UI inputs represent state values (consider what happens if a user closes their tab midway, and the tab is restored. Should all those values they filled in be restored? If so, that's state). That might make you feel like a large form needs tens or even a hundred input forms, but React is about modeling your UI in a maintainable way: you do not have 100 independent input fields, you have groups of related inputs, so you capture each group in a component and then build up your "master" form as a collection of groups.

MyForm:
  render:
    <PersonalData/>
    <AppPreferences/>
    <ThirdParty/>
     ...

This is also much easier to maintain than a giant single form component. Split up groups into Components with state maintenance, where each component is only responsible for tracking a few input fields at a time.

You may also feel like it's "a hassle" to write out all that code, but that's a false saving: developers-who-are-not-you, including future you, actually benefit greatly from seeing all those inputs hooked up explicitly, because it makes code paths much easier to trace. However, you can always optimize. For instance, you can write a state linker

MyComponent = React.createClass({
  getInitialState() {
    return {
      firstName: this.props.firstName || "",
      lastName: this.props.lastName || "" 
      ...: ...
      ...
    }
  },
  componentWillMount() {
    Object.keys(this.state).forEach(n => {
      let fn = n + 'Changed';
      this[fn] = evt => {
        let update = {};
        update[n] = evt.target.value;
        this.setState(update);
      });
    });
  },
  render: function() {
    return Object.keys(this.state).map(n => {
      <input
        key={n} 
        type="text"
        value={this.state[n]}
        onChange={this[n + 'Changed']}/>
    });
  }
});

Of course, there are improved versions of this, so hit up https://npmjs.com and search for a React state linking solution that you like best. Open Source is mostly about finding what others have already done, and using that instead of writing everything yourself from scratch.

React 16 (and 15.5 transitional) and 'modern' JS

As of React 16 (and soft-starting with 15.5) the createClass call is no longer supported, and class syntax needs to be used. This changes two things: the obvious class syntax, but also the thiscontext binding that createClass can do "for free", so to ensure things still work make sure you're using "fat arrow" notation for this context preserving anonymous functions in onWhatever handlers, such as the onChange we use in the code here:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    };
  }

  render() {
    return (
      //...
      <input value={this.state.inputValue} onChange={evt => this.updateInputValue(evt)}/>
      //...
    );
  },

  updateInputValue(evt) {
    this.setState({
      inputValue: evt.target.value
    });
  }
});

You may also have seen people use bind in their constructor for all their event handling functions, like this:

constructor(props) {
  super(props);
  this.handler = this.handler.bind(this);
  ...
}

render() {
  return (
    ...
    <element onclick={this.handler}/>
    ...
  );
}

Don't do that.

Almost any time you're using bind, the proverbial "you're doing it wrong" applies. Your class already defines the object prototype, and so already defines the instance context. Don't put bind of top of that; use normal event forwarding instead of duplicating all your function calls in the constructor, because that duplication increases your bug surface, and makes it much harder to trace errors because the problem might be in your constructor instead of where you call your code. As well as placing a burden of maintenance on others that you (have or choose) to work with.

Yes, I know the react docs say it's fine. It's not, don't do it.

React 16.8, using function components with hooks

As of React 16.8 the function component (i.e. literally just a function that takes some props as argument can be used as if it's an instance of a component class, without ever writing a class) can also be given state, through the use of hooks.

If you don't need full class code, and a single instance function will do, then you can now use the useState hook to get yourself a single state variable, and its update function, which works roughly the same as the above examples, except without the setState function call:

import { useState } from 'react';

function myFunctionalComponentFunction() {
  const [input, setInput] = useState(''); // '' is the initial state value
  return (
    <div>
    <label>Please specify:</label>
    <input value={input} onInput={e => setInput(e.target.value)}/>
    </div>
  );
}

Previously the unofficial distinction between classes and function components was "function components don't have state", so we can't hide behind that one anymore: the difference between function components and classes components can be found spread over several pages in the very well-written react documentation (no shortcut one liner explanation to conveniently misinterpret for you!) which you should read so that you know what you're doing and can thus know whether you picked the best (whatever that means for you) solution to program yourself out of a problem you're having.

What is class="mb-0" in Bootstrap 4?

Bootstrap has predefined classes that we use for styling. If you are familiar with CSS, you'd know what padding, margin and spacing etc. are.

mb-0 = margin-bottom:0;

OK now moving a little further in knowledge, bootstrap has more classes for margin including:

mt- = margin-top
mb- = margin-bottom
ml- = margin-left
mr- = margin-right
my- = it sets margin-left and margin-right at the same time on y axes
mX- = it sets margin-bottom and margin-top at the same time on X axes

This and much more is explained here https://getbootstrap.com/docs/5.0/utilities/spacing/ The best way to learn is through https://getbootstrap.com site itself. It explains a lot obout its built in classes.

jquery get height of iframe content when loaded

The less complicated answer is to use .contents() to get at the iframe. Interestingly, though, it returns a different value from what I get using the code in my original answer, due to the padding on the body, I believe.

$('iframe').contents().height() + 'is the height'

This is how I've done it for cross-domain communication, so I'm afraid it's maybe unnecessarily complicated. First, I would put jQuery inside the iFrame's document; this will consume more memory, but it shouldn't increase load time as the script only needs to be loaded once.

Use the iFrame's jQuery to measure the height of your iframe's body as early as possible (onDOMReady) and then set the URL hash to that height. And in the parent document, add an onload event to the iFrame tag that will look at the location of the iframe and extract the value you need. Because onDOMReady will always occur before the document's load event, you can be fairly certain the value will get communicated correctly without a race condition complicating things.

In other words:

...in Help.php:

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552
    }
};
$(getDocumentHeight);

...and in the parent document:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );

Convert Unix timestamp into human readable date using MySQL

Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.

I have an automatically updated last_modified field, defined as:

`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC

SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`

In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.

Run this twice, first without setting the time_zone.

remove duplicates from sql union

If you are using T-SQL then it appears from previous posts that UNION removes duplicates. But if you are not, you could use distinct. This doesn't quite feel right to me either but it could get you the result you are looking for

SELECT DISTINCT *
FROM
(
select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4 
union
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4
)a

Query to get all rows from previous month

Even though the answer for this question has been selected already, however, I believe the simplest query will be

SELECT * 
FROM table 
WHERE 
date_created BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE();

Evenly space multiple views within a container view

Very easy way to solve this in InterfaceBuilder:

Set the centered label (label2) to "Horizontal Center in Container" and "Vertical Center in Container"

Select the centered label and the top label (label1 + label2) and add TWO constraints for Vertical Spacing. One with Greater Than or Equal the min spacing. One with Less Than or Equal the max spacing.

The same for the centered label and the bottom label (label2 + label3).

Additionally you could also add two constraints to label1 - Top Space To SuperView and two constraints to label2 - Bottom Space To SuperView.

The result will be that all 4 spacings will change their sizes equally.

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details.

List:

class List
{
    public:
        List(): head(nullptr), tail(nullptr) {}
    private:
        class Node
        {
              public:
                  int   data;
                  Node* next;
                  Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};

Here I don't want to expose Node as other people may decide to use the class and that would hinder me from updating my class as anything exposed is part of the public API and must be maintained forever. By making the class private, I not only hide the implementation I am also saying this is mine and I may change it at any time so you can not use it.

Look at std::list or std::map they all contain hidden classes (or do they?). The point is they may or may not, but because the implementation is private and hidden the builders of the STL were able to update the code without affecting how you used the code, or leaving a lot of old baggage laying around the STL because they need to maintain backwards compatibility with some fool who decided they wanted to use the Node class that was hidden inside list.

Project with path ':mypath' could not be found in root project 'myproject'

Remove all the texts in android/settings.gradle and paste the below code

rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'

This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned

Data structure for maintaining tabular data in memory?

Having a "table" in memory that needs lookups, sorting, and arbitrary aggregation really does call out for SQL. You said you tried SQLite, but did you realize that SQLite can use an in-memory-only database?

connection = sqlite3.connect(':memory:')

Then you can create/drop/query/update tables in memory with all the functionality of SQLite and no files left over when you're done. And as of Python 2.5, sqlite3 is in the standard library, so it's not really "overkill" IMO.

Here is a sample of how one might create and populate the database:

import csv
import sqlite3

db = sqlite3.connect(':memory:')

def init_db(cur):
    cur.execute('''CREATE TABLE foo (
        Row INTEGER,
        Name TEXT,
        Year INTEGER,
        Priority INTEGER)''')

def populate_db(cur, csv_fp):
    rdr = csv.reader(csv_fp)
    cur.executemany('''
        INSERT INTO foo (Row, Name, Year, Priority)
        VALUES (?,?,?,?)''', rdr)

cur = db.cursor()
init_db(cur)
populate_db(cur, open('my_csv_input_file.csv'))
db.commit()

If you'd really prefer not to use SQL, you should probably use a list of dictionaries:

lod = [ ] # "list of dicts"

def populate_lod(lod, csv_fp):
    rdr = csv.DictReader(csv_fp, ['Row', 'Name', 'Year', 'Priority'])
    lod.extend(rdr)

def query_lod(lod, filter=None, sort_keys=None):
    if filter is not None:
        lod = (r for r in lod if filter(r))
    if sort_keys is not None:
        lod = sorted(lod, key=lambda r:[r[k] for k in sort_keys])
    else:
        lod = list(lod)
    return lod

def lookup_lod(lod, **kw):
    for row in lod:
        for k,v in kw.iteritems():
            if row[k] != str(v): break
        else:
            return row
    return None

Testing then yields:

>>> lod = []
>>> populate_lod(lod, csv_fp)
>>> 
>>> pprint(lookup_lod(lod, Row=1))
{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'}
>>> pprint(lookup_lod(lod, Name='Aardvark'))
{'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'}
>>> pprint(query_lod(lod, sort_keys=('Priority', 'Year')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
 {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
 {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
 {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
 {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
 {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> pprint(query_lod(lod, sort_keys=('Year', 'Priority')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
 {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
 {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
 {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
 {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
 {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> print len(query_lod(lod, lambda r:1997 <= int(r['Year']) <= 2002))
6
>>> print len(query_lod(lod, lambda r:int(r['Year'])==1998 and int(r['Priority']) > 2))
0

Personally I like the SQLite version better since it preserves your types better (without extra conversion code in Python) and easily grows to accommodate future requirements. But then again, I'm quite comfortable with SQL, so YMMV.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

#!/usr/bin/python

# encoding=utf8

Try This to starting of python file

How do I bind to list of checkbox values with AngularJS?

<input type='checkbox' ng-repeat="fruit in fruits"
  ng-checked="checkedFruits.indexOf(fruit) != -1" ng-click="toggleCheck(fruit)">

.

function SomeCtrl ($scope) {
    $scope.fruits = ["apple, orange, pear, naartjie"];
    $scope.checkedFruits = [];
    $scope.toggleCheck = function (fruit) {
        if ($scope.checkedFruits.indexOf(fruit) === -1) {
            $scope.checkedFruits.push(fruit);
        } else {
            $scope.checkedFruits.splice($scope.checkedFruits.indexOf(fruit), 1);
        }
    };
}

How do you get the current text contents of a QComboBox?

PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:

import sip
sip.setapi('QString', 2)

With this API, QtCore.QString class is no longer available and self.ui.comboBox.currentText() will return a Python string or unicode object.

See Selecting Incompatible APIs from the doc.

SQL NVARCHAR and VARCHAR Limits

Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:

CREATE PROCEDURE ExecuteMyHugeQuery
    @SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
    -- Now, if the length is greater than some arbitrary value
    -- Let's say 2000 for this example
    -- Let's chunk it
    -- Let's also assume we won't allow anything larger than 8000 total
    DECLARE @len INT
    SELECT @len = LEN(@SQL)

    IF (@len > 8000)
    BEGIN
        RAISERROR ('The query cannot be larger than 8000 characters total.',
                   16,
                   1);
    END

    -- Let's declare our possible chunks
    DECLARE @Chunk1 VARCHAR(2000),
            @Chunk2 VARCHAR(2000),
            @Chunk3 VARCHAR(2000),
            @Chunk4 VARCHAR(2000)

    SELECT @Chunk1 = '',
           @Chunk2 = '',
           @Chunk3 = '',
           @Chunk4 = ''

    IF (@len > 2000)
    BEGIN
        -- Let's set the right chunks
        -- We already know we need two chunks so let's set the first
        SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)

        -- Let's see if we need three chunks
        IF (@len > 4000)
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)

            -- Let's see if we need four chunks
            IF (@len > 6000)
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
                SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
            END
              ELSE
            BEGIN
                SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
            END
        END
          ELSE
        BEGIN
            SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
        END
    END

    -- Alright, now that we've broken it down, let's execute it
    EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

I had the same issue, and spent quite a bit of time trying to track down the solution. I had Anonymous Authentication set up at two different levels with two different users. Make sure that you're not overwriting your set up at a lower level.

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

How can I make a Python script standalone executable to run without ANY dependency?

You may like py2exe. You'll also find information in there for doing it on Linux.

Add or change a value of JSON key with jquery or javascript

It seems if your key is saved in a variable. data.key = value won't work.

You should use data[key] = value

Example:

data = {key1:'v1', key2:'v2'};

var mykey = 'key1'; 
data.mykey = 'newv1';
data[mykey] = 'newV2';

console.log(data);

Result:

{
  "key1": "newV2",
  "key2": "v2",
  "mykey": "newv1"
}

Add a prefix string to beginning of each line

If your prefix is a bit complicated, just put it in a variable:

prefix=path/to/file/

Then, you pass that variable and let awk deal with it:

awk -v prefix="$prefix" '{print prefix $0}' input_file.txt

Turn off enclosing <p> tags in CKEditor 3.0

In VS2015, this worked to turn the Enter key into <br>

myCKEControl.EnterMode = CKEditor.NET.EnterMode.BR

Personally, I don't care if my resulting text only has <br> and not <p>. It renders perfectly fine and it looks the way I want it to. In the end, it works.

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

OWIN Security - How to Implement OAuth2 Refresh Tokens

I don't think that you should be using an array to maintain tokens. Neither you need a guid as a token.

You can easily use context.SerializeTicket().

See my below code.

public class RefreshTokenProvider : IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        Create(context);
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Receive(context);
    }

    public void Create(AuthenticationTokenCreateContext context)
    {
        object inputs;
        context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);

        var grantType = ((FormCollection)inputs)?.GetValues("grant_type");

        var grant = grantType.FirstOrDefault();

        if (grant == null || grant.Equals("refresh_token")) return;

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);

        context.SetToken(context.SerializeTicket());
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket == null)
        {
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "invalid token";
            return;
        }

        if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
        {
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "unauthorized";
            return;
        }

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
        context.SetTicket(context.Ticket);
    }
}

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Vue - Deep watching an array of objects and calculating the change?

This is what I use to deep watch an object. My requirement was watching the child fields of the object.

new Vue({
    el: "#myElement",
    data:{
        entity: {
            properties: []
        }
    },
    watch:{
        'entity.properties': {
            handler: function (after, before) {
                // Changes detected.    
            },
            deep: true
        }
    }
});

How to send a JSON object using html form data

I found a way to pass a JSON message using only a HTML form.

This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.

GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.

{ 
 allUsers 
  { 
  userId 
  }
}

I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.

<html>
<body>
    <form method="post" action="http://localhost:8080/graphql">
        <input type="text" name="operations" value="{&quot;query&quot;: &quot;{ allUsers { userId } }&quot;, "variables":  {}}"/>
        <input type="submit" />
    </form>
</body>
</html>

In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.

CentOS 7 and Puppet unable to install nc

You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:

root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}

#we capture release hash
$curr_os = $os['release']

case $curr_os['major'] {
  '7': { .... something }
  *: {something}
}

That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.

The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.

How to store phone numbers on MySQL databases?

I suggest storing the numbers in a varchar without formatting. Then you can just reformat the numbers on the client side appropriately. Some cultures prefer to have phone numbers written differently; in France, they write phone numbers like 01-22-33-44-55.

You might also consider storing another field for the country that the phone number is for, because this can be difficult to figure out based on the number you are looking at. The UK uses 11 digit long numbers, some African countries use 7 digit long numbers.

That said, I used to work for a UK phone company, and we stored phone numbers in our database based on if they were UK or international. So, a UK phone number would be 02081234123 and an international one would be 001800300300.

Using strtok with a std::string

  1. If boost is available on your system (I think it's standard on most Linux distros these days), it has a Tokenizer class you can use.

  2. If not, then a quick Google turns up a hand-rolled tokenizer for std::string that you can probably just copy and paste. It's very short.

  3. And, if you don't like either of those, then here's a split() function I wrote to make my life easier. It'll break a string into pieces using any of the chars in "delim" as separators. Pieces are appended to the "parts" vector:

    void split(const string& str, const string& delim, vector<string>& parts) {
      size_t start, end = 0;
      while (end < str.size()) {
        start = end;
        while (start < str.size() && (delim.find(str[start]) != string::npos)) {
          start++;  // skip initial whitespace
        }
        end = start;
        while (end < str.size() && (delim.find(str[end]) == string::npos)) {
          end++; // skip to end of word
        }
        if (end-start != 0) {  // just ignore zero-length strings.
          parts.push_back(string(str, start, end-start));
        }
      }
    }
    

remove objects from array by object property

Check this out using Set and ES6 filter.

  let result = arrayOfObjects.filter( el => (-1 == listToDelete.indexOf(el.id)) );
  console.log(result);

Here is JsFiddle: https://jsfiddle.net/jsq0a0p1/1/

Start an activity from a fragment

If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

  1. Go to services.msc from run prompt.
  2. Restart the services of SQL server(MSSQLSERVER)
  3. Restart the services of SQL server(SQLEXPRESS)

How to validate a form with multiple checkboxes to have atleast one checked

I checked all answers and even in other similar questions, I tried to find optimal way with help of html class and custom rule.

my html structure for multiple checkboxes are like this

_x000D_
_x000D_
$.validator.addMethod('multicheckbox_rule', function (value, element) {_x000D_
   var $parent = $(element).closest('.checkbox_wrapper');_x000D_
   if($parent.find('.checkbox_item').is(':checked')) return true;_x000D_
            return false;_x000D_
}, 'Please at least select one');
_x000D_
<div class="checkbox_wrapper">_x000D_
<label for="checkbox-1"><input class="checkbox_item" id="checkbox-1"  name="checkbox_item[1]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
<label for="checkbox-2"><input class="checkbox_item" id="checkbox-2" name="checkbox_item[2]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Bootstrap 3 Horizontal and Vertical Divider

The <hr> should be placed inside a <div> for proper functioning.

Place it like this to get desired width `

<div class='row'>
        <div class='col-lg-8 col-lg-offset-2'>
        <hr>
       </div>
       </div>

`

Hope this helps a future reader!

Get exit code for command in bash/ksh

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don't capture 'ERROR_CODE' so that is always zero (undefined).

It's good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh
command="/bin/date -u"          #...Example Only

safeRunCommand() {
   cmnd="$@"                    #...insure whitespace passed and preserved
   $cmnd
   ERROR_CODE=$?                #...so we have it for the command we want
   if [ ${ERROR_CODE} != 0 ]; then
      printf "Error when executing command: '${command}'\n"
      exit ${ERROR_CODE}        #...consider 'return()' here
   fi
}

safeRunCommand $command
command="cp"
safeRunCommand $command

How can I count the number of matches for a regex?

If you want to use Java 8 streams and are allergic to while loops, you could try this:

public static int countPattern(String references, Pattern referencePattern) {
    Matcher matcher = referencePattern.matcher(references);
    return Stream.iterate(0, i -> i + 1)
            .filter(i -> !matcher.find())
            .findFirst()
            .get();
}

Disclaimer: this only works for disjoint matches.

Example:

public static void main(String[] args) throws ParseException {
    Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
    System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
    System.out.println(countPattern("[  ]", referencePattern));
}

This prints out:

2
0
1
0

This is a solution for disjoint matches with streams:

public static int countPattern(String references, Pattern referencePattern) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            new Iterator<Integer>() {
                Matcher matcher = referencePattern.matcher(references);
                int from = 0;

                @Override
                public boolean hasNext() {
                    return matcher.find(from);
                }

                @Override
                public Integer next() {
                    from = matcher.start() + 1;
                    return 1;
                }
            },
            Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}

Parsing time string in Python

Here's a stdlib solution that supports a variable utc offset in the input time string:

>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)

Make Iframe to fit 100% of container's remaining height

It's right, you are showing an iframe with 100% height respect to its container: the body.

Try this:

<body>
  <div style="width:100%; height:30px; background-color:#cccccc;">Banner</div>
  <div style="width:100%; height:90%; background-color:transparent;">
    <iframe src="http: //www.google.com.tw" style="width:100%; height:100%;">
    </iframe> 
  </div>
</body>

Of course, change the height of the second div to the height you want.

css label width not taking effect

Make it a block first, then float left to stop pushing the next block in to a new line.

#report-upload-form label {
                           padding-left:26px;
                           width:125px;
                           text-transform: uppercase;
                           display:block;
                           float:left
}

Call fragment from fragment

In MainActivity

private static android.support.v4.app.FragmentManager fragmentManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);                     

    fragmentManager = getSupportFragmentManager();                                                                 


    }

public void secondFragment() {

    fragmentManager
            .beginTransaction()
            .setCustomAnimations(R.anim.right_enter, R.anim.left_out)
            .replace(R.id.frameContainer, new secondFragment(), "secondFragmentTag").addToBackStack(null)
            .commit();
}

In FirstFragment call SecondFrgment Like this:

new MainActivity().secondFragment();

How do I create a Java string from the contents of a file?

User java.nio.Files to read all lines of file.

public String readFile() throws IOException {
        File fileToRead = new File("file path");
        List<String> fileLines = Files.readAllLines(fileToRead.toPath());
        return StringUtils.join(fileLines, StringUtils.EMPTY);
}

iOS Detection of Screenshot?

Swift 4 Examples

Example #1 using closure

NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil, 
                                       queue: OperationQueue.main) { notification in
    print("\(notification) that a screenshot was taken!")
}

Example #2 with selector

NotificationCenter.default.addObserver(self, 
                                       selector: #selector(screenshotTaken), 
                                       name: .UIApplicationUserDidTakeScreenshot, 
                                       object: nil)

@objc func screenshotTaken() {
    print("Screenshot taken!")
}

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

Another loop-based solution that exits quickly when the number is low (in C++ for multiple types)

template<class T>
T reverse_bits(T in) {
    T bit = static_cast<T>(1) << (sizeof(T) * 8 - 1);
    T out;

    for (out = 0; bit && in; bit >>= 1, in >>= 1) {
        if (in & 1) {
            out |= bit;
        }
    }
    return out;
}

or in C for an unsigned int

unsigned int reverse_bits(unsigned int in) {
    unsigned int bit = 1u << (sizeof(T) * 8 - 1);
    unsigned int out;

    for (out = 0; bit && in; bit >>= 1, in >>= 1) {
        if (in & 1)
            out |= bit;
    }
    return out;
}

Mod in Java produces negative numbers

Since Java 8 you can use the Math.floorMod() method:

Math.floorMod(-1, 2); //== 1

Note: If the modulo-value (here 2) is negative, all output values will be negative too. :)

Source: https://stackoverflow.com/a/25830153/2311557

What is the best project structure for a Python application?

The "Python Packaging Authority" has a sampleproject:

https://github.com/pypa/sampleproject

It is a sample project that exists as an aid to the Python Packaging User Guide's Tutorial on Packaging and Distributing Projects.

Transparent scrollbar with css

Try this one, it works fine for me.

In CSS:

::-webkit-scrollbar
{
    width: 0px;
}
::-webkit-scrollbar-track-piece
{
    background-color: transparent;
    -webkit-border-radius: 6px;
}

and here is the working demo: https://jsfiddle.net/qpvnecz5/

When is it appropriate to use C# partial classes?

As an alternative to pre-compiler directives.

If you use pre-compiler directives (namely #IF DEBUG) then you end up with some gnarly looking code intermingled with your actual Release code.

You can create a seperate partial-class to contain this code, and either wrap the entire partial class in a directive, or omit that code-file from being sent to the compiler (effectively doing the same).

What's the best way to trim std::string?

why not use lambda?

auto no_space = [](char ch) -> bool {
  return !std::isspace<char>(ch, std::locale::classic());
};
auto ltrim = [](std::string& s) -> std::string& {
  s.erase(s.begin(), std::find_if(s.begin(), s.end(), no_space));
  return s;
};
auto rtrim = [](std::string& s) -> std::string& {
  s.erase(std::find_if(s.rbegin(), s.rend(), no_space).base(), s.end());
  return s;
};
auto trim_copy = [](std::string s) -> std::string& { return ltrim(rtrim(s)); };
auto trim = [](std::string& s) -> std::string& { return ltrim(rtrim(s)); };

Checking for empty queryset in Django

Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

if orgs.exists():
    # Do this...
else:
    # Do that...

But if you are going to evaluate QuerySet anyway it's better to use:

if orgs:
   ...

For more information read QuerySet.exists() documentation.

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

On Ubuntu, You can follow these steps to resolve the issue:

  1. Create a directory named plugins inside $HOME/.mozilla, if it doesn't exist already
  2. Create a symlink to libnpjp2.so inside this directory using this command:

    ln -s $JAVA_HOME/jre/lib/i386/libnpjp2.so $MOZILLA_HOME/plugins
    

    -or-

    ln -s $JAVA_HOME/jre/lib/amd64/libnpjp2.so $MOZILLA_HOME/plugins
    

    depending on whether you're using a 32 or 64 bit JVM installation. Moreover, $JAVA_HOME is the location of your JVM installation.

More detailed instructions can be found here.

Flutter- wrapping text

Using Ellipsis

Text(
  "This is a long text",
  overflow: TextOverflow.ellipsis,
),

enter image description here


Using Fade

Text(
  "This is a long text",
  overflow: TextOverflow.fade,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Using Clip

Text(
  "This is a long text",
  overflow: TextOverflow.clip,
  maxLines: 1,
  softWrap: false,
),

enter image description here


Note:

If you are using Text inside a Row, you can put above Text inside Expanded like:

Expanded(
  child: AboveText(),
)

T-SQL XOR Operator

MS SQL only short form (since SQL Server 2012):

1=iif( a=b ,1,0)^iif( c=d ,1,0)

Skip over a value in the range function in python

for i in range(0, 101):
if i != 50:
    do sth
else:
    pass

Request is not available in this context

This worked for me - if you have to log in Application_Start, do it before you modify the context. You will get a log entry, just with no source, like:

2019-03-12 09:35:43,659 INFO (null) - Application Started

I generally log both the Application_Start and Session_Start, so I see more detail in the next message

2019-03-12 09:35:45,064 INFO ~/Leads/Leads.aspx - Session Started (Local)

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Application Started");
            GlobalContext.Properties["page"] = new GetCurrentPage();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Globals._Environment = WebAppConfig.getEnvironment(Request.Url.AbsoluteUri, Properties.Settings.Default.LocalOverride);
            log.Info(string.Format("Session Started ({0})", Globals._Environment));
        }


JSON.net: how to deserialize without using the default constructor?

Json.Net prefers to use the default (parameterless) constructor on an object if there is one. If there are multiple constructors and you want Json.Net to use a non-default one, then you can add the [JsonConstructor] attribute to the constructor that you want Json.Net to call.

[JsonConstructor]
public Result(int? code, string format, Dictionary<string, string> details = null)
{
    ...
}

It is important that the constructor parameter names match the corresponding property names of the JSON object (ignoring case) for this to work correctly. You do not necessarily have to have a constructor parameter for every property of the object, however. For those JSON object properties that are not covered by the constructor parameters, Json.Net will try to use the public property accessors (or properties/fields marked with [JsonProperty]) to populate the object after constructing it.

If you do not want to add attributes to your class or don't otherwise control the source code for the class you are trying to deserialize, then another alternative is to create a custom JsonConverter to instantiate and populate your object. For example:

class ResultConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(Result));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the JSON for the Result into a JObject
        JObject jo = JObject.Load(reader);

        // Read the properties which will be used as constructor parameters
        int? code = (int?)jo["Code"];
        string format = (string)jo["Format"];

        // Construct the Result object using the non-default constructor
        Result result = new Result(code, format);

        // (If anything else needs to be populated on the result object, do that here)

        // Return the result
        return result;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then, add the converter to your serializer settings, and use the settings when you deserialize:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new ResultConverter());
Result result = JsonConvert.DeserializeObject<Result>(jsontext, settings);

How to increase memory limit for PHP over 2GB?

You can also try this:

ini_set("max_execution_time", "-1");
ini_set("memory_limit", "-1");
ignore_user_abort(true);
set_time_limit(0);

What is the right way to treat argparse.Namespace() as a dictionary?

Straight from the horse's mouth:

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— The Python Standard Library, 16.4.4.6. The Namespace object

Java 8 stream's .min() and .max(): why does this compile?

This works because Integer::min resolves to an implementation of the Comparator<Integer> interface.

The method reference of Integer::min resolves to Integer.min(int a, int b), resolved to IntBinaryOperator, and presumably autoboxing occurs somewhere making it a BinaryOperator<Integer>.

And the min() resp max() methods of the Stream<Integer> ask the Comparator<Integer> interface to be implemented.
Now this resolves to the single method Integer compareTo(Integer o1, Integer o2). Which is of type BinaryOperator<Integer>.

And thus the magic has happened as both methods are a BinaryOperator<Integer>.

How to delete a file after checking whether it exists

If you are reading from that file using FileStream and then wanting to delete it, make sure you close the FileStream before you call the File.Delete(path). I had this issue.

var filestream = new System.IO.FileStream(@"C:\Test\PutInv.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(@"C:\Test\PutInv.txt");

How to load external scripts dynamically in Angular?

import { Injectable } from '@angular/core';
import * as $ from 'jquery';

interface Script {
    src: string;
    loaded: boolean;
}

@Injectable()
export class ScriptLoaderService {
    public _scripts: Script[] = [];

    /**
     * @deprecated
     * @param tag
     * @param {string} scripts
     * @returns {Promise<any[]>}
     */
    load(tag, ...scripts: string[]) {
        scripts.forEach((src: string) => {
            if (!this._scripts[src]) {
                this._scripts[src] = { src: src, loaded: false };
            }
        });

        const promises: any[] = [];
        scripts.forEach(src => promises.push(this.loadScript(tag, src)));

        return Promise.all(promises);
    }

    /**
     * Lazy load list of scripts
     * @param tag
     * @param scripts
     * @param loadOnce
     * @returns {Promise<any[]>}
     */
    loadScripts(tag, scripts, loadOnce?: boolean) {
        debugger;
        loadOnce = loadOnce || false;

        scripts.forEach((script: string) => {
            if (!this._scripts[script]) {
                this._scripts[script] = { src: script, loaded: false };
            }
        });

        const promises: any[] = [];
        scripts.forEach(script => promises.push(this.loadScript(tag, script, loadOnce)));

        return Promise.all(promises);
    }

    /**
     * Lazy load a single script
     * @param tag
     * @param {string} src
     * @param loadOnce
     * @returns {Promise<any>}
     */
    loadScript(tag, src: string, loadOnce?: boolean) {
        debugger;
        loadOnce = loadOnce || false;

        if (!this._scripts[src]) {
            this._scripts[src] = { src: src, loaded: false };
        }

        return new Promise((resolve, _reject) => {
            // resolve if already loaded
            if (this._scripts[src].loaded && loadOnce) {
                resolve({ src: src, loaded: true });
            } else {
                // load script tag
                const scriptTag = $('<script/>')
                    .attr('type', 'text/javascript')
                    .attr('src', this._scripts[src].src);

                $(tag).append(scriptTag);

                this._scripts[src] = { src: src, loaded: true };
                resolve({ src: src, loaded: true });
            }
        });
    }

    reloadOnSessionChange() {
        window.addEventListener('storage', function(data) {
            if (data['key'] === 'token' && data['oldValue'] == null && data['newValue']) {
                document.location.reload();
            }
        });
    }
}

Can a constructor in Java be private?

Well, if all of your methods in a class are static, then a private constructor is a good idea.

How can I apply a border only inside a table?

that will do it all without css <TABLE BORDER=1 RULES=ALL FRAME=VOID>

code from: HTML CODE TUTORIAL

CSS: how to add white space before element's content?

Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/

This will add 10 pixels to the left of the paragraph element

p {
    margin-left: 10px;
 }

or if you just want some padding within your paragraph element

p {
    padding-left: 10px;
}

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

Combine Points with lines with ggplot2

A small change to Paul's code so that it doesn't return the error mentioned above.

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
           id.vars = "Species")
dat$x <- c(1:150, 1:150)
ggplot(aes(x = x, y = value, color = variable), data = dat) +  
  geom_point() + geom_line()

What is the opposite of :hover (on mouse leave)?

Put your duration time in the non-hover selection:

li a {
  background-color: #111;
  transition:1s;
}

li a:hover {
  padding:19px;
}

how to generate web service out of wsdl

You cannot guarantee that the automatically-generated WSDL will match the WSDL from which you create the service interface.

In your scenario, you should place the WSDL file on your web site somewhere, and have consumers use that URL. You should disable the Documentation protocol in the web.config so that "?wsdl" does not return a WSDL. See <protocols> Element.

Also, note the first paragraph of that article:

This topic is specific to a legacy technology. XML Web services and XML Web service clients should now be created using Windows Communication Foundation (WCF).

Java Byte Array to String to Byte Array

Use the below code API to convert bytecode as string to Byte array.

 byte[] byteArray = DatatypeConverter.parseBase64Binary("JVBERi0xLjQKMyAwIG9iago8P...");

Docker compose port mapping

It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.

https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.

First, you'll need to install the nc command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.

Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.

# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]

Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc, even with the -l and -k options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.

# cmd.sh
#! /usr/bin/env bash

while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &

tail -f /dev/null # Or any other command that never exits

Xcode 6: Keyboard does not show up in simulator

This seems to be a bug in iOS 8. There are two fixes to this problem :

  1. Toggle between simulator keyboard and MacBook keyboard using the Command+K shortcut.

  2. Reattach keyboard to simulator :

    a. Open Simulator

    b. Select Hardware -> Keyboard

    c. Uncheck and then check 'Connect Hardware Keyboard'

Screenshot for step 2

OR simply press the Shift + Command + K shortcut

How to make Bitmap compress without change the bitmap size?

If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.

Quality Accepts 0 - 100

0 = MAX Compression (Least Quality which is suitable for Small images)

100 = Least Compression (MAX Quality which is suitable for Big images)

How to replace (null) values with 0 output in PIVOT

If you have a situation where you are using dynamic columns in your pivot statement you could use the following:

DECLARE @cols               NVARCHAR(MAX)
DECLARE @colsWithNoNulls    NVARCHAR(MAX)
DECLARE @query              NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(Name) 
            FROM Hospital
            WHERE Active = 1 AND StateId IS NOT NULL
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @colsWithNoNulls = STUFF(
            (
                SELECT distinct ',ISNULL(' + QUOTENAME(Name) + ', ''No'') ' + QUOTENAME(Name)
                FROM Hospital
                WHERE Active = 1 AND StateId IS NOT NULL
                FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

EXEC ('
        SELECT Clinician, ' + @colsWithNoNulls + '
        FROM
        (
            SELECT DISTINCT p.FullName AS Clinician, h.Name, CASE WHEN phl.personhospitalloginid IS NOT NULL THEN ''Yes'' ELSE ''No'' END AS HasLogin
            FROM Person p
            INNER JOIN personlicense pl ON pl.personid = p.personid
            INNER JOIN LicenseType lt on lt.licensetypeid = pl.licensetypeid
            INNER JOIN licensetypegroup ltg ON ltg.licensetypegroupid = lt.licensetypegroupid
            INNER JOIN Hospital h ON h.StateId = pl.StateId
            LEFT JOIN PersonHospitalLogin phl ON phl.personid = p.personid AND phl.HospitalId = h.hospitalid
            WHERE ltg.Name = ''RN'' AND
                pl.licenseactivestatusid = 2 AND
                h.Active = 1 AND
                h.StateId IS NOT NULL
        ) AS Results
        PIVOT
        (
            MAX(HasLogin)
            FOR Name IN (' + @cols + ')
        ) p
')

How to mock location on device?

The Google tutorial for doing this can be found here, it provides code examples and explains the process.

http://developer.android.com/training/location/location-testing.html#SendMockLocations

Limiting floats to two decimal points

The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:

>>> 0.1
0.10000000000000001

you may be tempted to use the round() function to chop it back to the single digit you expect. But that makes no difference:

>>> round(0.1, 1)
0.10000000000000001

The problem is that the binary floating-point value stored for “0.1” was already the best possible binary approximation to 1/10, so trying to round it again can’t make it better: it was already as good as it gets.

Another consequence is that since 0.1 is not exactly 1/10, summing ten values of 0.1 may not yield exactly 1.0, either:

>>> sum = 0.0
>>> for i in range(10):
...     sum += 0.1
...
>>> sum
0.99999999999999989

One alternative and solution to your problems would be using the decimal module.

Preventing HTML and Script injections in Javascript

Try this method to convert a 'string that could potentially contain html code' to 'text format':

$msg = "<div></div>";
$safe_msg = htmlspecialchars($msg, ENT_QUOTES);
echo $safe_msg;

Hope this helps!

Private class declaration

You can.

package test;

public class Test {
    public static void main(String[] args) {
        B b = new B();
    }
}

class B {
  // Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}

How can I change the font-size of a select option?

select[value="value"]{
   background-color: red;
   padding: 3px;
   font-weight:bold;
}

setHintTextColor() in EditText

Inside Layout Xml File We can Change Color of Hint.....

android:textColorHint="@android:color/*****"

you can replace * with color or color code.

How to fix "containing working copy admin area is missing" in SVN?

I just did 'svn revert /blabla' and it worked, the folder is back and I can svn delete it

How to convert hex to rgb using Java?

For shortened hex code like #fff or #000

int red = "colorString".charAt(1) == '0' ? 0 : 
     "colorString".charAt(1) == 'f' ? 255 : 228;  
int green =
     "colorString".charAt(2) == '0' ? 0 :  "colorString".charAt(2) == 'f' ?
     255 : 228;  
int blue = "colorString".charAt(3) == '0' ? 0 : 
     "colorString".charAt(3) == 'f' ? 255 : 228;

Color.rgb(red, green,blue);

Group dataframe and get sum AND count?

try this:

In [110]: (df.groupby('Company Name')
   .....:    .agg({'Organisation Name':'count', 'Amount': 'sum'})
   .....:    .reset_index()
   .....:    .rename(columns={'Organisation Name':'Organisation Count'})
   .....: )
Out[110]:
          Company Name   Amount  Organisation Count
0  Vifor Pharma UK Ltd  4207.93                   5

or if you don't want to reset index:

df.groupby('Company Name')['Amount'].agg(['sum','count'])

or

df.groupby('Company Name').agg({'Amount': ['sum','count']})

Demo:

In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
                         sum  count
Company Name
Vifor Pharma UK Ltd  4207.93      5

In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
                      Amount
                         sum count
Company Name
Vifor Pharma UK Ltd  4207.93     5