Programs & Examples On #Color profile

How to add new line into txt file

Why not do it with one method call:

File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });

which will do the newline for you, and allow you to insert multiple lines at once if you want.

How to move up a directory with Terminal in OS X

cd .. will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications would take you to Macintosh HD/Applications

read file from assets

one line solution for kotlin:

fun readFileText(fileName: String): String {
    return assets.open(fileName).bufferedReader().use { it.readText() }
}

Also you can use it as extension function everyWhere

fun Context.readTextFromAsset(fileName : String) : String{
     return assets.open(fileName).bufferedReader().use { 
     it.readText()}
}

Simply call in any context Class

context.readTextFromAsset("my file name")

How to create our own Listener interface in android?

There are 4 steps:

1.create interface class (listener)

2.use interface in view 1 (define variable)

3.implements interface to view 2 (view 1 used in view 2)

4.pass interface in view 1 to view 2

Example:

Step 1: you need create interface and definde function

public interface onAddTextViewCustomListener {
    void onAddText(String text);
}

Step 2: use this interface in view

public class CTextView extends TextView {


    onAddTextViewCustomListener onAddTextViewCustomListener; //listener custom

    public CTextView(Context context, onAddTextViewCustomListener onAddTextViewCustomListener) {
        super(context);
        this.onAddTextViewCustomListener = onAddTextViewCustomListener;
        init(context, null);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    public void init(Context context, @Nullable AttributeSet attrs) {

        if (isInEditMode())
            return;

        //call listener
        onAddTextViewCustomListener.onAddText("this TextView added");
    }
}

Step 3,4: implements to activity

public class MainActivity extends AppCompatActivity implements onAddTextViewCustomListener {


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

        //get main view from layout
        RelativeLayout mainView = (RelativeLayout)findViewById(R.id.mainView);

        //create new CTextView and set listener
        CTextView cTextView = new CTextView(getApplicationContext(), this);

        //add cTextView to mainView
        mainView.addView(cTextView);
    }

    @Override
    public void onAddText(String text) {
        Log.i("Message ", text);
    }
}

isolating a sub-string in a string before a symbol in SQL Server 2008

This can achieve using two SQL functions- SUBSTRING and CHARINDEX

You can read strings to a variable as shown in the above answers, or can add it to a SELECT statement as below:

SELECT SUBSTRING('Net Operating Loss - 2007' ,0, CHARINDEX('-','Net Operating Loss - 2007'))

Run git pull over all subdirectories

I use this

for dir in $(find . -name ".git")
do cd ${dir%/*}
    echo $PWD
    git pull
    echo ""
    cd - > /dev/null
done

Github

html <input type="text" /> onchange event not working

A couple of comments that IMO are important:

  • input elements not not emitting 'change' event until USER action ENTER or blur await IS the correct behavior.

  • The event you want to use is "input" ("oninput"). Here is well demonstrated the different between the two: https://javascript.info/events-change-input

  • The two events signal two different user gestures/moments ("input" event means user is writing or navigating a select list options, but still didn't confirm the change. "change" means user did changed the value (with an enter or blur our)

  • Listening for key events like many here recommended is a bad practice in this case. (like people modifying the default behavior of ENTER on inputs)...

  • jQuery has nothing to do with this. This is all in HTML standard.

  • If you have problems understanding WHY this is the correct behavior, perhaps is helpful, as experiment, use your text editor or browser without a mouse/pad, just a keyboard.

My two cents.

Extract substring in Bash

Given test.txt is a file containing "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

cut -b19-20 test.txt > test1.txt # This will extract chars 19 & 20 "ST" 
while read -r; do;
> x=$REPLY
> done < test1.txt
echo $x
ST

Failed to locate the winutils binary in the hadoop binary path

winutils.exe are required for hadoop to perform hadoop related commands. please download hadoop-common-2.2.0 zip file. winutils.exe can be found in bin folder. Extract the zip file and copy it in the local hadoop/bin folder.

Use of alloc init instead of new

Very old question, but I've written some example just for fun — maybe you'll find it useful ;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

In main function both statements:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

result in the same output:

2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating...
2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...

Express-js wildcard routing to cover everything under and including a path

In array you also can use variables passing to req.params:

app.get(["/:foo", "/:foo/:bar"], /* function */);

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

I had a similar problem recently, and needed to change the permissions of my vendor folder

By running following commands :

  1. php artisan cache:clear
  2. chmod -R 777 storage vendor
  3. composer dump-autoload

I need to give all the permissions required to open and write vendor files to solve this issue

How do I generate a list with a specified increment step?

You can use scalar multiplication to modify each element in your vector.

> r <- 0:10 
> r <- r * 2
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

or

> r <- 0:10 * 2 
> r 
 [1]  0  2  4  6  8 10 12 14 16 18 20

Check if a String contains a special character

All depends on exactly what you mean by "special". In a regex you can specify

  • \W to mean non-alpahnumeric
  • \p{Punct} to mean punctuation characters

I suspect that the latter is what you mean. But if not use a [] list to specify exactly what you want.

Can I access constants in settings.py from templates in Django?

If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

Here's how:

  1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

    from django.conf import settings # import the settings file
    
    def admin_media(request):
        # return the value you want as a dictionnary. you may add multiple values in there.
        return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
    
  2. add your context processor to your settings.py file:

    TEMPLATES = [{
        # whatever comes before
        'OPTIONS': {
            'context_processors': [
                # whatever comes before
                "your_app.context_processors.admin_media",
            ],
        }
    }]
    
  3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

    from django.shortcuts import render
    
    def my_view(request):
        return render(request, "index.html")
    
  4. and finally, in your template:

    ...
    <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
    ...
    

Is it valid to define functions in JSON results?

Leave the quotes off...

var a = {"b":function(){alert('hello world');} };

a.b();

What is Linux’s native GUI API?

In Linux the graphical user interface is not a part of the operating system. The graphical user interface found on most Linux desktops is provided by software called the X Window System, which defines a device independent way of dealing with screens, keyboards and pointer devices.

X Window defines a network protocol for communication, and any program that knows how to "speak" this protocol can use it. There is a C library called Xlib that makes it easier to use this protocol, so Xlib is kind of the native GUI API. Xlib is not the only way to access an X Window server; there is also XCB.

Toolkit libraries such as GTK+ (used by GNOME) and Qt (used by KDE), built on top of Xlib, are used because they are easier to program with. For example they give you a consistent look and feel across applications, make it easier to use drag-and-drop, provide components standard to a modern desktop environment, and so on.

How X draws on the screen internally depends on the implementation. X.org has a device independent part and a device dependent part. The former manages screen resources such as windows, while the latter communicates with the graphics card driver, usually a kernel module. The communication may happen over direct memory access or through system calls to the kernel. The driver translates the commands into a form that the hardware on the card understands.

As of 2013, a new window system called Wayland is starting to become usable, and many distributions have said they will at some point migrate to it, though there is still no clear schedule. This system is based on OpenGL/ES API, which means that in the future OpenGL will be the "native GUI API" in Linux. Work is being done to port GTK+ and QT to Wayland, so that current popular applications and desktop systems would need minimal changes. The applications that cannot be ported will be supported through an X11 server, much like OS X supports X11 apps through Xquartz. The GTK+ port is expected to be finished within a year, while Qt 5 already has complete Wayland support.

To further complicate matters, Ubuntu has announced they are developing a new system called Mir because of problems they perceive with Wayland. This window system is also based on the OpenGL/ES API.

An error when I add a variable to a string

You're missing your database name:

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

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

var_dump($entry_database);

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

Dynamic WHERE clause in LINQ

A simple Approach can be if your Columns are of Simple Type like String

public static IEnumerable<MyObject> WhereQuery(IEnumerable<MyObject> source, string columnName, string propertyValue)
{
   return source.Where(m => { return m.GetType().GetProperty(columnName).GetValue(m, null).ToString().StartsWith(propertyValue); });
}

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

I have tried and it successfully, before pulling, let commit all file that you have not committed, then you will not receive that messages from AS.

What is the 'realtime' process priority setting for?

Like all other answers before real time gives that program the utmost priority class. Nothing is processed until that program has been processed.
On my pentium 4 machine I set minecraft to real time a lot since it increases the game performance a lot, and the system seems completely stable. so realtime isn't as bad as it seems, just if you have a multi-core set a program's affinity to a specific core or cores (just not all of them, just to let everything else be able to run in case the real time set programs gets hung up) and set the priority to real time.

How to generate Javadoc from command line

Link to JavaDoc

I believe this will surely help you.

javadoc -d C:/javadoc/test com.mypackage

"undefined" function declared in another file?

you should use go modules now, if you are not following How to write go code

With go module you don't have to put the code in the $GOPATH/src. it can live in any other location as well.

You can move the code to different directory like /employee, To make it work Just under employee directory initialise the go module

go mod init example.com/employee

Is there a way to create multiline comments in Python?

Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.

Here is an example:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

How to install a node.js module without using npm?

Download the code from github into the node_modules directory

var moduleName = require("<name of directory>")

that should do it.

if the module has dependancies and has a package.json, open the module and enter npm install.

Hope this helps

Bootstrap Modal Backdrop Remaining

try this

$('.modal').on('hide.bs.modal', function () {
    if ($(this).is(':visible')) {
       console.log("show modal")
       $('.modal-backdrop').show();
    }else{
        console.log("hidden modal");
        $('.modal-backdrop').remove();
    }
})

Plotting in a non-blocking way with Matplotlib


A simple trick that works for me is the following:

  1. Use the block = False argument inside show: plt.show(block = False)
  2. Use another plt.show() at the end of the .py script.

Example:

import matplotlib.pyplot as plt

plt.imshow(add_something)
plt.xlabel("x")
plt.ylabel("y")

plt.show(block=False)

#more code here (e.g. do calculations and use print to see them on the screen

plt.show()

Note: plt.show() is the last line of my script.

Xcode process launch failed: Security

To get around the process launch failed: Security issue and immediately launch the app on your device, tap the app icon on your iOS device after running the app via Xcode.

This will allow you to immediately run the app. It may not actually "fix" the root issue that is causing these permission alerts.

Be sure to tap the app icon while the Xcode alert is still shown. Otherwise the app will not run. I continually forget this vital step and am unable to run the app on my device. Thus I am documenting it here for myself and everyone else :)

  1. Run the app via Xcode. You will see the security alert below. Do not press OK.

Could not launch "AppName" process launch failed: Security

  1. On your iOS device, tap the newly installed app icon:

tap the app icon on your iOS device

  1. After tapping the icon, you should now see an alert asking you to "Trust" the Untrusted App Developer. After doing so the app will immediately run, unconnected to the Xcode debugger.

    • If you do not see this "Trust" alert, you likely pressed "OK" in Xcode too soon. Do not press "OK" on the Xcode alert until after trusting the developer.

Trust this developer?

  1. Finally, go back and press "OK" on the Xcode alert. You will have to re-run the app to connect the running app on your iOS device to the Xcode debugger.

Now press OK in Xcode.

How to change the remote repository for a git submodule?

These commands will do the work on command prompt without altering any files on local repository

git config --file=.gitmodules submodule.Submod.url https://github.com/username/ABC.git
git config --file=.gitmodules submodule.Submod.branch Development
git submodule sync
git submodule update --init --recursive --remote

Please look at the blog for screenshots: Changing GIT submodules URL/Branch to other URL/branch of same repository

MongoDB: How to find the exact version of installed MongoDB

To check mongodb version use the mongod command with --version option.

To check MongoDB Server version, Open the command line via your terminal program and execute the following command:

Path : C:\Program Files\MongoDB\Server\3.2\bin Open Cmd and execute the following command: mongod --version To Check MongoDB Shell version, Type:

mongo --version

Resizing UITableView to fit content

In case your contentSize is not correct this is because it is based on the estimatedRowHeight (automatic), use this before

tableView.estimatedRowHeight = 0;

source : https://forums.developer.apple.com/thread/81895

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

jQuery exclude elements with certain class in selector

To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $(".navitem").click(function(){_x000D_
        $(".navitem").removeClass("active");_x000D_
        $(".navitem").not($(this)).addClass("active");_x000D_
    });_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
    width: 100px;_x000D_
    background: red;_x000D_
    color: white;_x000D_
    display: inline-block;_x000D_
    position: relative;_x000D_
    text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
    background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
_x000D_
_x000D_

The above example can be simplified, but wanted to show the usage of this in the not() selector.

How do I pause my shell script for a second before continuing?

And what about:

read -p "Press enter to continue"

$(this).val() not working to get text from span using jquery

I think you want .text():

var monthname = $(this).text();

How to run a command in the background and get no output?

If you want to run the script in a linux kickstart you have to run as below .

sh /tmp/script.sh > /dev/null 2>&1 < /dev/null &

Get an object's class name at runtime

  • Had to add ".prototype." to use : myClass.prototype.constructor.name .
  • Otherwise with the following code : myClass.constructor.name, I had the TypeScript error :

error TS2339: Property 'name' does not exist on type 'Function'.

How to get full REST request body using Jersey?

Since you're transferring data in xml, you could also (un)marshal directly from/to pojos.

There's an example (and more info) in the jersey user guide, which I copy here:

POJO with JAXB annotations:

@XmlRootElement
public class Planet {
    public int id;
    public String name;
    public double radius;
}

Resource:

@Path("planet")
public class Resource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Planet getPlanet() {
        Planet p = new Planet();
        p.id = 1;
        p.name = "Earth";
        p.radius = 1.0;

        return p;
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public void setPlanet(Planet p) {
        System.out.println("setPlanet " + p.name);
    }

}      

The xml that gets produced/consumed:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
    <id>1</id>
    <name>Earth</name>
    <radius>1.0</radius>
</planet>

Vue.js toggle class on click

In addition to NateW's answer, if you have hyphens in your css class name, you should wrap that class within (single) quotes:

<th 
  class="initial " 
  v-on:click="myFilter"
  v-bind:class="{ 'is-active' : isActive}"
>

 <span class="wkday">M</span>
 </th>

See this topic for more on the subject.

Customizing the template within a Directive

Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.

Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.

The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:

    angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        template: function(element, attrs) {
           var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
             return htmlText;
        }
        compile: function(element, attrs)
        {
           //do whatever else is necessary
        }
    }
})

MySQL LEFT JOIN Multiple Conditions

Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result

SELECT a.* FROM a 
    LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']} 
    WHERE a.keyword LIKE '%".$keyword."%' 
    GROUP BY group_id

Including a groovy script in another groovy

Here's a complete example of including one script within another.
Just run the Testmain.groovy file
Explanatory comments included because I'm nice like that ;]

Testutils.groovy

// This is the 'include file'
// Testmain.groovy will load it as an implicit class
// Each method in here will become a method on the implicit class

def myUtilityMethod(String msg) {
    println "myUtilityMethod running with: ${msg}"
}

Testmain.groovy

// Run this file

// evaluate implicitly creates a class based on the filename specified
evaluate(new File("./Testutils.groovy"))
// Safer to use 'def' here as Groovy seems fussy about whether the filename (and therefore implicit class name) has a capital first letter
def tu = new Testutils()
tu.myUtilityMethod("hello world")

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

how to display data values on Chart.js

Based on @Ross's answer answer for Chart.js 2.0 and up, I had to include a little tweak to guard against the case when the bar's heights comes too chose to the scale boundary.

Example

The animation attribute of the bar chart's option:

animation: {
            duration: 500,
            easing: "easeOutQuart",
            onComplete: function () {
                var ctx = this.chart.ctx;
                ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
                ctx.textAlign = 'center';
                ctx.textBaseline = 'bottom';

                this.data.datasets.forEach(function (dataset) {
                    for (var i = 0; i < dataset.data.length; i++) {
                        var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
                            scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
                        ctx.fillStyle = '#444';
                        var y_pos = model.y - 5;
                        // Make sure data value does not get overflown and hidden
                        // when the bar's value is too close to max value of scale
                        // Note: The y value is reverse, it counts from top down
                        if ((scale_max - model.y) / scale_max >= 0.93)
                            y_pos = model.y + 20; 
                        ctx.fillText(dataset.data[i], model.x, y_pos);
                    }
                });               
            }
        }

Getting Hour and Minute in PHP

In addressing your comment that you need your current time, and not the system time, you will have to make an adjustment yourself, there are 3600 seconds in an hour (the unit timestamps use), so use that. for example, if your system time was one hour behind:

$time = date('H:i',time() + 3600);

Storing C++ template function definitions in a .CPP file

This is definitely not a nasty hack, but be aware of the fact that you will have to do it (the explicit template specialization) for every class/type you want to use with the given template. In case of MANY types requesting template instantiation there can be A LOT of lines in your .cpp file. To remedy this problem you can have a TemplateClassInst.cpp in every project you use so that you have greater control what types will be instantiated. Obviously this solution will not be perfect (aka silver bullet) as you might end up breaking the ODR :).

pandas unique values multiple columns

In [5]: set(df.Col1).union(set(df.Col2))
Out[5]: {'Bill', 'Bob', 'Joe', 'Mary', 'Steve'}

Or:

set(df.Col1) | set(df.Col2)

How to create a project from existing source in Eclipse and then find it?

The easiest method is really good but you don't get a standard Java project, i.e., the .java and .class files separated in different folders.

To get this very easily:

  1. Create a folder called "ProjectName" on the workspace of Eclipse.
  2. Copy or move your folder with the .java files to the "ProjectName" folder.
  3. Create a new Java Project called "ProjectName" (with the Use default location marked).
  4. Press <Enter> and that's it.

Multiple arguments to function called by pthread_create()?

In this code's thread creation, the address of a function pointer is being passed. The original pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0

It should read as pthread_create(&some_thread, NULL, print_the_arguments, (void *) &args)

A good way to remember is that all of this function's arguments should be addresses.

some_thread is declared statically, so the address is sent properly using &.

I would create a pthread_attr_t variable, then use pthread_attr_init() on it and pass that variable's address. But, passing a NULL pointer is valid as well.

The & in front of the function label is what is causing the issue here. The label used is already a void* to a function, so only the label is necessary.

To say != 0 with the final argument would seem to cause undetermined behavior. Adding this means that a boolean is being passed instead of a reference.

Akash Agrawal's answer is also part of the solution to this code's problem.

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.

ex.

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

Is it possible to have multiple styles inside a TextView?

As Jon said, for me this is the best solution and you dont need to set any text at runtime, only use this custom class HtmlTextView

public class HtmlTextView extends TextView {

  public HtmlTextView(Context context) {
      super(context);
  }

  public HtmlTextView(Context context, AttributeSet attrs) {
      super(context, attrs);
  }

  public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr) 
  {
      super(context, attrs, defStyleAttr);
  }

  @TargetApi(21)
  public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
      super(context, attrs, defStyleAttr, defStyleRes);
  }

  @Override
  public void setText(CharSequence s,BufferType b){
      super.setText(Html.fromHtml(s.toString()),b);
  }

}

and thats it, now only put it in your XML

<com.fitc.views.HtmlTextView
    android:id="@+id/html_TV"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/example_html" />

with your Html String

<string name="example_html">
<![CDATA[
<b>Author:</b> Mr Donuthead<br/>
<b>Contact:</b> [email protected]<br/>
<i>Donuts for life </i>
]]>

Create ArrayList from array

If the array is of a primitive type, the given answers won't work. But since Java 8 you can use:

int[] array = new int[5];
Arrays.stream(array).boxed().collect(Collectors.toList());

Math constant PI value in C

anyway you have not a unlimited accuracy so C define a constant in this way:

#define PI 3.14159265358979323846

import math.h to use this

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Depending on your platform you can use: sqlite3 file_name.db from the terminal. .tables will list the tables, .schema is full layout. SQLite commands like: select * from table_name; and such will print out the full contents. Type: ".exit" to exit. No need to download a GUI application.Use a semi-colon if you want it to execute a single command. Decent SQLite usage tutorial http://www.thegeekstuff.com/2012/09/sqlite-command-examples/

Removing all empty elements from a hash / YAML?

You can use Hash#reject to remove empty key/value pairs from a ruby Hash.

# Remove empty strings
{ a: 'first', b: '', c: 'third' }.reject { |key,value| value.empty? } 
#=> {:a=>"first", :c=>"third"}

# Remove nil
{a: 'first', b: nil, c: 'third'}.reject { |k,v| v.nil? } 
# => {:a=>"first", :c=>"third"}

# Remove nil & empty strings
{a: '', b: nil, c: 'third'}.reject { |k,v| v.nil? || v.empty? } 
# => {:c=>"third"}

Check if application is installed - Android

@Override 
protected void onResume() {
    super.onResume();
    boolean installed = false;

    while (!installed) {
        installed = appInstalledOrNot (APPPACKAGE);
        if (installed) {
            Toast.makeText(this, "App installed", Toast.LENGTH_SHORT).show ();
        }
    }
} 

private boolean appInstalledOrNot (String uri) {
    PackageManager pm = getPackageManager();
    boolean app_installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        app_installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        app_installed = false;
    }
    return app_installed;
}

http to https through .htaccess

Since this is one of the top results in the search, if you're trying to add http to https redirect on AWS beanstalk, the accepted solution will not work. You need following code instead:

RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^.*$ https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

HTTP GET request in JavaScript?

Ajax

You'd be best off using a library such as Prototype or jQuery.

Mockito - NullpointerException when stubbing Method

you need to initialize MockitoAnnotations.initMocks(this) method has to called to initialize annotated fields.

   @Before public void initMocks() {
       MockitoAnnotations.initMocks(this);
   }

for more details see Doc

How can I Insert data into SQL Server using VBNet

Imports System.Data

Imports System.Data.SqlClient

Public Class Form2

Dim myconnection As SqlConnection

Dim mycommand As SqlCommand

Dim dr As SqlDataReader

Dim dr1 As SqlDataReader

Dim ra As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")

    'you need to provide password for sql server

    myconnection.Open()

    mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)

    mycommand.ExecuteNonQuery()

    MessageBox.Show("New Row Inserted" & ra)

    myconnection.Close()

End Sub

End Class

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

I am working behind a proxy and just installed SASS by downloading directly from http://rubygems.org.

I then ran sudo gem install [path/to/downloaded/gem/file]. I cannot say this will work for all gems, but it may help some people.

How can I concatenate two arrays in Java?

You can try this

 public static Object[] addTwoArray(Object[] objArr1, Object[] objArr2){
    int arr1Length = objArr1!=null && objArr1.length>0?objArr1.length:0;
    int arr2Length = objArr2!=null && objArr2.length>0?objArr2.length:0;
    Object[] resutlentArray = new Object[arr1Length+arr2Length]; 
    for(int i=0,j=0;i<resutlentArray.length;i++){
        if(i+1<=arr1Length){
            resutlentArray[i]=objArr1[i];
        }else{
            resutlentArray[i]=objArr2[j];
            j++;
        }
    }

    return resutlentArray;
}

U can type cast your array !!!

How to define a variable in a Dockerfile?

To my knowledge, only ENV allows that, as mentioned in "Environment replacement"

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build.

In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.


This day, I use both ARG (docker 1.10+, and docker build --build-arg var=value) and ENV.
Using ARG alone means your variable is visible at build time, not at runtime.

My Dockerfile usually has:

ARG var
ENV var=${var}

In your case, ARG is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.

fatal: 'origin' does not appear to be a git repository

It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)

git pull origin master

for me that simple call solved those error messages:

  • fatal: 'master' does not appear to be a git repository
  • fatal: Could not read from remote repository.

REST URI convention - Singular or plural name of resource while creating it

Using plural for all methods is more practical at least in one aspect: if you're developing and testing a resource API using Postman (or similar tool), you don't need to edit the URI when switching from GET to PUT to POST etc.

Length of array in function argument

The array decays to a pointer when passed.

Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.


That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).

Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?


Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.

You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.

Transpose a matrix in Python

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

How to define unidirectional OneToMany relationship in JPA

My bible for JPA work is the Java Persistence wikibook. It has a section on unidirectional OneToMany which explains how to do this with a @JoinColumn annotation. In your case, i think you would want:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE")
private Set<Text> text;

I've used a Set rather than a List, because the data itself is not ordered.

The above is using a defaulted referencedColumnName, unlike the example in the wikibook. If that doesn't work, try an explicit one:

@OneToMany
@JoinColumn(name="TXTHEAD_CODE", referencedColumnName="DATREG_META_CODE")
private Set<Text> text;

Cycles in family tree software

Assertions don't survive reality

Usually assertions don't survive the contact with real world data. It's a part of the process of software engineering to decide, with which data you want to deal and which are out of scope.

Cyclic family graphs

Regarding family "trees" (in fact it are full blown graphs, including cycles), there is a nice anecdote:

I married a widow who had a grown daughter. My father, who often visited us, fell in love with my step-daughter and married her. As a result, my father became my son, and my daughter became my mother. Some time later, I gave my wife a son, who was the brother of my father, and my uncle. My father's wife (who is also my daughter and my mother) got a son. As a result, I got a brother and a grandson in the same person. My wife is now my grandmother, because she is my mother's mother. So I am the husband of my wife, and at the same time the step-grandson of my wife. In other words, I'm my own grandpa.

Things get even more strange, when you take surrogates or "fuzzy fatherhood" into account.

How to deal with that

Define cycles as out-of-scope

You could decide that your software should not deal with such rare cases. If such a case occurs, the user should use a different product. This makes dealing with the more common cases much more robust, because you can keep more assertions and a simpler data model.

In this case, add some good import and export features to your software, so the user can easily migrate to a different product when necessary.

Allow manual relations

You could allow the user to add manual relations. These relations are not "first-class citizens", i.e. the software takes them as-is, doesn't check them and doesn't handle them in the main data model.

The user can then handle rare cases by hand. Your data model will still stay quite simple and your assertions will survive.

Be careful with manual relations. There is a temptation to make them completely configurable and hence create a fully configurable data model. This will not work: Your software will not scale, you will get strange bugs and finally the user interface will become unusable. This anti-pattern is called "soft coding", and "The daily WTF" is full of examples for that.

Make your data model more flexible, skip assertions, test invariants

The last resort would be making your data model more flexible. You would have to skip nearly all assertions and base your data model on a full blown graph. As the above example shows, it is easily possible to be your own grandfather, so you can even have cycles.

In this case, you should extensively test your software. You had to skip nearly all assertions, so there is a good chance for additional bugs.

Use a test data generator to check unusual test cases. There are quick check libraries for Haskell, Erlang or C. For Java / Scala there are ScalaCheck and Nyaya. One test idea would be to simulate a random population, let it interbreed at random, then let your software first import and then export the result. The expectation would be, that all connections in the output are also in the input and vice verse.

A case, where a property stays the same is called an invariant. In this case, the invariant is the set of "romantic relations" between the individuals in the simulated population. Try to find as much invariants as possible and test them with randomly generated data. Invariants can be functional, e.g.:

  • an uncle stays an uncle, even when you add more "romantic relations"
  • every child has a parent
  • a population with two generations has at least one grand-parent

Or they can be technical:

  • Your software will not crash on a graph up to 10 billion members (no matter how many interconnections)
  • Your software scales with O(number-of-nodes) and O(number-of-edges^2)
  • Your software can save and re-load every family graph up to 10 billion members

By running the simulated tests, you will find lots of strange corner cases. Fixing them will take a lot of time. Also you will lose a lot of optimizations, your software will run much slower. You have to decide, if it is worth it and if this is in the scope of your software.

Assigning a variable NaN in python without numpy

nan = float('nan')

And now you have the constant, nan.

You can similarly create NaN values for decimal.Decimal.:

dnan = Decimal('nan')

How to split long commands over multiple lines in PowerShell

If you have a function:

$function:foo | % Invoke @(
  'bar'
  'directory'
  $true
)

If you have a cmdlet:

[PSCustomObject] @{
  Path  = 'bar'
  Type  = 'directory'
  Force = $true
} | New-Item

If you have an application:

{foo.exe @Args} | % Invoke @(
  'bar'
  'directory'
  $true
)

Or

icm {foo.exe @Args} -Args @(
  'bar'
  'directory'
  $true
)

How do I retrieve my MySQL username and password?

Stop the MySQL process.

Start the MySQL process with the --skip-grant-tables option.

Start the MySQL console client with the -u root option.

List all the users;

SELECT * FROM mysql.user;

Reset password;

UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';

But DO NOT FORGET to

Stop the MySQL process

Start the MySQL Process normally (i.e. without the --skip-grant-tables option)

when you are finished. Otherwise, your database's security could be compromised.

HTML5 video - show/hide controls programmatically

Here's how to do it:

var myVideo = document.getElementById("my-video")    
myVideo.controls = false;

Working example: https://jsfiddle.net/otnfccgu/2/

See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp

What is a word boundary in regex, does \b match hyphen '-'?

A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ([0-9A-Za-z_]).

So, in the string "-12", it would match before the 1 or after the 2. The dash is not a word character.

What is a raw type and why shouldn't we use it?

I found this page after doing some sample exercises and having the exact same puzzlement.

============== I went from this code as provide by the sample ===============

public static void main(String[] args) throws IOException {

    Map wordMap = new HashMap();
    if (args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            countWord(wordMap, args[i]);
        }
    } else {
        getWordFrequency(System.in, wordMap);
    }
    for (Iterator i = wordMap.entrySet().iterator(); i.hasNext();) {
        Map.Entry entry = (Map.Entry) i.next();
        System.out.println(entry.getKey() + " :\t" + entry.getValue());
    }

====================== To This code ========================

public static void main(String[] args) throws IOException {
    // replace with TreeMap to get them sorted by name
    Map<String, Integer> wordMap = new HashMap<String, Integer>();
    if (args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            countWord(wordMap, args[i]);
        }
    } else {
        getWordFrequency(System.in, wordMap);
    }
    for (Iterator<Entry<String, Integer>> i = wordMap.entrySet().iterator(); i.hasNext();) {
        Entry<String, Integer> entry =   i.next();
        System.out.println(entry.getKey() + " :\t" + entry.getValue());
    }

}

===============================================================================

It may be safer but took 4 hours to demuddle the philosophy...

Git copy changes from one branch to another

Instead of merge, as others suggested, you can rebase one branch onto another:

git checkout BranchB
git rebase BranchA

This takes BranchB and rebases it onto BranchA, which effectively looks like BranchB was branched from BranchA, not master.

Jquery open popup on button click for bootstrap

The answer is on the example link you provided:

http://getbootstrap.com/javascript/#modals-usage

i.e.

Call a modal with id myModal with a single line of JavaScript:

$('#myModal').modal('show');

Converting List<String> to String[] in Java

You want

String[] strarray = strlist.toArray(new String[0]);

See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

System.out.println(Arrays.toString(strarray));

since that will print the actual elements.

Create dynamic variable name

This is not possible, it will give you a compile time error,

You can use array for this type of requirement .

For your Reference :

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

Using 'make' on OS X

If you've installed Xcode 4.3 and its Command Line Tools, just open Terminal and type the following: On Xcode 4.3, type the following in Terminal:

export PATH=$PATH:/Applications/Xcode.app/Contents/Developer/usr/bin

Open the terminal in visual studio?

New in the most recent version of Visual Studio, there is View --> Terminal, which will open a PowerShell instance as a VS dockable window, rather than a floating PowerShell or cmd instance from the Developer Command Prompt.

View then Terminal

In-place type conversion of a NumPy array

Update: This function only avoids copy if it can, hence this is not the correct answer for this question. unutbu's answer is the right one.


a = a.astype(numpy.float32, copy=False)

numpy astype has a copy flag. Why shouldn't we use it ?

Wait until boolean value changes it state

You need a mechanism which avoids busy-waiting. The old wait/notify mechanism is fraught with pitfalls so prefer something from the java.util.concurrent library, for example the CountDownLatch:

public final CountDownLatch latch = new CountDownLatch(1);

public void run () {
  latch.await();
  ...
}

And at the other side call

yourRunnableObj.latch.countDown();

However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService to which you submit as a task the work which must be done when the condition is met.

javascript popup alert on link click

just make it function,

<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>

<a href="javascript:AlertIt();">click me</a>

What is the difference between Google App Engine and Google Compute Engine?

In addition to the App Engine vs Compute Engine notes above the list here also includes a comparison with Google Kubernete Engine and some notes based on experience with a wide range of apps from small to very large. For more points see the Google Cloud Platform documentation high level description of features in App Engine Standard and Flex on the page Choosing an App Engine Environment. For another comparison of deployment of App Engine and Kubernetes see the post by Daz Wilkin App Engine Flex or Kubernetes Engine.

App Engine Standard

Pros

  • Very economical for low traffic apps in terms of direct costs and also the cost of maintaining the app.
  • Auto scaling is fast. Autoscaling in App Engine is based on lightweight instance classes F1-F4.
  • Version management and traffic splitting are fast and convenient. These features are built into App Engine (both Standard and Flex) natively.
  • Minimal management, developers need focus only on their app. Developers do not need to worry about managing VMs in a reliable, as in GCE, or learning about clusters, as with GKE.
  • Access to Datastore is fast. When App Engine was first released, the runtime was co-located with Datastore. Later Datastore was split out as the standalone product Cloud Datastore but the co-location of App Engine Standard serving with Datastore remains.
  • Access to Memcache is supported.
  • The App Engine sandbox is very secure. Compared with development on GCE or other virtual machines, where you need to do your own diligence to prevent the virtual machine from being taken over at the operating system level, the App Engine Standard sandbox is relatively secure by default.

Cons

  • Generally more constrained than other environments Instances are smaller. Although this is good for rapid autoscaling, many apps can benefit from larger instances, such as GCE instance sizes up to 96 cores.
  • Networking is not integrated with GCE
  • Cannot put App Engine behind a Google Cloud Load Balancer. Limited to supported runtimes: Python 2.7, Java 7 and 8, Go 1.6-1.9, and PHP 5.5. In Java, there is some support for Servlets but not the full J2EE standard.

App Engine Flex

Pros

  • Can use a custom runtime
  • Native integration with GCE networking
  • Version and traffic management is convenient, same as Standard
  • The larger instance sizes may be more suitable to to large complex applications, especially Java applications that can use a lot of memory

Cons

  • Network integration is not perfect - no integration with internal load balancers or Shared Virtual Private Clouds
  • Access to managed Memcache not generally available

Google Kubernetes Engine

Pros

  • Native integration with containers allows custom runtimes and greater control over cluster configuration.
  • Embodies many best practices working with virtual machines, such as immutable runtime environments and easy ability to roll back to previous versions
  • Provides a consistent and repeatable deployment framework
  • Based on open standards, notably Kubernetes, for portability between clouds and on-premises.
  • Version management can accomplished with Docker containers and the Google Container Registry

Cons

  • Traffic splitting and management is do-it-yourself, possibly leveraging Istio and Envoy
  • Some management overhead
  • Some time to ramp up on Kubernetes concepts, such as pods, deployments, services, ingress, and namespaces
  • Need to expose some public IPs unless using Private Clusters, now in beta, eliminate that need but you still need to provide access to locations where kubectl commands will be run from.
  • Monitoring integration not perfect
  • While L3 internal load balancing is supported natively on Kubernetes Engine, L7 internal load balancing is do-it-yourself, possibly leveraging Envoy

Compute Engine

Pros

  • Easy to ramp up - no need to ramp up on Kubernetes or App Engine, just reuse whatever you know from previous experience. This is probably the main reason for using Compute Engine directly.
  • Complete control - you can leverage many Compute Engine features directly and install the latest of all your favorite stuff to stay on the bleeding edge.
  • No need for public IPs. Some legacy software may be too hard to lock down if anything is exposed on public IPs.
  • You can leverage the Container-Optimized OS for running Docker containers

Cons

  • Mostly do-it-yourself, which can be challenging to do adequately for reliability and security, although you can reuse solutions from various places, including the Cloud Launcher.
  • More management overhead. There are many management tools for Compute Engine but they will not necessarily understand how you have deployed your application, like the App Engine and Kubernetes Engine monitoring tools do
  • Autoscaling is based on GCE instances, which can be slower than App Engine
  • Tendency is to install software on snowflake GCE instances, which can be some effort to maintain

How to add hours to current date in SQL Server?

DATEADD (datepart , number , date )

declare @num_hours int; 
    set @num_hours = 5; 

select dateadd(HOUR, @num_hours, getdate()) as time_added, 
       getdate() as curr_date  

How do I get the current date in JavaScript?

Most of the other answers are providing the date with time.
If you only need date.

new Date().toISOString().split("T")[0]

Output

[ '2021-02-08', '06:07:44.629Z' ]

If you want it in / format use replace.

If you want other formats then best to use momentjs.

Uncaught ReferenceError: $ is not defined error in jQuery

Scripts are loaded in the order you have defined them in the HTML.

Therefore if you first load:

<script type="text/javascript" src="./javascript.js"></script>

without loading jQuery first, then $ is not defined.

You need to first load jQuery so that you can use it.

I would also recommend placing your scripts at the bottom of your HTML for performance reasons.

How to convert <font size="10"> to px?

This cannot be answered that easily. It depends on the font used and the points per inch (ppi). This should give an overview of the problem.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

  1. Open config.default.php file under phpmyadmin/libraries/
  2. Find $cfg['Servers'][$i]['host'] = 'localhost'; Change to $cfg['Servers'][$i]['host'] = '127.0.0.1';
  3. refresh your phpmyadmin page, login

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

How to find MySQL process list and to kill those processes?

select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist) as stats;

Then copy and paste the result back into the terminal. Something like:

KILL 2871; KILL 2879; KILL 2874; KILL 2872; KILL 2866;

BATCH file asks for file or folder

The real trick is: Use a Backslash at the end of the target path where to copy the file. The /Y is for overwriting existing files, if you want no warnings.

Example:

xcopy /Y "C:\file\from\here.txt" "C:\file\to\here\"

Default settings Raspberry Pi /etc/network/interfaces

For my Raspberry Pi 3B model it was

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

How to call another controller Action From a controller in Mvc

Controllers are just classes - new one up and call the action method just like you would any other class member:

var result = new ControllerB().FileUploadMsgView("some string");

Most efficient way to append arrays in C#?

The solution looks like great fun, but it is possible to concatenate arrays in just two statements. When you're handling large byte arrays, I suppose it is inefficient to use a Linked List to contain each byte.

Here is a code sample for reading bytes from a stream and extending a byte array on the fly:

    byte[] buf = new byte[8192];
    byte[] result = new byte[0];
    int count = 0;
    do
    {
        count = resStream.Read(buf, 0, buf.Length);
        if (count != 0)
        {
            Array.Resize(ref result, result.Length + count);
            Array.Copy(buf, 0, result, result.Length - count, count);
        }
    }
    while (count > 0); // any more data to read?
    resStream.Close();

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

from here ORA-00054: resource busy and acquire with NOWAIT specified

You can also look up the sql,username,machine,port information and get to the actual process which holds the connection

SELECT O.OBJECT_NAME, S.SID, S.SERIAL#, P.SPID, S.PROGRAM,S.USERNAME,
S.MACHINE,S.PORT , S.LOGON_TIME,SQ.SQL_FULLTEXT 
FROM V$LOCKED_OBJECT L, DBA_OBJECTS O, V$SESSION S, 
V$PROCESS P, V$SQL SQ 
WHERE L.OBJECT_ID = O.OBJECT_ID 
AND L.SESSION_ID = S.SID AND S.PADDR = P.ADDR 
AND S.SQL_ADDRESS = SQ.ADDRESS;

Get current date/time in seconds

I use this:

Math.round(Date.now() / 1000)

No need for new object creation (see doc Date.now())

How to set background color in jquery

You actually got it. Just forgot some quotes.

$(this).css({backgroundColor: 'red'});

or

$(this).css('background-color', 'red');

You don't need to pass over a map/object to set only one property. You can just put pass it as string. Note that if passing an object you cannot use a -. All CSS properties which have such a character are mapped with capital letters.

Reference: .css()

The calling thread cannot access this object because a different thread owns it

For some reason Candide's answer didn't build. It was helpful, though, as it led me to find this, which worked perfectly:

System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke((Action)(() =>
{
   //your code here...
}));

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

JavaScript "cannot read property "bar" of undefined

Just check for it before you pass to your function. So you would pass:

thing.foo ? thing.foo.bar : undefined

SQL query to find third highest salary in company

you can find the third most salary with this query:

SELECT min(salary) 
FROM tblEmployee 
WHERE salary IN (SELECT TOP(3) salary 
                 FROM tblEmployee 
                 ORDER BY salary DESC)

IntelliJ does not show 'Class' when we right click and select 'New'

If you open your module settings (F4) you can nominate which paths contain 'source'. Intellij will then mark these directories in blue and allow you to add classes etc.

In a similar fashion you can highlight test directories for unit tests.

How do I find out if first character of a string is a number?

IN KOTLIN :

Suppose that you have a String like this :

private val phoneNumber="9121111111"

At first you should get the first one :

val firstChar=phoneNumber.slice(0..0)

At second you can check the first char that return a Boolean :

firstChar.isInt() // or isFloat()

Map vs Object in JavaScript

In addition to the other answers, I've found that Maps are more unwieldy and verbose to operate with than objects.

obj[key] += x
// vs.
map.set(map.get(key) + x)

This is important, because shorter code is faster to read, more directly expressive, and better kept in the programmer's head.

Another aspect: because set() returns the map, not the value, it's impossible to chain assignments.

foo = obj[key] = x;  // Does what you expect
foo = map.set(key, x)  // foo !== x; foo === map

Debugging maps is also more painful. Below, you can't actually see what keys are in the map. You'd have to write code to do that.

Good luck evaluating a Map Iterator

Objects can be evaluated by any IDE:

WebStorm evaluating an object

Tomcat 8 is not able to handle get request with '|' in query parameters?

The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.

or edit this parameter on your application.properties

server.tomcat.uri-encoding=utf-8

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A little off topic, but if you want to migrate the data to a new table, and the possible duplicates are in the original table, and the column possibly duplicated is not an id, a GROUP BY will do:

INSERT INTO TABLE_2
(name)
  SELECT t1.name
  FROM TABLE_1 t1
  GROUP BY t1.name

How to set variable from a SQL query?

Select @ModelID =m.modelid 
From   MODELS m
Where  m.areaid = 'South Coast'

In this case if you have two or more results returned then your result is the last record. So be aware of this if you might have two more records returned as you might not see the expected result.

Convert Enum to String

This would work too.

    List<string> names = Enum.GetNames(typeof(MyEnum)).ToList();

Code signing is required for product type 'Application' in SDK 'iOS5.1'

You can get around this by using the simulator if you don't actually need to be deploying to a device. That solved it for me.

CMD: Export all the screen content to a text file

If your batch file is not interactive and you don't need to see it run then this should work.

@echo off
call file.bat >textfile.txt 2>&1

Otherwise use a tee filter. There are many, some not NT compatible. SFK the Swiss Army Knife has a tee feature and is still being developed. Maybe that will work for you.

Explain ExtJS 4 event handling

Just two more things I found helpful to know, even if they are not part of the question, really.

You can use the relayEvents method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load event. It is quite handy when writing custom components that encapsulate several sub-components.

The other way around, i.e. passing on events received by an encapsulating component mycmp to one of its sub-components subcmp, can be done like this

mycmp.on('show' function (mycmp, eOpts)
{
   mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});

How to open an external file from HTML

You may need an extra "/"

<a href="file:///server/directory/file.xlsx">Click me!</a>

reading from app.config file

The reason is simple, your call to ConfigurationSettings.AppSettings is not returning the required config file. Please try any of the following ways:

  • Make sure your app config has the same name as your application's exe file - with the extension .config appended eg MyApp.exe.config
  • OR you can use ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings["StartingMonthColumn"]

Hope this helps

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Append text with .bat

I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.

http://technet.microsoft.com/en-us/library/bb490986.aspx

Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.

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

Below command for files.

scp `find . -maxdepth 1 -name "*.log" \! -name "hs_err_pid2801.log" -type f` root@IP:/tmp/test/

  1. IP will be destination server IP address.
  2. -name "*.log" for include files.
  3. \! -name "hs_err_pid2801.log" for exclude files.
  4. . is current working dir.
  5. -type f for file type.

Below command for directory.

scp -r `find . -maxdepth 1 -name "lo*" \! -name "localhost" -type d` root@IP:/tmp/test/

you can customize above command as per your requirement.

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

Firestore Getting documents id from collection

To obtain the id of the documents in a collection, you must use snapshotChanges()

    this.shirtCollection = afs.collection<Shirt>('shirts');
    // .snapshotChanges() returns a DocumentChangeAction[], which contains
    // a lot of information about "what happened" with each change. If you want to
    // get the data and the id use the map operator.
    this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data() as Shirt;
        const id = a.payload.doc.id;
        return { id, ...data };
      });
    });

Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example

How can I check whether a option already exist in select by JQuery

This evaluates to true if it already exists:

$("#yourSelect option[value='yourValue']").length > 0;

how to set start value as "0" in chartjs?

Please add this option:

//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,

(Reference: Chart.js)

N.B: The original solution I posted was for Highcharts, if you are not using Highcharts then please remove the tag to avoid confusion

How do I check if the mouse is over an element in jQuery?

Just a note about the popular and helpful Arthur Goldsmith answer above: If you're moving your mouse from one element to another in IE (at least until IE 9) you may have some trouble getting this to work correctly if the new element has a transparent background (which it would by default). My workaround was the give the new element a transparent background image.

Transparent ARGB hex value

Transparency is controlled by the alpha channel (AA in #AARRGGBB). Maximal value (255 dec, FF hex) means fully opaque. Minimum value (0 dec, 00 hex) means fully transparent. Values in between are semi-transparent, i.e. the color is mixed with the background color.

To get a fully transparent color set the alpha to zero. RR, GG and BB are irrelevant in this case because no color will be visible. This means #00FFFFFF ("transparent White") is the same color as #00F0F8FF ("transparent AliceBlue"). To keep it simple one chooses black (#00000000) or white (#00FFFFFF) if the color does not matter.

In the table you linked to you'll find Transparent defined as #00FFFFFF.

Error: Java: invalid target release: 11 - IntelliJ IDEA

I added these two lines to build.gradle file

compileJava.options.fork = true
                                              
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk-11.0.8'

and it works

I am using windows and my project based on gradle

my jdk path -> 'C:\Program Files\Java\jdk-11.0.8'

please provide your jdk path

Remove rows not .isin('X')

You can use the DataFrame.select method:

In [1]: df = pd.DataFrame([[1,2],[3,4]], index=['A','B'])

In [2]: df
Out[2]: 
   0  1
A  1  2
B  3  4

In [3]: L = ['A']

In [4]: df.select(lambda x: x in L)
Out[4]: 
   0  1
A  1  2

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

You could compile and link in one command:

gcc file1.c file2.c -o myprogram

And run with:

./myprogram

But to answer the question as asked, simply pass the object files to gcc:

gcc file1.o file2.o -o myprogram

Read data from a text file using Java

Yes, buffering should be used for better performance. Use BufferedReader OR byte[] to store your temp data.

thanks.

remove all variables except functions

Here's a one-liner that removes all objects except for functions:

rm(list = setdiff(ls(), lsf.str()))

It uses setdiff to find the subset of objects in the global environment (as returned by ls()) that don't have mode function (as returned by lsf.str())

How can I perform static code analysis in PHP?

I have tried using php -l and a couple of other tools.

However, the best one in my experience (your mileage may vary, of course) is scheck of pfff toolset. I heard about pfff on Quora (Is there a good PHP lint / static analysis tool?).

You can compile and install it. There are no nice packages (on my Linux Mint Debian system, I had to install the libpcre3-dev, ocaml, libcairo-dev, libgtk-3-dev and libgimp2.0-dev dependencies first) but it should be worth an install.

The results are reported like

$ ~/sw/pfff/scheck ~/code/github/sc/
login-now.php:7:4: CHECK: Unused Local variable $title
go-automatic.php:14:77: CHECK: Use of undeclared variable $goUrl.

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

No provider for Router?

Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):

RouterModule.forRoot([{ path: "", component: LoginComponent}])

Why does JPA have a @Transient annotation?

I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.

Disabled href tag

You can emulate the disabled attribute on a <a> tag.

<a href="link.html" disabled="">Link</a>

a[disabled] {
   pointer-events: none;
   cursor: default;
}

How to display a list inline using Twitter's Bootstrap

While TheBrent's answer is true in general, it does not answer the question of how to do it in the official bootstrap way. The markup for bootstrap is simple:

<ul class="inline">
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Source

http://jsfiddle.net/MgcDU/4602/

css background image in a different folder from css

body

{

background-image: url('../images/bg.jpeg');

}

HTML5 live streaming

You can use a fantastic library name Videojs. You will find more useful informations here. But with quick start you can do something like this:

<link href="//vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
<video 
id="Video" 
class="video-js vjs-default-skin vjs-big-play-centered" 
controls 
preload="none" 
width="auto" 
height="auto" 
poster="poster.jpg" 
data-setup='{"techOrder": ["flash", "html5", "other supported tech"], "nativeControlsForTouch": true, "controlBar": { "muteToggle": false, "volumeControl": false, "timeDivider": false, "durationDisplay": false, "progressControl": false } }'
>
<source src="rtmp://{domain_server}/{publisher}" type='rtmp/mp4'/>
</video>
<script>
var player = videojs('Video');
player.play();
</script>

Sending POST data without form

have a look at the php documentation for theese functions you can send post reqeust using them.

fsockopen()
fputs()

or simply use a class like Zend_Http_Client which is also based on socket-conenctions.

also found a neat example using google...

How does bitshifting work in Java?

00101011 = 43 in decimal

class test {    
    public static void main(String[] args){
       int a= 43;       
       String b= Integer.toBinaryString(a >> 2);        
       System.out.println(b);
    }   
}

Output:

101011 becomes 1010

Output Django queryset as JSON

It didn't work, because QuerySets are not JSON serializable.

1) In case of json.dumps you have to explicitely convert your QuerySet to JSON serializable objects:

class Model(model.Model):
    def as_dict(self):
        return {
            "id": self.id,
            # other stuff
        }

And the serialization:

dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')

2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:

serializers.serialize("json", self.get_queryset())

Read more about it here:

https://docs.djangoproject.com/en/dev/topics/serialization/

Change the mouse pointer using JavaScript

Javascript is pretty good at manipulating css.

 document.body.style.cursor = *cursor-url*;
 //OR
 var elementToChange = document.getElementsByTagName("body")[0];
 elementToChange.style.cursor = "url('cursor url with protocol'), auto";

or with jquery:

$("html").css("cursor: url('cursor url with protocol'), auto");

Firefox will not work unless you specify a default cursor after the imaged one!

other cursor keywords

Also remember that IE6 only supports .cur and .ani cursors.

If cursor doesn't change: In case you are moving the element under the cursor relative to the cursor position (e.g. element dragging) you have to force a redraw on the element:

// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);

working sample:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First jQuery-Enabled Page</title>
<style type="text/css">

div {
    height: 100px;
    width: 1000px;
    background-color: red;
}

</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script></head>
<body>
<div>
hello with a fancy cursor!
</div>
</body>
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.cursor = "url('http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur'), auto";


</script>
</html>

How to increase font size in NeatBeans IDE?

you might also want to change your font size for other parts of the IDE (other than the code).

Just add the parameter --fontsize <size> (default size is 11) to the startup command.

You can put it into the command line when launching IDE. You can also put it into the netbeans.conf file, which is in the /etc subdirectory of NetBeans installation.

Just place it as a last parameter into the netbeans_default_options parameter.

Overcoming "Display forbidden by X-Frame-Options"

Edit .htaccess if you want to remove X-Frame-Options from an entire directory.

And add the line: Header always unset X-Frame-Options

[contents from: Overcoming "Display forbidden by X-Frame-Options"

NSUserDefaults - How to tell if a key exists

The objectForKey: method will return nil if the value does not exist. Here's a simple IF / THEN test that will tell you if the value is nil:

if([[NSUserDefaults standardUserDefaults] objectForKey:@"YOUR_KEY"] != nil) {
    ...
}

error: Error parsing XML: not well-formed (invalid token) ...?

Problem is that you are doing something wrong in XML layout file

android:text=" <- Go Back" // this creates error
android:text="Go Back" // correct way

Targeting .NET Framework 4.5 via Visual Studio 2010

FYI, if you want to create an Installer package in VS2010, unfortunately it only targets .NET 4. To work around this, you have to add NET 4.5 as a launch condition.

Add the following in to the Launch Conditions of the installer (Right click, View, Launch Conditions).

In "Search Target Machine", right click and select "Add Registry Search".

Property: REGISTRYVALUE1
RegKey: Software\Microsoft\NET Framework Setup\NDP\v4\Full
Root: vsdrrHKLM
Value: Release

Add new "Launch Condition":

Condition: REGISTRYVALUE1>="#378389"
InstallUrl: http://www.microsoft.com/en-gb/download/details.aspx?id=30653
Message: Setup requires .NET Framework 4.5 to be installed.

Where:

378389 = .NET Framework 4.5

378675 = .NET Framework 4.5.1 installed with Windows 8.1

378758 = .NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2

379893 = .NET Framework 4.5.2

Launch condition reference: http://msdn.microsoft.com/en-us/library/vstudio/xxyh2e6a(v=vs.100).aspx

Bash script to cd to directory with spaces in pathname

I found the solution below on this page:

x="test\ me"  
eval cd $x

A combination of \ in a double-quoted text constant and an eval before cd makes it work like a charm!

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

For this case word boundary (\b) can also be used instead of start anchor (^) and end anchor ($):

\b\d{1,45}\b

\b is a position between \w and \W (non-word char), or at the beginning or end of a string.

How to comment and uncomment blocks of code in the Office VBA Editor

In the VBA editor, go to View, Toolbars, Customise... or right click on the tool bar and select Customise...

Under the Commands tab, select the Edit menu on the left.

Then approximately two thirds of the way down there's two icons, Comment Block and Uncomment Block.

Drag and drop these onto your toolbar and then you have easy access to highlight a block of code, and comment it out and uncomment with the click of a button!


See GauravSingh's answer if you want to assign keyboard shortcuts.

get all keys set in memcached

Base on @mu ? answer here. I've written a cache dump script.

The script dumps all the content of a memcached server. It's tested with Ubuntu 12.04 and a localhost memcached, so your milage may vary.

#!/usr/bin/env bash

echo 'stats items'  \
| nc localhost 11211  \
| grep -oe ':[0-9]*:'  \
| grep -oe '[0-9]*'  \
| sort  \
| uniq  \
| xargs -L1 -I{} bash -c 'echo "stats cachedump {} 1000" | nc localhost 11211'

What it does, it goes through all the cache slabs and print 1000 entries of each.

Please be aware of certain limits of this script i.e. it may not scale for a 5GB cache server for example. But it's useful for debugging purposes on a local machine.

How to copy a dictionary and only edit the copy

In addition to the other provided solutions, you can use ** to integrate the dictionary into an empty dictionary, e.g.,

shallow_copy_of_other_dict = {**other_dict}.

Now you will have a "shallow" copy of other_dict.

Applied to your example:

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = {**dict1}
>>> dict2
{'key1': 'value1', 'key2': 'value2'}
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key1': 'value1', 'key2': 'value2'}
>>>

Pointer: Difference between shallow and deep copys

How to trigger a click on a link using jQuery

For links this should work:

eval($(selector).attr('href'));

How to color System.out.println output?

This has worked for me:

System.out.println((char)27 + "[31mThis text would show up red" + (char)27 + "[0m");

You need the ending "[37m" to return the color to white (or whatever you were using). If you don't it may make everything that follows "red".

Eclipse IDE for Java - Full Dark Theme

Install a newer version of Eclipse, (Luna Release (4.4.0) or more recent), it include a great Dark theme by default.

Here is a screenshot :

Eclipse Luna 4.4.0 Dark Theme

app.config for a class library

There is no automatic addition of app.config file when you add a class library project to your solution.

To my knowledge, there is no counter indication about doing so manualy. I think this is a common usage.

About log4Net config, you don't have to put the config into app.config, you can have a dedicated conf file in your project as well as an app.config file at the same time.

this link http://logging.apache.org/log4net/release/manual/configuration.html will give you examples about both ways (section in app.config and standalone log4net conf file)

ip address validation in python using regex

Why not use a library function to validate the ip address?

>>> ip="241.1.1.112343434" 
>>> socket.inet_aton(ip)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

Post parameter is always null

The issue is that your action method is expecting a simple type i.e., a string parameter value. What you are providing is an object.

There are 2 solutions to your problem.

  1. Create a simple class with "value" property and then use that class as parameter, in which case Web API model binding will read JSON object from request and bind it to your param object "values" property.

  2. Just pass string value "test", and it will work.

Is there a query language for JSON?

I'd recommend my project I'm working on called jLinq. I'm looking for feedback so I'd be interested in hearing what you think.

If lets you write queries similar to how you would in LINQ...

var results = jLinq.from(records.users)

    //you can join records
    .join(records.locations, "location", "locationId", "id")

    //write queries on the data
    .startsWith("firstname", "j")
    .or("k") //automatically remembers field and command names

    //even query joined items
    .equals("location.state", "TX")

    //and even do custom selections
    .select(function(rec) {
        return {
            fullname : rec.firstname + " " + rec.lastname,
            city : rec.location.city,
            ageInTenYears : (rec.age + 10)
        };
    });

It's fully extensible too!

The documentation is still in progress, but you can still try it online.

How do you extract classes' source code from a dll file?

Use dotPeek

enter image description here

Select the .dll to decompile

enter image description here

That's it

'npm' is not recognized as internal or external command, operable program or batch file

I ran into this problem the other day on my Windows 7 machine. Problem wasn't my path, but I had to use escaped forward slashes instead of backslashes like this:

"scripts": {
    "script": ".\\bin\\script.sh"
}

async at console app in C#?

As a quick and very scoped solution:

Task.Result

Both Task.Result and Task.Wait won't allow to improving scalability when used with I/O, as they will cause the calling thread to stay blocked waiting for the I/O to end.

When you call .Result on an incomplete Task, the thread executing the method has to sit and wait for the task to complete, which blocks the thread from doing any other useful work in the meantime. This negates the benefit of the asynchronous nature of the task.

notasync

Application Installation Failed in Android Studio

Allow or enable "Installation from USB" in the developer options.

When does a process get SIGABRT (signal 6)?

There's another simple cause in case of c++.

std::thread::~thread{
    if((joinable ())
        std::terminate ();
}

i.e. scope of thread ended but you forgot to call either

thread::join();

or

thread::detach();

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

Int to Char in C#

(char)myint;

for example:

Console.WriteLine("(char)122 is {0}", (char)122);

yields:

(char)122 is z

How do I create a link to add an entry to a calendar?

UPDATE (free for personal use):
HTTPS IS NOW SUPPORTED

While my answer below detailing how-to for each service WILL work, IMO it's much easier now to go with a third-party like AddThisEvent [https://addthisevent.com]. It lets you customize lots of options as well as add to Facebook and more. Unfortunately, they've now made it a paid service for anything other than personal use and do enforce this.

I assume there are other third-party solutions like this one, but I can only speak to this one, and it has worked great for us so far.


For an "Add to my Google Calendar", they used to have a code generator form you could use, but have since taken it down. For more details on Google Calendar links, see squarecandy's answer below.

For Outlook, it's a BIT more complicated, but basically you need to create a .vcs file with the event's data, and just make a link to that file. Step-by-step instructions here.

For an iCal link, you could use a PHP class like this one, or follow this page's instructions on how to create an ics file (iCal file).

Using cut command to remove multiple columns

You should be able to continue the sequences directly in your existing -f specification.

To skip both 5 and 7, try:

cut -d, -f-4,6-6,8-

As you're skipping a single sequential column, this can also be written as:

cut -d, -f-4,6,8-

To keep it going, if you wanted to skip 5, 7, and 11, you would use:

cut -d, -f-4,6-6,8-10,12-

To put it into a more-clear perspective, it is easier to visualize when you use starting/ending columns which go on the beginning/end of the sequence list, respectively. For instance, the following will print columns 2 through 20, skipping columns 5 and 11:

cut -d, -f2-4,6-10,12-20

So, this will print "2 through 4", skip 5, "6 through 10", skip 11, and then "12 through 20".

How can I get the content of CKEditor using JQuery?

Now that jQuery adapter exists, this answer needs to be updated:

Say you initiated the editor with $('.ckeditor').ckeditor(opt) then you get the value with $('.ckeditor').val()

How to change a particular element of a C++ STL vector

I prefer

l.at(4)= -1;

while [4] is your index

How to hide a div element depending on Model value? MVC

Your code isn't working, because the hidden attibute is not supported in versions of IE before v11

If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:

*[hidden] { display: none; }

send mail to multiple receiver with HTML mailto

"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."

http://www.sightspecific.com/~mosh/www_faq/multrec.html

For a quick fix to your problem, change your ; to a comma , and eliminate the spaces between email addresses

<a href='mailto:[email protected],[email protected]'>Email Us</a>

How to hide a mobile browser's address bar?

In chrome lastest. Add following css it auto hide address bar (URL bar) when scroll!

html { height: 100vh; }
body { height: 100%; }

And this is why: https://developers.google.com/web/updates/2016/12/url-bar-resizing

Hope to helpful!

Linking a qtDesigner .ui file to python/pyqt?

You can convert your .ui files to an executable python file using the below command..

pyuic4 -x form1.ui > form1.py

Now you can straightaway execute the python file as

python3(whatever version) form1.py

You can import this file and you can use it.

I don't understand -Wl,-rpath -Wl,

One other thing. You may need to specify the -L option as well - eg

-Wl,-rpath,/path/to/foo -L/path/to/foo -lbaz

or you may end up with an error like

ld: cannot find -lbaz

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

Format Date/Time in XAML in Silverlight

For me this worked:

<TextBlock Text="{Binding Date , StringFormat=g}" Width="130"/>

If want to show seconds also using G instead of g :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130"/>

Also if want for changing date type to another like Persian , using Language :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130" Language="fa-IR"/>

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

What is the proper way to check and uncheck a checkbox in HTML5?

In jQuery:

To check the checkbox:

$("#checkboxid").attr("checked","checked");

To uncheck the checkbox:

$("#checkboxid").removeAttr("checked");

The other answers hint at the solution and point you to documentation that after further digging will get you to this answer. Jukka K. Korpela has the reason this is the correct answer, basically I followed his link and then looked up the jQuery docs to get to that result. Just figured I'd save future people who find this article those extra steps.

Setting the JVM via the command line on Windows

You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.

Type java -help for the options. In particular, see:

-version:<value>
              require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
              include/exclude user private JREs in the version search

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.

I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.

For simplicity, here's your same code re-written with a function callback provided by the calling controller:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(callbackFunc) {
        $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
        }).success(function(data){
            // With the data succesfully returned, call our callback
            callbackFunc(data);
        }).error(function(){
            alert("error");
        });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Now, $http actually already returns a $promise, so this can be re-written:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function() {
        // $http() returns a $promise that we can add handlers with .then()
        return $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.

MySQL SELECT statement for the "length" of the field is greater than 1

select * from [tbl] where [link] is not null and len([link]) > 1

For MySQL user:

LENGTH([link]) > 1

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

I've found examples, where PyPy is slower than Python. But: Only on Windows.

C:\Users\User>python -m timeit -n10 -s"from sympy import isprime" "isprime(2**521-1);isprime(2**1279-1)"
10 loops, best of 3: 294 msec per loop

C:\Users\User>pypy -m timeit -n10 -s"from sympy import isprime" "isprime(2**521-1);isprime(2**1279-1)"
10 loops, best of 3: 1.33 sec per loop

So, if you think of PyPy, forget Windows. On Linux, you can achieve awesome accelerations. Example (list all primes between 1 and 1,000,000):

from sympy import sieve
primes = list(sieve.primerange(1, 10**6))

This runs 10(!) times faster on PyPy than on Python. But not on windows. There it is only 3x as fast.

How to Decrease Image Brightness in CSS

The feature you're looking for is filter. It is capable of doing a range of image effects, including brightness:

#myimage {
    filter: brightness(50%);
}

You can find a helpful article about it here: http://www.html5rocks.com/en/tutorials/filters/understanding-css/

An another: http://davidwalsh.name/css-filters

And most importantly, the W3C specs: https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html

Note this is something that's only very recently coming into CSS as a feature. It is available, but a large number of browsers out there won't support it yet, and those that do support it will require a vendor prefix (ie -webkit-filter:, -moz-filter, etc).

It is also possible to do filter effects like this using SVG. SVG support for these effects is well established and widely supported (the CSS filter specs have been taken from the existing SVG specs)

Also note that this is not to be confused with the proprietary filter style available in old versions of IE (although I can predict a problem with the namespace clash when the new style drops its vendor prefix).

If none of that works for you, you could still use the existing opacity feature, but not the way you're thinking: simply create a new element with a solid dark colour, place it on top of your image, and fade it out using opacity. The effect will be of the image behind being darkened.

Finally you can check the browser support of filter here.

ADB Android Device Unauthorized

I was stuck on this for quite some time, and I was able to side-step the issue completely by copying the adbkey from a computer that my phone would connect to.

Can an Android App connect directly to an online mysql database

Yes definitely you can connect to the MySql online database for that you need to create a web service. This web service will provide you access to the MySql database. Then you can easily pull and push data to MySql Database. PHP will be a good option for creating web service its simple to implement. Good luck...

How to enter special characters like "&" in oracle database?

Also you can use concat like this :D

Insert into Table Value(CONCAT('JAVA ',CONCAT('& ', 'Oracle'));

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

How to copy only a single worksheet to another workbook using vba

I have 1 WorkBook("SOURCE") that contains around 20 Sheets. I want to copy only 1 particular sheet to another Workbook("TARGET") using Excel VBA. Please note that the "TARGET" Workbook doen't exist yet. It should be created at runtime.

Another Way

Sub Sample()
    '~~> Change Sheet1 to the relevant sheet
    '~~> This will create a new workbook with the relevant sheet
    ThisWorkbook.Sheets("Sheet1").Copy

    '~~> Save the new workbook
    ActiveWorkbook.SaveAs "C:\Target.xlsx", FileFormat:=51
End Sub

This will automatically create a new workbook called Target.xlsx with the relevant sheet