Programs & Examples On #Mojolicious

Mojolicious is an MVC web framework in Perl.

AngularJS sorting rows by table header

I'm just getting my feet wet with angular, but I found this great tutorial.
Here's a working plunk I put together with credit to Scott Allen and the above tutorial. Click search to display the sortable table.

For each column header you need to make it clickable - ng-click on a link will work. This will set the sortName of the column to sort.

<th>
     <a href="#" ng-click="sortName='name'; sortReverse = !sortReverse">
          <span ng-show="sortName == 'name' && sortReverse" class="glyphicon glyphicon-triangle-bottom"></span>
          <span ng-show="sortName == 'name' && !sortReverse" class="glyphicon glyphicon-triangle-top"></span>
           Name
     </a>
</th>

Then, in the table body you can pipe in that sortName in the orderBy filter orderBy:sortName:sortReverse

<tr ng-repeat="repo in repos | orderBy:sortName:sortReverse | filter:searchRepos">
     <td>{{repo.name}}</td>
     <td class="tag tag-primary">{{repo.stargazers_count | number}}</td>
     <td>{{repo.language}}</td>
</tr>

ORDER BY the IN value list

And here's another solution that works and uses a constant table (http://www.postgresql.org/docs/8.3/interactive/sql-values.html):

SELECT * FROM comments AS c,
(VALUES (1,1),(3,2),(2,3),(4,4) ) AS t (ord_id,ord)
WHERE (c.id IN (1,3,2,4)) AND (c.id = t.ord_id)
ORDER BY ord

But again I'm not sure that this is performant.

I've got a bunch of answers now. Can I get some voting and comments so I know which is the winner!

Thanks All :-)

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

How to define custom configuration variables in rails

In Rails 3.0.5, the following approach worked for me:

In config/environments/development.rb, write

config.custom_config_key = :config_value

The value custom_config_key can then be referenced from other files using

Rails.application.config.custom_config_key

Assert that a method was called in a Python unit test

You can mock out aw.Clear, either manually or using a testing framework like pymox. Manually, you'd do it using something like this:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

Using pymox, you'd do it like this:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)

Soft hyphen in HTML (<wbr> vs. &shy;)

I used soft hyphen unicode character successfully in few desktop and mobile browsers to solve the issue.

The unicode symbol is \u00AD and is pretty easy to insert into Python unicode string like s = u'????? ? ?????? ???????\u00AD??\u00AD??\u00AD??\u00AD???'.

Other solution is to insert the unicode char itself, and the source string will look perfectly ordinary in editors like Sublime Text, Kate, Geany, etc (cursor will feel the invisible symbol though).

Hex editors of in-house tools can automate this task easily.

An easy kludge is to use rare and visible character, like ¦, which is easy to copy and paste, and replace it on soft hyphen using, e.g. frontend script in $(document).ready(...). Source code like s = u'????? ? ?????? ???¦???¦?¦??¦??¦??¦???'.replace('¦', u'\u00AD') is easier to read than s = u'????? ? ?????? ???\u00AD?\u00AD??\u00AD?\u00AD??\u00AD??\u00AD??\u00AD???'.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

In IntelliJ:

  1. Open Project Structure (?;) > Modules > YOUR MODULE -> Language level: set 9, in your case.
  2. Repeat for each module.

screenshot

How to create and write to a txt file using VBA

Use FSO to create the file and write to it.

Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test" 
oFile.Close
Set fso = Nothing
Set oFile = Nothing    

See the documentation here:

Any way to make a WPF textblock selectable?

Use a TextBox with these settings instead to make it read only and to look like a TextBlock control.

<TextBox Background="Transparent"
         BorderThickness="0"
         Text="{Binding Text, Mode=OneWay}"
         IsReadOnly="True"
         TextWrapping="Wrap" />

Trigger event when user scroll to specific element - with jQuery

Inview library triggered event and works well with jquery 1.8 and higher! https://github.com/protonet/jquery.inview

$('div').on('inview', function (event, visible) {
  if (visible == true) {
    // element is now visible in the viewport
  } else {
    // element has gone out of viewport
  }
});

Read this https://remysharp.com/2009/01/26/element-in-view-event-plugin

Count the Number of Tables in a SQL Server Database

USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';

to get table counts

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';

this also works

USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();

How to right-align form input boxes?

Try this:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
    p {
        text-align: right;
    }
    input {
        width: 100px;
    }
    </style>
</head>

<body>
    <form>
        <p>
            <input name="declared_first" value="above" />
        </p>
        <p>
            <input name="declared_second" value="below" />
        </p>
    </form>
</body>
</html>

What's the difference between "Solutions Architect" and "Applications Architect"?

Sounds like the same to me! Though I don't totally disagree with Oli. I'd give a selected few people the Software Architect title if they want it but experience tells me the people who would actually deserve the title of Software Architect usually aint that in to titles.

In Go's http package, how do I get the query string on a POST request?

There are two ways of getting query params:

  1. Using reqeust.URL.Query()
  2. Using request.Form

In second case one has to be careful as body parameters will take precedence over query parameters. A full description about getting query params can be found here

https://golangbyexample.com/net-http-package-get-query-params-golang

How can I check the current status of the GPS receiver?

If you do not need an update on the very instant the fix is lost, you can modify the solution of Stephen Daye in that way, that you have a method that checks if the fix is still present.

So you can just check it whenever you need some GPS data and and you don't need that GpsStatus.Listener.

The "global" variables are:

private Location lastKnownLocation;
private long lastKnownLocationTimeMillis = 0;
private boolean isGpsFix = false;

This is the method that is called within "onLocationChanged()" to remember the update time and the current location. Beside that it updates "isGpsFix":

private void handlePositionResults(Location location) {
        if(location == null) return;

        lastKnownLocation = location;
        lastKnownLocationTimeMillis = SystemClock.elapsedRealtime();

        checkGpsFix(); // optional
    }

That method is called whenever I need to know if there is a GPS fix:

private boolean checkGpsFix(){

    if (SystemClock.elapsedRealtime() - lastKnownLocationTimeMillis < 3000) {
        isGpsFix = true;

    } else {
        isGpsFix = false;
        lastKnownLocation = null;
    }
    return isGpsFix;
}

In my implementation I first run checkGpsFix() and if the result is true I use the variable "lastKnownLocation" as my current position.

Getting started with OpenCV 2.4 and MinGW on Windows 7

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-file-extracting so just double click the file to start installation. Install it in a directory, say C:\.

OpenCV self-extracting

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add C:\opencv\build\x86\mingw\bin directory to your system PATH. This directory contains OpenCV DLLs which is required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced TabEnvironment variables...

You will see a window like shown below:

Add OpenCV DLL directory to system path

On the System Variables section,
select Path (1), click Edit... (2), add C:\opencv\build\x86\mingw\bin (3) then click Ok.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Installing MinGW compiler suite

I highly recommend you to use gcc (GNU Compiler Collection) for compiling your code. gcc is the compiler suite widely available in Linux systems and MinGW is the native port for Windows.

Download the MinGW installer from Sourceforge.net and double click to start installation. Just follow the wizard and select the directory to be installed, say C:\MinGW.

Select directory in MinGW installation

Select "C Compiler" and "C++ Compiler" to be installed.

Select components to be installed

The installer will download some packages from the internet so you have to wait for a while. After the installation finished, add C:\MinGW\bin to your system path using the steps described before.

Add MinGW bin directory to system path

To test if your MinGW installation is success, open a command-line box and type: gcc. If everything is ok, it will display this message:

gcc: fatal error: no input files
compilation terminated

This completes the MinGW installation, now is the time to write your "Hello, World!" program.


3. Write a sample code

Open your text editor and type the code below and save the file to loadimg.cpp.

#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
  Mat im = imread(argc == 2 ? argv[1] : "lena.jpg", 1);
  if (im.empty())
  {
    cout << "Cannot open image!" << endl;
    return -1;
  }

  imshow("image", im);
  waitKey(0);

  return 0;
}

Put lena.jpg or any image you like in the same directory with the file above. Open a command-line box and compile the code above by typing:

g++ -I"C:\opencv\build\include" -L"C:\opencv\build\x86\mingw\lib" loadimg.cpp -lopencv_core243 -lopencv_highgui243 -o loadimg

If it compiles successfully, it will create an executable named loadimg.exe.

Type:

loadimg

To execute the program. Result:

The result of your first OpenCV program


4. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → C:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Cannot find name 'require' after upgrading to Angular4

Add the following line at the top of the file that gives the error:

declare var require: any

Android, How to create option Menu

public class MenuTest extends Activity {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.more_tab_menu, menu);

        // return true so that the menu pop up is opened
        return true; 
    }
}

and don't forget to press the menu button or icon on Emulator or device

max value of integer

The C language definition specifies minimum ranges for various data types. For int, this minimum range is -32767 to 32767, meaning an int must be at least 16 bits wide. An implementation is free to provide a wider int type with a correspondingly wider range. For example, on the SLES 10 development server I work on, the range is -2147483647 to 2137483647.

There are still some systems out there that use 16-bit int types (All The World Is Not A VAX x86), but there are plenty that use 32-bit int types, and maybe a few that use 64-bit.

The C language was designed to run on different architectures. Java was designed to run in a virtual machine that hides those architectural differences.

Auto increment primary key in SQL Server Management Studio 2012

Perhaps I'm missing something but why doesn't this work with the SEQUENCE object? Is this not what you're looking for?

Example:

CREATE SCHEMA blah.
GO

CREATE SEQUENCE blah.blahsequence
START WITH 1
INCREMENT BY 1
NO CYCLE;

CREATE TABLE blah.de_blah_blah
(numbers bigint PRIMARY KEY NOT NULL
......etc

When referencing the squence in say an INSERT command just use:

NEXT VALUE FOR blah.blahsequence

More information and options for SEQUENCE

Renaming files using node.js

You'll need to use fs for that: http://nodejs.org/api/fs.html

And in particular the fs.rename() function:

var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
    if ( err ) console.log('ERROR: ' + err);
});

Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

(This assumes here that your .json file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)

How to get a json string from url?

If you're using .NET 4.5 and want to use async then you can use HttpClient in System.Net.Http:

using (var httpClient = new HttpClient())
{
    var json = await httpClient.GetStringAsync("url");

    // Now parse with JSON.Net
}

My Routes are Returning a 404, How can I Fix Them?

the simple Commands with automatic loads the dependencies

composer dump-autoload

and still getting that your some important files are missing so go here to see whole procedure

https://codingexpertise.blogspot.com/2018/11/laravel-new.html

How do I quickly rename a MySQL database (change schema name)?

Use these few simple commands:

mysqldump -u username -p -v olddatabase > olddbdump.sql
mysqladmin -u username -p create newdatabase
mysql -u username -p newdatabase < olddbdump.sql

Or to reduce I/O use the following as suggested by @Pablo Marin-Garcia:

mysqladmin -u username -p create newdatabase
mysqldump -u username -v olddatabase -p | mysql -u username -p -D newdatabase

How can I make Visual Studio wrap lines at 80 characters?

Tools >> Options >> Text Editor >> All Languages >> General >> Select Word Wrap.

I dont know if you can select a specific number of columns?

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

I've simply toggled "Build Active Architecture Only" to "Yes" in the target's build settings, and it's OK now!

ScriptManager.RegisterStartupScript code not working - why?

You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code

ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);

Android eclipse DDMS - Can't access data/data/ on phone to pull files

To set permission on the data folder and all it's subfolders and files:
Open command prompt from the ADB folder:

>> adb shell
>> su
>> find /data -type d -exec chmod 777 {} \;

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

Is this a console program project or a Windows project? I'm asking because for a Win32 and similar project, the entry point is WinMain().

  1. Right-click the Project (not the Solution) on the left side.
  2. Then click Properties -> Configuration Properties -> Linker -> System

If it says Subsystem Windows your entry point should be WinMain(), i.e.

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
   your code here ...
}

Besides, speaking of the comments. This is a compile (or more precisely a Link) error, not a run-time error. When you start to debug, the compiler needs to make a complete program (not just to compile your module) and that is when the error occurs.

It does not even get to the point being loaded and run.

Setting default value in select drop-down using Angularjs

Problem 1:

The generated HTML you're getting is normal. Apparently it's a feature of Angular to be able to use any kind of object as value for a select. Angular does the mapping between the HTML option-value and the value in the ng-model. Also see Umur's comment in this question: How do I set the value property in AngularJS' ng-options?

Problem 2:

Make sure you're using the following ng-options:

<select ng-model="object.item" ng-options="item.id as item.name for item in list" />

And put this in your controller to select a default value:

object.item = 4

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

C# how to use enum with switch

The correct answer is already given, nevertheless here is the better way (than switch):

private Dictionary<Operator, Func<int, int, double>> operators =
    new Dictionary<Operator, Func<int, int, double>>
    {
        { Operator.PLUS, ( a, b ) => a + b },
        { Operator.MINUS, ( a, b ) => a - b },
        { Operator.MULTIPLY, ( a, b ) => a * b },
        { Operator.DIVIDE ( a, b ) => (double)a / b },
    };

public double Calculate( int left, int right, Operator op )
{
    return operators.ContainsKey( op ) ? operators[ op ]( left, right ) : 0.0;
}

Child inside parent with min-height: 100% not inheriting height

Although display: flex; has been suggested here, consider using display: grid; now that it's widely supported. By default, the only child of a grid will entirely fill its parent.

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0; /* Don't forget Safari */_x000D_
}_x000D_
_x000D_
#containment {_x000D_
  display: grid;_x000D_
  min-height: 100%;_x000D_
  background: pink;_x000D_
}_x000D_
_x000D_
#containment-shadow-left {_x000D_
  background: aqua;_x000D_
}
_x000D_
_x000D_
_x000D_

Copying Code from Inspect Element in Google Chrome

you dont have to do that in the Google chrome. Use the Internet explorer it offers the option to copy the css associated and after you copy and paste select the style and put that into another file .css to call into that html which you have created. Hope this will solve you problem than anything else:)

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

If you don't want to use a separate JS library to create a custom control for that, you could use two confirm dialogs to do the checks:

if (confirm("Are you sure you want to quit?") ) {
    if (confirm("Save your work before leaving?") ) {
        // code here for save then leave (Yes)
    } else {
        //code here for no save but leave (No)
    }
} else {
    //code here for don't leave (Cancel)
}

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

How to use 'find' to search for files created on a specific date?

You can't. The -c switch tells you when the permissions were last changed, -a tests the most recent access time, and -m tests the modification time. The filesystem used by most flavors of Linux (ext3) doesn't support a "creation time" record. Sorry!

How do I convert a decimal to an int in C#?

No answer seems to deal with the OverflowException/UnderflowException that comes from trying to convert a decimal that is outside the range of int.

int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));

This solution will return the maximum or minimum int value possible if the decimal value is outside the int range. You might want to add some rounding with Math.Round, Math.Ceiling or Math.Floor for when the value is inside the int range.

How does Git handle symbolic links?

You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?

To find out, first, make a symbolic link:

$ ln -s /path/referenced/by/symlink symlink

Git doesn't know about this file yet. git ls-files lets you inspect your index (-s prints stat-like output):

$ git ls-files -s ./symlink
[nothing]

Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.

$ git add ./symlink

So, what was added?

$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0       symlink

The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file:

$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink

(Note 120000 is the mode listed in ls-files output. It would be something like 100644 for a regular file.)

But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks config. From man git-config:

core.symlinks

If false, symbolic links are checked out as small plain files that contain the link text.

So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks config.

Either way, the data referenced by the symlink is not stored in the repository.

Detecting iOS / Android Operating system

This issue has already been resolved here : What is the best way to detect a mobile device in jQuery?.

On the accepted answer, they basically test if it's an iPhone, an iPod, an Android device or whatever to return true. Just keep the ones you want for instance if( /Android/i.test(navigator.userAgent) ) { // some code.. } will return true only for Android user-agents.

However, user-agents are not really reliable since they can be changed. The best thing is still to develop something universal for all mobile platforms.

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

Storyboard:

Just uncheck: Adjust Scroll View Insets in View Controller's options

enter image description here

Code:

self.automaticallyAdjustsScrollViewInsets = false

Serialize an object to string

I was unable to use the JSONConvert method suggested by xhafan

In .Net 4.5 even after adding the "System.Web.Extensions" assembly reference I was still unable to access the JSONConvert.

However, once you add the reference you can get the same string print out using:

JavaScriptSerializer js = new JavaScriptSerializer();
string jsonstring = js.Serialize(yourClassObject);

How do you uninstall all dependencies listed in package.json (NPM)?

If using Bash, just switch into the folder that has your package.json file and run the following:

for package in `ls node_modules`; do npm uninstall $package; done;

In the case of globally-installed packages, switch into your %appdata%/npm folder (if on Windows) and run the same command.

EDIT: This command breaks with npm 3.3.6 (Node 5.0). I'm now using the following Bash command, which I've mapped to npm_uninstall_all in my .bashrc file:

npm uninstall `ls -1 node_modules | tr '/\n' ' '`

Added bonus? it's way faster!

https://github.com/npm/npm/issues/10187

golang why don't we have a set datastructure

Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).

Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool (and set the value to true for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key] to check for presence.

Fragment Inside Fragment

That may help those who works on Kotlin you can use extension function so create a kotlin file let's say "util.kt" and add this piece of code

fun Fragment.addChildFragment(fragment: Fragment, frameId: Int) {

    val transaction = childFragmentManager.beginTransaction()
    transaction.replace(frameId, fragment).commit()
}

Let's say this is the class of the child

class InputFieldPresentation: Fragment()
{
    var views: View? = null
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        views = inflater!!.inflate(R.layout.input_field_frag, container, false)
        return views
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ...
    }
    ...
}

Now you can add the children to the father fragment like this

 FatherPresentation:Fragment()
{
  ...

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val fieldFragment= InputFieldPresentation()
        addChildFragment(fieldFragment,R.id.fragmet_field)
    }
...
}

where R.id.fragmet_field is the id of the layout which will contain the fragment.This lyout is inside the father fragment of course. Here is an example

father_fragment.xml:

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >

    ...

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:id="@+id/fragmet_field"
            android:orientation="vertical"
            >
        </LinearLayout>
    ...

    </LinearLayout>

Why aren't programs written in Assembly more often?

Because it's always that way: time pass and good things pass away too :(

But when you write asm code it's totally different feeling than when you code high-level langs, though you know it's much less productive. It's like you're a painter: you are free to draw anything you like the way you like with absolutely no restrictions(well, only by CPU features)... That is why I love it. It's a pity this language goes away. But while somebody still remembers it and codes it, it will never die!

Why are my CSS3 media queries not working on mobile devices?

Well, in my case, the px after the width value was missing ... Interestingly, the W3C validator did not even notice this error, just silently ignored the definition.

Parse strings to double with comma and point

You can check if the string contains a decimal point using

string s="";

        if (s.Contains(','))
        { 
        //treat as double how you wish
        }

and then treat that as a decimal, otherwise just pass the non-double value along.

Can I get the name of the current controller in the view?

If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head> tag

  <%= stylesheet_link_tag  controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>

Also, to specify the same class CSS on a different controller
Add this line in the body of application.html.erb

  <body class="<%= controller.controller_name %>-<%= controller.action_name %>">

So, now for example I would like to change the p tag in 'home' controller and 'index' action. Inside index.scss file adds.

.nameOfController-nameOfAction <tag> { }

 .home-index p {
        color:red !important;
      }

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

Trigger a button click with JavaScript on the Enter key in a text box

One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:

<form onsubmit="Search();" action="javascript:void(0);">
    <input type="text" id="searchCriteria" placeholder="Search Criteria"/>
    <input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>

Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.

Eclipse error: "Editor does not contain a main type"

Did you import the packages for the file reading stuff.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

also here

cfiltering(numberOfUsers, numberOfMovies);

Are you trying to create an object or calling a method?

also another thing:

user_movie_matrix[userNo][movieNo]=rating;

you are assigning a value to a member of an instance as if it was a static variable also remove the Th in

private int user_movie_matrix[][];Th

Hope this helps.

What's the difference between <b> and <strong>, <i> and <em>?

We use the <strong> tag for text which has high priority for SEO purposes like product name, company name etc, while <b> simple makes it bold.

Similarly, we use <em> for text which has high priority for SEO, while <i> to make the text simply italic.

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

How to write both h1 and h2 in the same line?

In many cases,

display:inline;

is enough.

But in some cases, you have to add following:

clear:none;

C++ alignment when printing cout <<

See also: Which C I/O library should be used in C++ code?

struct Item
{
   std::string     artist;
   std::string     c;
   integer         price;  // in cents (as floating point is not acurate)
   std::string     Genre;
   integer         disc;
   integer         sale;
   integer         tax;
};

std::cout << "Sales Report for September 15, 2010\n"
          << "Artist  Title   Price   Genre   Disc    Sale    Tax Cash\n";
FOREACH(Item loop,data)
{
    fprintf(stdout,"%8s%8s%8.2f%7s%1s%8.2f%8.2f\n",
          , loop.artist
          , loop.title
          , loop.price / 100.0
          , loop.Genre
          , loop.disc , "%"
          , loop.sale / 100.0
          , loop.tax / 100.0);

   // or

    std::cout << std::setw(8) << loop.artist
              << std::setw(8) << loop.title
              << std::setw(8) << fixed << setprecision(2) << loop.price / 100.0
              << std::setw(8) << loop.Genre
              << std::setw(7) << loop.disc << std::setw(1) << "%"
              << std::setw(8) << fixed << setprecision(2) << loop.sale / 100.0
              << std::setw(8) << fixed << setprecision(2) << loop.tax / 100.0
              << "\n";

    // or

    std::cout << boost::format("%8s%8s%8.2f%7s%1s%8.2f%8.2f\n")
              % loop.artist
              % loop.title
              % loop.price / 100.0
              % loop.Genre
              % loop.disc % "%"
              % loop.sale / 100.0
              % loop.tax / 100.0;
}

Find and replace with sed in directory and sub directories

This worked for me:

find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;

Tokenizing strings in C

strtok can be very dangerous. It is not thread safe. Its intended use is to be called over and over in a loop, passing in the output from the previous call. The strtok function has an internal variable that stores the state of the strtok call. This state is not unique to each thread - it is global. If any other code uses strtok in another thread, you get problems. Not the kind of problems you want to track down either!

I'd recommend looking for a regex implementation, or using sscanf to pull apart the string.

Try this:

char strprint[256];
char text[256];
strcpy(text, "My string to test");
while ( sscanf( text, "%s %s", strprint, text) > 0 ) {
   printf("token: %s\n", strprint);
}

Note: The 'text' string is destroyed as it's separated. This may not be the preferred behaviour =)

How do you exit from a void function in C++?

void foo() {
  /* do some stuff */
  if (!condition) {
    return;
  }
}

You can just use the return keyword just like you would in any other function.

Angular 4 - Observable catch error

You should be using below

return Observable.throw(error || 'Internal Server error');

Import the throw operator using the below line

import 'rxjs/add/observable/throw';

ASP.NET MVC - Getting QueryString values

You can always use Request.QueryString collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.

error: Libtool library used but 'LIBTOOL' is undefined

In my case on macOS I solved it with:

brew link libtool

postgreSQL - psql \i : how to execute script in a given path

i did try this and its working in windows machine to run a sql file on a specific schema.

psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql

Passing parameter via url to sql server reporting service

I had the same question and more, and though this thread is old, it is still a good one, so in summary for SSRS 2008R2 I found...

Situations

  1. You want to use a value from a URL to look up data
  2. You want to display a parameter from a URL in a report
  3. You want to pass a parameter from one report to another report

Actions

If applicable, be sure to replace Reports/Pages/Report.aspx?ItemPath= with ReportServer?. In other words: Instead of this:

http://server/Reports/Pages/Report.aspx?ItemPath=/ReportFolder/ReportSubfolder/ReportName

Use this syntax:

http://server/ReportServer?/ReportFolder/ReportSubfolder/ReportName

Add parameter(s) to the report and set as hidden (or visible if user action allowed, though keep in mind that while the report parameter will change, the URL will not change based on an updated entry).

Attach parameters to URL with &ParameterName=Value

Parameters can be referenced or displayed in report using @ParameterName, whether they're set in the report or in the URL

To hide the toolbar where parameters are displayed, add &rc:Toolbar=false to the URL (reference)

Putting that all together, you can run a URL with embedded values, or call this as an action from one report and read by another report:

http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID=ABC123&rc:Toolbar=false

In report dataset properties query: SELECT stuff FROM view WHERE User = @UserID

In report, set expression value to [UserID] (or =Fields!UserID.Value)

Keep in mind that if a report has multiple parameters, you might need to include all parameters in the URL, even if blank, depending on how your dataset query is written.

To pass a parameter using Action = Go to URL, set expression to:

="http://server.domain.com/ReportServer?/ReportFolder1/ReportSubfolder1/ReportName&UserID="
 &Fields!UserID.Value 
 &"&rc:Toolbar=false"
 &"&rs:ClearSession=True"

Be sure to have a space after an expression if followed by & (a line break is isn't enough). No space is required before an expression. This method can pass a parameter but does not hide it as it is visible in the URL.

If you don't include &rs:ClearSession=True then the report won't refresh until browser session cache is cleared.

To pass a parameter using Action = Go to report:

  • Specify the report
  • Add parameter(s) to run the report
  • Add parameter(s) you wish to pass (the parameters need to be defined in the destination report, so to my knowledge you can't use URL-specific commands such as rc:toolbar using this method); however, I suppose it would be possible to read or set the Prompt User checkbox, as seen in reporting sever parameters, through custom code in the report.)

For reference, / = %2f

Parsing JSON array with PHP foreach

You need to tell it which index in data to use, or double loop through all.

E.g., to get the values in the 4th index in the outside array.:

foreach($user->data[3]->values as $values)
{
     echo $values->value . "\n";
}

To go through all:

foreach($user->data as $mydata)
{
    foreach($mydata->values as $values) {
        echo $values->value . "\n";
    }

}   

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

PHP compare time

To see of the curent time is greater or equal to 14:08:10 do this:

if (time() >= strtotime("14:08:10")) {
  echo "ok";
}

Depending on your input sources, make sure to account for timezone.

See PHP time() and PHP strtotime()

How to use XPath contains() here?

//ul[@class="featureList" and li//text()[contains(., "Model")]]

Table and Index size in SQL Server

Here is more compact version of the most successful answer:

create table #tbl(
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)
)

exec sp_msforeachtable 'insert into #tbl exec sp_spaceused [?]'

select * from #tbl
    order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #tbl

Java - How do I make a String array with values?

You want to initialize an array. (For more info - Tutorial)

int []ar={11,22,33};

String []stringAr={"One","Two","Three"};

From the JLS

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

Using group by and having clause

1.Get supplier numbers and names for suppliers of parts supplied to at least two different projects.

 SELECT S.SID, S.NAME
 FROM SUPPLIES SP
 JOIN SUPPLIER S
 ON SP.SID = S.SID
 WHERE PID IN
 (SELECT PID FROM SUPPPLIES GROUP BY PID, JID HAVING COUNT(*) >= 2)

I am not slear about your second question

CSS display:inline property with list-style-image: property on <li> tags

I would suggest not to use list-style-image, as it behaves quite differently in different browsers, especially the image position

instead, you can use something like this

ol.widgets,
ol.widgets li { list-style: none; }
ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; }

it works in all browsers and would give you the identical result in different browsers.

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

Start you activity with StartActivityForResult and while you logout set your result and according to you result finish your activity

intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityForResult(intent, BACK_SCREEN);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case BACK_SCREEN:
        if (resultCode == REFRESH) {
            setResult(REFRESH);
            finish();
        }
        break;
    }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();

        alertDialog
                .setTitle((String) getResources().getText(R.string.home));
        alertDialog.setMessage((String) getResources().getText(
                R.string.gotoHome));
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {

                        setResult(REFRESH);
                        finish();
                    }

                });

        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                    }
                });
        alertDialog.show();
        return true;
    } else
        return super.onKeyDown(keyCode, event);

}

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

How to set the height of table header in UITableView?

Use table view default property :

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35.0;
}

Thanks

Calculating frames per second in a game

In Typescript, I use this algorithm to calculate framerate and frametime averages:

let getTime = () => {
    return new Date().getTime();
} 

let frames: any[] = [];
let previousTime = getTime();
let framerate:number = 0;
let frametime:number = 0;

let updateStats = (samples:number=60) => {
    samples = Math.max(samples, 1) >> 0;

    if (frames.length === samples) {
        let currentTime: number = getTime() - previousTime;

        frametime = currentTime / samples;
        framerate = 1000 * samples / currentTime;

        previousTime = getTime();

        frames = [];
    }

    frames.push(1);
}

usage:

statsUpdate();

// Print
stats.innerHTML = Math.round(framerate) + ' FPS ' + frametime.toFixed(2) + ' ms';

Tip: If samples is 1, the result is real-time framerate and frametime.

Differences between cookies and sessions?

Session in Asp.net:

1.Maintains the data accross all over the application.

2.Persists the data if current session is alive. If we need some data to accessible from multiple controllers acitons and views the session is the way to store and retreive data.

3.Sessions are server side files that contains user information. [Sessions are unique identifier that maps them to specific users]

Translating that to Web Servers: The server will store the pertinent information in the session object, and create a session ID which it will send back to the client in a cookie. When the client sends back the cookie, the server can simply look up the session object using the ID. So, if you delete the cookie, the session will be lost.

Convert Python dict into a dataframe

This is how it worked for me :

df= pd.DataFrame([d.keys(), d.values()]).T
df.columns= ['keys', 'values']  # call them whatever you like

I hope this helps

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

New to MongoDB Can not run command mongo

You just need to create directory in C:. as C:\data\db\

Now just start mongoDB:

C:\Users\gi.gupta>"c:\Program Files\MongoDB\Server\3.2\bin\mongod.exe"
2016-05-03T10:49:30.412+0530 I CONTROL  [main] Hotfix KB2731284 or later update is not installed, will zero-out data files
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] MongoDB starting : pid=7904 port=27017 dbpath=C:\data\db\ 64-bit host=GLTPM-W036
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] db version v3.2.6
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] git version: 05552b562c7a0b3143a729aaa0838e558dc49b25
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1p-fips 9 Jul 2015
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] modules: none
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] build environment:
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten]     distarch: x86_64
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten]     target_arch: x86_64
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] options: {}
2016-05-03T10:49:30.427+0530 I -        [initandlisten] Detected data files in C:\data\db\ created by the 'wiredTiger' storage engine, so setting the active storage engine to
2016-05-03T10:49:30.429+0530 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=1G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(f
chive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2016-05-03T10:49:30.998+0530 I NETWORK  [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2016-05-03T10:49:30.998+0530 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/diagnostic.data'
2016-05-03T10:49:31.000+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2016-05-03T10:49:40.766+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:57504 #1 (1 connection now open)

It will then run as service in background.

Python MySQLdb TypeError: not all arguments converted during string formatting

The accepted answer by @kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.

There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported

cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')

but the 1.2.5 versions require

cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])

as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.

The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.

If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:

$ pip install MySQL-python==1.2.3

How to define dimens.xml for every different screen size in android?

You have to create Different values folder for different screens . Like

values-sw720dp          10.1” tablet 1280x800 mdpi

values-sw600dp          7.0”  tablet 1024x600 mdpi

values-sw480dp          5.4”  480x854 mdpi 
values-sw480dp          5.1”  480x800 mdpi 

values-xxhdpi           5.5"  1080x1920 xxhdpi
values-xxxhdpi           5.5" 1440x2560 xxxhdpi

values-xhdpi            4.7”   1280x720 xhdpi 
values-xhdpi            4.65”  720x1280 xhdpi 

values-hdpi             4.0” 480x800 hdpi
values-hdpi             3.7” 480x854 hdpi

values-mdpi             3.2” 320x480 mdpi

values-ldpi             3.4” 240x432 ldpi
values-ldpi             3.3” 240x400 ldpi
values-ldpi             2.7” 240x320 ldpi

enter image description here

For more information you may visit here

Different values folders in android

http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html

Edited By @humblerookie

You can make use of Android Studio plugin called Dimenify to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.

Maven – Always download sources and javadocs

To follow up on the answer from kevinarpe this does both sources and Javadocs:

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.1.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>sources</goal>
                            <goal>resolve</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <classifier>javadoc</classifier>
                </configuration>
            </plugin>
        </plugins>
    </build>

How to measure time taken between lines of code in python?

With a help of a small convenience class, you can measure time spent in indented lines like this:

with CodeTimer():
   line_to_measure()
   another_line()
   # etc...

Which will show the following after the indented line(s) finishes executing:

Code block took: x.xxx ms

UPDATE: You can now get the class with pip install linetimer and then from linetimer import CodeTimer. See this GitHub project.

The code for above class:

import timeit

class CodeTimer:
    def __init__(self, name=None):
        self.name = " '"  + name + "'" if name else ''

    def __enter__(self):
        self.start = timeit.default_timer()

    def __exit__(self, exc_type, exc_value, traceback):
        self.took = (timeit.default_timer() - self.start) * 1000.0
        print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')

You could then name the code blocks you want to measure:

with CodeTimer('loop 1'):
   for i in range(100000):
      pass

with CodeTimer('loop 2'):
   for i in range(100000):
      pass

Code block 'loop 1' took: 4.991 ms
Code block 'loop 2' took: 3.666 ms

And nest them:

with CodeTimer('Outer'):
   for i in range(100000):
      pass

   with CodeTimer('Inner'):
      for i in range(100000):
         pass

   for i in range(100000):
      pass

Code block 'Inner' took: 2.382 ms
Code block 'Outer' took: 10.466 ms

Regarding timeit.default_timer(), it uses the best timer based on OS and Python version, see this answer.

What is the naming convention in Python for variable and function names?

Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head.

I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have SomeClass.doSomething() than SomeClass.do_something(). If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.

How do I copy folder with files to another folder in Unix/Linux?

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you're copying is called dir1 and you want to copy it to your /home/Pictures folder:

cp -r dir1/ ~/Pictures/

Linux is case-sensitive and also needs the / after each directory to know that it isn't a file. ~ is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd.

When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:

man [insert command here]

at a terminal prompt.

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

Ajax request returns 200 OK, but an error event is fired instead of success

I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:

$.ajax({
    type: 'POST',
    url: 'Jqueryoperation.aspx?Operation=DeleteRow',
    contentType: 'application/json; charset=utf-8',
    data: json,
    dataType: 'text json',
    cache: false,
    success: AjaxSucceeded,
    error: AjaxFailed
});

Initialize 2D array

You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:

for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
    table[row][col] = (char) ('1' + row * 3 + col);

In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Or if you're planning to expand the algorithm, the previous code would prove more, efficient.

jquery stop child triggering parent event

Better way by using on() with chaining like,

$(document).ready(function(){
    $(".header").on('click',function(){
        $(this).children(".children").toggle();
    }).on('click','a',function(e) {
        e.stopPropagation();
   });
});

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

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

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

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

UICollectionView current visible cell index

try this, it works. (in the example below i have 3 cells for example.)

    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
    let visibleRect = CGRect(origin: self.collectionView.contentOffset, size: self.collectionView.bounds.size)
    let visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect))
    let visibleIndexPath = self.collectionView.indexPathForItemAtPoint(visiblePoint)
    if let v = visibleIndexPath {
        switch v.item {
        case 0: setImageDescription()
            break
        case 1: setImageConditions()
            break
        case 2: setImageResults()
            break
        default: break
        }
    }

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Your json string is wrapped within square brackets ([]), hence it is interpreted as array instead of single RetrieveMultipleResponse object. Therefore, you need to deserialize it to type collection of RetrieveMultipleResponse, for example :

var objResponse1 = 
    JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);

How to convert timestamp to datetime in MySQL?

To answer Janus Troelsen comment

Use UNIX_TIMESTAMP instead of TIMESTAMP

SELECT from_unixtime( UNIX_TIMESTAMP(  "2011-12-01 22:01:23.048" ) )

The TIMESTAMP function returns a Date or a DateTime and not a timestamp, while UNIX_TIMESTAMP returns a unix timestamp

How do I check if a string contains a specific word?

Here is a little utility function that is useful in situations like this

// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
    return strpos($haystack, $needle) !== false;
}

How to get an object's methods?

the best way is:

let methods = Object.getOwnPropertyNames(yourobject);
console.log(methods)

use 'let' only in es6, use 'var' instead

Split string into array of character strings

Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt method.

Combined with an ArrayList<String> for example you can get your array of individual characters.

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

wait also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in background. Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID.

# run processes and store pids in array
for i in $n_procs; do
    ./procs[${i}] &
    pids[${i}]=$!
done

# wait for all pids
for pid in ${pids[*]}; do
    wait $pid
done

How do I set a program to launch at startup

Here is all way to add your program to startup for Windows Vista, 7, 8, 10

  • File path

C:\Users\Bureau Briffault\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup (Visible from task manager, Running on current user login success, No admin privileges required)

C:\Users\Default\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup (Visible from task manager, Running on all user login success, Admin privileges required)


  • Registry path

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run (Visible from task manager, Running on current user login success, No admin privileges required)

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce (Not visible from task manager, Running on current user login success, Running for one login time, No admin privileges required)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run (Visible from task manager, Running on all user login success, Admin privileges required)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce (Not visible from task manager, Running on all user login success, Running for one login time, Admin privileges required)


  • Task scheduler

Microsoft.Win32.Taskscheduler.dll (Not visible from task manager, Running on windows boot, Running as admin, Admin privileges required)

How to add meta tag in JavaScript

Try

_x000D_
_x000D_
document.head.innerHTML += '<meta http-equiv="X-UA-..." content="IE=edge">'
_x000D_
_x000D_
_x000D_

Opening a new tab to read a PDF file

Will open your pdf in a new tab with pdf viewer and can download too

<a className=""
   href="/project_path_to_your_pdf_asset/failename.pdf"
   target="_blank"
>
   View PDF
</a>

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

remove double quotes from Json return data using Jquery

For niche needs when you know your data like your example ... this works :

JSON.parse(this_is_double_quoted);

JSON.parse("House");  // for example

Get the POST request body from HttpServletRequest

If the request body is empty, then it simply means that it's already been consumed beforehand. For example, by a request.getParameter(), getParameterValues() or getParameterMap() call. Just remove the lines doing those calls from your code.

How to get elements with multiple classes

AND (both classes)

var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");

OR (at least one class)

var list = document.querySelectorAll(".class1,.class2");

XOR (one class but not the other)

var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");

NAND (not both classes)

var list = document.querySelectorAll(":not(.class1),:not(.class2)");

NOR (not any of the two classes)

var list = document.querySelectorAll(":not(.class1):not(.class2)");

detect back button click in browser

I'm detecting the back button by this way:

window.onload = function () {
if (typeof history.pushState === "function") {
    history.pushState("jibberish", null, null);
    window.onpopstate = function () {
        history.pushState('newjibberish', null, null);
        // Handle the back (or forward) buttons here
        // Will NOT handle refresh, use onbeforeunload for this.
    };
}

It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.

if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null); 
window.onpopstate = function () {
    if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null ) 
    {
        addCookie('cookieChrome',1, 1440);      
    } 
    else 
    {
        history.pushState('newjibberish', null, null);  
    }
};

}

AND VERY IMPORTANT, history.pushState("jibberish", null, null); duplicates the browser history.

Some one knows who can i fix it?

SQL SELECT everything after a certain character

Try this in MySQL.

right(field,((CHAR_LENGTH(field))-(InStr(field,','))))

Can CSS detect the number of children an element has?

yes we can do this using nth-child like so

div:nth-child(n + 8) {
    background: red;
}

This will make the 8th div child onwards become red. Hope this helps...

Also, if someone ever says "hey, they can't be done with styled using css, use JS!!!" doubt them immediately. CSS is extremely flexible nowadays

Example :: http://jsfiddle.net/uWrLE/1/

In the example the first 7 children are blue, then 8 onwards are red...

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

Displaying the build date

Add below to pre-build event command line:

echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt"

Add this file as resource, now you have 'BuildDate' string in your resources.

To create resources, see How to create and use resources in .NET.

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Update: For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {    
    compile 'joda-time:joda-time:2.9.4'
}

How do you get a directory listing in C?

There is no standard C (or C++) way to enumerate files in a directory.

Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.

Input button target="_blank" isn't causing the link to load in a new window/tab

Please try this it's working for me

onClick="window.open('http://www.facebook.com/','facebook')"

<button type="button" class="btn btn-default btn-social" onClick="window.open('http://www.facebook.com/','facebook')">
          <i class="fa fa-facebook" aria-hidden="true"></i>
</button>

Define constant variables in C++ header

It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.

In foo.cc:

#include <cstdio>               // for puts

#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"

int main(int argc, const char* argv[])
{
  puts("Hello!");
  bar();
  zoo();
  puts(Message::third);
  return 0;
}

In messages.hh:

#ifndef MESSAGES_HH
#define MESSAGES_HH

namespace Message {
  char const * const first = "Yes, this is the first message!";
  char const * const second = "This is the second message.";
  char const * const third = "Message #3.";
};

#endif

In bar.cc:

#include "messages.hh"
#include <cstdio>

void bar(void)
{
  puts("Wow!");
  printf("bar: %s\n", Message::first);
}

In zoo.cc:

#include <cstdio>
#include "messages.hh"

void zoo(void)
{
  printf("zoo: %s\n", Message::second);
}

In bar.hh:

#ifndef BAR_HH
#define BAR_HH

#include "messages.hh"

void bar(void);

#endif

In zoo.hh:

#ifndef ZOO_HH
#define ZOO_HH

#include "messages.hh"

void zoo(void);

#endif

This yields the following output:

Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.

The data type char const * const means a constant pointer to an array of constant characters. The first const is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the consts, but then the source code is less portable.

Error converting data types when importing from Excel to SQL Server 2008

SSIS doesn't implicitly convert data types, so you need to do it explicitly. The Excel connection manager can only handle a few data types and it tries to make a best guess based on the first few rows of the file. This is fully documented in the SSIS documentation.

You have several options:

  • Change your destination data type to float
  • Load to a 'staging' table with data type float using the Import Wizard and then INSERT into the real destination table using CAST or CONVERT to convert the data
  • Create an SSIS package and use the Data Conversion transformation to convert the data

You might also want to note the comments in the Import Wizard documentation about data type mappings.

Generate MD5 hash string with T-SQL

Use HashBytes

SELECT HashBytes('MD5', '[email protected]')

That will give you 0xF53BD08920E5D25809DF2563EF9C52B6

-

SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', '[email protected]'),2)

That will give you F53BD08920E5D25809DF2563EF9C52B6

Importing text file into excel sheet

I think my answer to my own question here is the simplest solution to what you are trying to do:

  1. Select the cell where the first line of text from the file should be.

  2. Use the Data/Get External Data/From File dialog to select the text file to import.

  3. Format the imported text as required.

  4. In the Import Data dialog that opens, click on Properties...

  5. Uncheck the Prompt for file name on refresh box.

  6. Whenever the external file changes, click the Data/Get External Data/Refresh All button.

Note: in your case, you should probably want to skip step #5.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

Nobody seems to be explaining the difference between an array and an object.

[] is declaring an array.

{} is declaring an object.

An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object" to further show you that an array is an object.

The additional features consist of a magic .length property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push(), .pop(), .slice(), .splice(), etc... You can see a list of array methods here.

An object gives you the ability to associate a property name with a value as in:

var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo);      // shows 3
console.log(x.whatever); // shows 10

Object properties can be accessed either via the x.foo syntax or via the array-like syntax x["foo"]. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar] and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo syntax.

A property name can be any string value.


An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0 and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort() or to add or remove things from the list.

iOS - UIImageView - how to handle UIImage image orientation

extension UIImage {
    func fixImageOrientation() -> UIImage {
        UIGraphicsBeginImageContext(self.size)
        self.draw(at: .zero)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? self
    }
}
  1. Create extension like top example.
  2. Call it: imageView.image?.fixImageOrientation() or UIImage(named: "someImage").fixImageOrientation()

  3. Good luck all!

html form - make inputs appear on the same line

Wrap your multiple form elements in a div with a class that uses

display: table 

Inside that div, wrap each label and input in divs with a class that uses

display: table-cell

Stay away from floats!

Reference

Call one constructor from another

If what you want can't be achieved satisfactorily without having the initialization in its own method (e.g. because you want to do too much before the initialization code, or wrap it in a try-finally, or whatever) you can have any or all constructors pass the readonly variables by reference to an initialization routine, which will then be able to manipulate them at will.

public class Sample
{
    private readonly int _intField;
    public int IntProperty => _intField; 

    private void setupStuff(ref int intField, int newValue) => intField = newValue;

    public Sample(string theIntAsString)
    {
        int i = int.Parse(theIntAsString);
        setupStuff(ref _intField,i);
    }

    public Sample(int theInt) => setupStuff(ref _intField, theInt);
}

Is there a limit to the length of a GET request?

As Requested By User Erickson, I Post My comment As Answer:

I have done some more testing with IE8, IE9, FF14, Opera11, Chrome20 and Tomcat 6.0.32 (fresh installation), Jersey 1.13 on the server side. I used the jQuery function $.getJson and JSONP. Results: All Browsers allowed up to around 5400 chars. FF and IE9 did up to around 6200 chars. Everything above returned "400 Bad request". I did not further investigate what was responsible for the 400. I was fine with the maximum I found, because I needed around 2000 chars in my case.

Convert character to ASCII code in JavaScript

For supporting all UTF-16 (also non-BMP/supplementary characters) from ES6 the string.codePointAt() method is available;

This method is an improved version of charCodeAt which could support only unicode codepoints < 65536 ( 216 - a single 16bit ) .

How to print a dictionary line by line in Python?

# Declare and Initialize Map
map = {}

map ["New"] = 1
map ["to"] = 1
map ["Python"] = 5
map ["or"] = 2

# Print Statement
for i in map:
  print ("", i, ":", map[i])

#  New : 1
#  to : 1
#  Python : 5
#  or : 2

jsonify a SQLAlchemy result set in Flask

Here is a way to add an as_dict() method on every class, as well as any other method you want to have on every single class. Not sure if this is the desired way or not, but it works...

class Base(object):
    def as_dict(self):
        return dict((c.name,
                     getattr(self, c.name))
                     for c in self.__table__.columns)


Base = declarative_base(cls=Base)

How to create standard Borderless buttons (like in the design guideline mentioned)?

If you want to achieve the same programmatically :

(this is C# but easily transatable to Java)

Button button = new Button(new ContextThemeWrapper(Context, Resource.Style.Widget_AppCompat_Button_Borderless_Colored), null, Resource.Style.Widget_AppCompat_Button_Borderless_Colored);

Match

    <Button
       style="@style/Widget.AppCompat.Button.Borderless.Colored"
    .../>

Simplest way to wait some asynchronous tasks complete, in Javascript?

All answers are quite old. Since the beginning of 2013 Mongoose started to support promises gradually for all queries, so that would be the recommended way of structuring several async calls in the required order going forward I guess.

How can I mix LaTeX in with Markdown?

Perhaps mathJAX is the ticket. It's built on jsMath, a 2004 vintage JavaScript library.

As of 5-Feb-2015 I'd switch to recommend KaTeX - most performant Javascript LaTeX library from Khan Academy.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

A Tic-tac-toe adaptation to the min max algorithem

let gameBoard: [
    [null, null, null],
    [null, null, null],
    [null, null, null]
]

const SYMBOLS = {
    X:'X',
    O:'O'
}

const RESULT = {
    INCOMPLETE: "incomplete",
    PLAYER_X_WON: SYMBOLS.x,
    PLAYER_O_WON: SYMBOLS.o,
    tie: "tie"
}

We'll need a function that can check for the result. The function will check for a succession of chars. What ever the state of the board is, the result is one of 4 options: either Incomplete, player X won, Player O won or a tie.

_x000D_
_x000D_
function checkSuccession (line){_x000D_
    if (line === SYMBOLS.X.repeat(3)) return SYMBOLS.X_x000D_
    if (line === SYMBOLS.O.repeat(3)) return SYMBOLS.O_x000D_
    return false _x000D_
}_x000D_
_x000D_
function getResult(board){_x000D_
_x000D_
    let result = RESULT.incomplete_x000D_
    if (moveCount(board)<5){_x000D_
        return result_x000D_
    }_x000D_
_x000D_
    let lines_x000D_
_x000D_
    //first we check row, then column, then diagonal_x000D_
    for (var i = 0 ; i<3 ; i++){_x000D_
        lines.push(board[i].join(''))_x000D_
    }_x000D_
_x000D_
    for (var j=0 ; j<3; j++){_x000D_
        const column = [board[0][j],board[1][j],board[2][j]]_x000D_
        lines.push(column.join(''))_x000D_
    }_x000D_
_x000D_
    const diag1 = [board[0][0],board[1][1],board[2][2]]_x000D_
    lines.push(diag1.join(''))_x000D_
    const diag2 = [board[0][2],board[1][1],board[2][0]]_x000D_
    lines.push(diag2.join(''))_x000D_
    _x000D_
    for (i=0 ; i<lines.length ; i++){_x000D_
        const succession = checkSuccesion(lines[i])_x000D_
        if(succession){_x000D_
            return succession_x000D_
        }_x000D_
    }_x000D_
_x000D_
    //Check for tie_x000D_
    if (moveCount(board)==9){_x000D_
        return RESULT.tie_x000D_
    }_x000D_
_x000D_
    return result_x000D_
}
_x000D_
_x000D_
_x000D_

Our getBestMove function will receive the state of the board, and the symbol of the player for which we want to determine the best possible move. Our function will check all possible moves with the getResult function. If it is a win it will give it a score of 1. if it's a loose it will get a score of -1, a tie will get a score of 0. If it is undetermined we will call the getBestMove function with the new state of the board and the opposite symbol. Since the next move is of the oponent, his victory is the lose of the current player, and the score will be negated. At the end possible move receives a score of either 1,0 or -1, we can sort the moves, and return the move with the highest score.

_x000D_
_x000D_
const copyBoard = (board) => board.map( _x000D_
    row => row.map( square => square  ) _x000D_
)_x000D_
_x000D_
function getAvailableMoves (board) {_x000D_
  let availableMoves = []_x000D_
  for (let row = 0 ; row<3 ; row++){_x000D_
    for (let column = 0 ; column<3 ; column++){_x000D_
      if (board[row][column]===null){_x000D_
        availableMoves.push({row, column})_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return availableMoves_x000D_
}_x000D_
_x000D_
function applyMove(board,move, symbol) {_x000D_
  board[move.row][move.column]= symbol_x000D_
  return board_x000D_
}_x000D_
 _x000D_
function getBestMove (board, symbol){_x000D_
_x000D_
    let availableMoves = getAvailableMoves(board)_x000D_
_x000D_
    let availableMovesAndScores = []_x000D_
_x000D_
    for (var i=0 ; i<availableMoves.length ; i++){_x000D_
      let move = availableMoves[i]_x000D_
      let newBoard = copyBoard(board)_x000D_
      newBoard = applyMove(newBoard,move, symbol)_x000D_
      result = getResult(newBoard,symbol).result_x000D_
      let score_x000D_
      if (result == RESULT.tie) {score = 0}_x000D_
      else if (result == symbol) {_x000D_
        score = 1_x000D_
      }_x000D_
      else {_x000D_
        let otherSymbol = (symbol==SYMBOLS.x)? SYMBOLS.o : SYMBOLS.x_x000D_
        nextMove = getBestMove(newBoard, otherSymbol)_x000D_
        score = - (nextMove.score)_x000D_
      }_x000D_
      if(score === 1)  // Performance optimization_x000D_
        return {move, score}_x000D_
      availableMovesAndScores.push({move, score})_x000D_
    }_x000D_
_x000D_
    availableMovesAndScores.sort((moveA, moveB )=>{_x000D_
        return moveB.score - moveA.score_x000D_
      })_x000D_
    return availableMovesAndScores[0]_x000D_
  }
_x000D_
_x000D_
_x000D_

Algorithm in action, Github, Explaining the process in more details

How to create a custom scrollbar on a div (Facebook style)

This link should get you started. Long story short, a div that has been styled to look like a scrollbar is used to catch click-and-drag events. Wired up to these events are methods that scroll the contents of another div which is set to an arbitrary height and typically has a css rule of overflow:scroll (there are variants on the css rules but you get the idea).

I'm all about the learning experience -- but after you've learned how it works, I recommend using a library (of which there are many) to do it. It's one of those "don't reinvent" things...

How to run a C# application at Windows startup?

If you could not set your application autostart you can try to paste this code to manifest

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

or delete manifest I had found it in my application

Why does corrcoef return a matrix?

It allows you to compute correlation coefficients of >2 data sets, e.g.

>>> from numpy import *
>>> a = array([1,2,3,4,6,7,8,9])
>>> b = array([2,4,6,8,10,12,13,15])
>>> c = array([-1,-2,-2,-3,-4,-6,-7,-8])
>>> corrcoef([a,b,c])
array([[ 1.        ,  0.99535001, -0.9805214 ],
       [ 0.99535001,  1.        , -0.97172394],
       [-0.9805214 , -0.97172394,  1.        ]])

Here we can get the correlation coefficient of a,b (0.995), a,c (-0.981) and b,c (-0.972) at once. The two-data-set case is just a special case of N-data-set class. And probably it's better to keep the same return type. Since the "one value" can be obtained simply with

>>> corrcoef(a,b)[1,0]
0.99535001355530017

there's no big reason to create the special case.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

In order to make that working I had to set:

compile ("com.android.support:support-v4:22.2.0")
compile ("com.android.support:appcompat-v7:22.2.0")
compile ("com.android.support:support-annotations:22.2.0")
compile ("com.android.support:recyclerview-v7:22.2.0")
compile ("com.android.support:design:22.2.0")

compile ("com.android.support:design:22.2.0")

Documentation states something different (docs):

com.android.support:support-design:22.0.0

How can I add a key/value pair to a JavaScript object?

You could use either of these (provided key3 is the acutal key you want to use)

arr[ 'key3' ] = value3;

or

arr.key3 = value3;

If key3 is a variable, then you should do:

var key3 = 'a_key';
var value3 = 3;
arr[ key3 ] = value3;

After this, requesting arr.a_key would return the value of value3, a literal 3.

How to select top n rows from a datatable/dataview in ASP.NET

In framework 3.5, dt.Rows.Cast<System.Data.DataRow>().Take(n)

Otherwise the way you mentioned

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

In my case all Internet access must run through a proxy and npm was not configured with the proxy to reach http://registry.npmjs.org.

I ran npm install --log-level verbose to get more information and saw that the response had HTML stating I was not authenticated with the proxy.

Running the following fixed it (replacing below with your username/password/proxy address:

npm config set proxy 'username:[email protected]'
npm config set https-proxy 'username:[email protected]'

I do not advise putting the password in raw text instead using something like cntlm to set up a local proxy that delegates to the real proxy.

Angular 2 Unit Tests: Cannot find name 'describe'

You need to install typings for jasmine. Assuming you are on a relatively recent version of typescript 2 you should be able to do:

npm install --save-dev @types/jasmine

How to pass variable number of arguments to a PHP function

In a new Php 5.6, you can use ... operator instead of using func_get_args().

So, using this, you can get all the parameters you pass:

function manyVars(...$params) {
   var_dump($params);
}

PHP sessions that have already been started

It would be more efficient:

@session_start();

Avoiding error handler in the screen

Best,

Select current date by default in ASP.Net Calendar control

Two ways of doing it.

Late binding

<asp:Calendar ID="planning" runat="server" SelectedDate="<%# DateTime.Now %>"></asp:Calendar>

Code behind way (Page_Load solution)

protected void Page_Load(object sender, EventArgs e)
{
    BindCalendar();
}

private void BindCalendar()
{
    planning.SelectedDate = DateTime.Today;
}

Altough, I strongly recommend to do it from a BindMyStuff way. Single entry point easier to debug. But since you seems to know your game, you're all set.

Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

Get WooCommerce product categories from WordPress

<?php

  $taxonomy     = 'product_cat';
  $orderby      = 'name';  
  $show_count   = 0;      // 1 for yes, 0 for no
  $pad_counts   = 0;      // 1 for yes, 0 for no
  $hierarchical = 1;      // 1 for yes, 0 for no  
  $title        = '';  
  $empty        = 0;

  $args = array(
         'taxonomy'     => $taxonomy,
         'orderby'      => $orderby,
         'show_count'   => $show_count,
         'pad_counts'   => $pad_counts,
         'hierarchical' => $hierarchical,
         'title_li'     => $title,
         'hide_empty'   => $empty
  );
 $all_categories = get_categories( $args );
 foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;       
        echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

        $args2 = array(
                'taxonomy'     => $taxonomy,
                'child_of'     => 0,
                'parent'       => $category_id,
                'orderby'      => $orderby,
                'show_count'   => $show_count,
                'pad_counts'   => $pad_counts,
                'hierarchical' => $hierarchical,
                'title_li'     => $title,
                'hide_empty'   => $empty
        );
        $sub_cats = get_categories( $args2 );
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo  $sub_category->name ;
            }   
        }
    }       
}
?>

This will list all the top level categories and subcategories under them hierarchically. do not use the inner query if you just want to display the top level categories. Style it as you like.

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

The query either returned no rows or is erroneus, thus FALSE is returned. Change it to

if (!$dbc || mysqli_num_rows($dbc) == 0)

mysqli_num_rows:

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

SQL JOIN, GROUP BY on three tables to get totals

Thank you very much for the replies!

Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:

1   39.00   9.00

You'll end up with:

1   78.00   48.00

Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.

After much struggling, I think that the following query returns what I need it to:

SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
  SELECT invoiceid, SUM(p.amount) amount
  FROM invoicepayments ip 
  LEFT JOIN payments p ON ip.paymentid = p.paymentid
  GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'

Would you guys concur?

overlay opaque div over youtube iframe

I spent a day messing with CSS before I found anataliocs tip. Add wmode=transparent as a parameter to the YouTube URL:

<iframe title=<your frame title goes here> 
    src="http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent"  
    scrolling="no" 
    frameborder="0" 
    width="640" 
    height="390" 
    style="border:none;">
</iframe>

This allows the iframe to inherit the z-index of its container so your opaque <div> would be in front of the iframe.

Setting up PostgreSQL ODBC on Windows

As I see PostgreSQL installer doesn't include 64 bit version of ODBC driver, which is necessary in your case. Download psqlodbc_09_00_0310-x64.zip and install it instead. I checked that on Win 7 64 bit and PostgreSQL 9.0.4 64 bit and it looks ok:

enter image description here

Test connection:

enter image description here

Storing Data in MySQL as JSON

Early support for storing JSON in MySQL has been added to the MySQL 5.7.7 JSON labs release (linux binaries, source)! The release seems to have grown from a series of JSON-related user-defined functions made public back in 2013.

This nascent native JSON support seems to be heading in a very positive direction, including JSON validation on INSERT, an optimized binary storage format including a lookup table in the preamble that allows the JSN_EXTRACT function to perform binary lookups rather than parsing on every access. There is also a whole raft of new functions for handling and querying specific JSON datatypes:

CREATE TABLE users (id INT, preferences JSON);

INSERT INTO users VALUES (1, JSN_OBJECT('showSideBar', true, 'fontSize', 12));

SELECT JSN_EXTRACT(preferences, '$.showSideBar') from users;

+--------------------------------------------------+
| id   | JSN_EXTRACT(preferences, '$.showSideBar') |
+--------------------------------------------------+
| 1    | true                                      |
+--------------------------------------------------+

IMHO, the above is a great use case for this new functionality; many SQL databases already have a user table and, rather than making endless schema changes to accommodate an evolving set of user preferences, having a single JSON column a single JOIN away is perfect. Especially as it's unlikely that it would ever need to be queried for individual items.

While it's still early days, the MySQL server team are doing a great job of communicating the changes on the blog.

java: Class.isInstance vs Class.isAssignableFrom

For brevity, we can understand these two APIs like below:

  1. X.class.isAssignableFrom(Y.class)

If X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

  1. X.class.isInstance(y)

Say y is an instance of class Y, if X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

How To Set A JS object property name from a variable

This is the way to dynamically set the value

var jsonVariable = {};
for (var i = 1; i < 3; i++) {
    var jsonKey = i + 'name';
    jsonVariable[jsonKey] = 'name' + i;
}

Allow only numbers and dot in script

This is a great place to use regular expressions.

By using a regular expression, you can replace all that code with just one line.

You can use the following regex to validate your requirements:

[0-9]*\.?[0-9]*

In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.

You can replace your code with this:

function validate(s) {
    var rgx = /^[0-9]*\.?[0-9]*$/;
    return s.match(rgx);
}

That code can replace your entire function!

Note that you have to escape the period with a backslash (otherwise it stands for 'any character').

For more reading on using regular expressions with javascript, check this out:

You can also test the above regex here:


Explanation of the regex used above:

  • The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.

  • The * means "zero or more of the previous expression."

  • [0-9]* means "zero or more numbers"

  • The backslash is used as an escape character for the period, because period usually stands for "any character."

  • The ? means "zero or one of the previous character."

  • The ^ represents the beginning of a string.

  • The $ represents the end of a string.

  • Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.

Hope this helps!

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

Check if a value exists in pandas dataframe index

This should do the trick

'g' in df.index

Python: Pandas Dataframe how to multiply entire column with a scalar

Here's the answer after a bit of research:

df.loc[:,'quantity'] *= -1 #seems to prevent SettingWithCopyWarning 

How to find/identify large commits in git history?

How can I track down the large files in the git history?

Start by analyzing, validating and selecting the root cause. Use git-repo-analysis to help.

You may also find some value in the detailed reports generated by BFG Repo-Cleaner, which can be run very quickly by cloning to a Digital Ocean droplet using their 10MiB/s network throughput.

Accessing a resource via codebehind in WPF

You may also use this.Resources["mykey"]. I guess that is not much better than your own suggestion.

How to set the thumbnail image on HTML5 video?

That seems to be an extra image being shown there.

You can try using this

<img src="/images/image_of_video.png" alt="image" />
/* write your code for the video here */

Now using jQuery play the video and hide the image as

$('img').click(function () {
  $(this).hide();
  // use the parameters to play the video now..
})

Do HTTP POST methods send data as a QueryString?

The best way to visualize this is to use a packet analyzer like Wireshark and follow the TCP stream. HTTP simply uses TCP to send a stream of data starting with a few lines of HTTP headers. Often this data is easy to read because it consists of HTML, CSS, or XML, but it can be any type of data that gets transfered over the internet (Executables, Images, Video, etc).

For a GET request, your computer requests a specific URL and the web server usually responds with a 200 status code and the the content of the webpage is sent directly after the HTTP response headers. This content is the same content you would see if you viewed the source of the webpage in your browser. The query string you mentioned is just part of the URL and gets included in the HTTP GET request header that your computer sends to the web server. Below is an example of an HTTP GET request to http://accel91.citrix.com:8000/OA_HTML/OALogout.jsp?menu=Y, followed by a 302 redirect response from the server. Some of the HTTP Headers are wrapped due to the size of the viewing window (these really only take one line each), and the 302 redirect includes a simple HTML webpage with a link to the redirected webpage (Most browsers will automatically redirect any 302 response to the URL listed in the Location header instead of displaying the HTML response):

HTTP GET with 302 redirect

For a POST request, you may still have a query string, but this is uncommon and does not have anything to do with the data that you are POSTing. Instead, the data is included directly after the HTTP headers that your browser sends to the server, similar to the 200 response that the web server uses to respond to a GET request. In the case of POSTing a simple web form this data is encoded using the same URL encoding that a query string uses, but if you are using a SOAP web service it could also be encoded using a multi-part MIME format and XML data.

For example here is what an HTTP POST to an XML based SOAP web service located at http://192.168.24.23:8090/msh looks like in Wireshark Follow TCP Stream:

HTTP POST TCP Stream

Where are the Properties.Settings.Default stored?

User-specific settings are saved in the user's Application Data folder for that application. Look for a user.config file.

I don't know what you expected, since users often don't even have write access to the executable directory in the first place.

Get filename from input [type='file'] using jQuery

Using Bootstrap

Remove form-control-file Class from input field to avoid unwanted horizontal scroll bar

Try this!!

_x000D_
_x000D_
$('#upload').change(function() {_x000D_
    var filename = $('#upload').val();_x000D_
    if (filename.substring(3,11) == 'fakepath') {_x000D_
        filename = filename.substring(12);_x000D_
    } // For Remove fakepath_x000D_
    $("label[for='file_name'] b").html(filename);_x000D_
    $("label[for='file_default']").text('Selected File: ');_x000D_
    if (filename == "") {_x000D_
        $("label[for='file_default']").text('No File Choosen');_x000D_
    }_x000D_
});
_x000D_
.custom_file {_x000D_
  margin: auto;_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="form-group">_x000D_
   <label for="upload" class="btn btn-sm btn-primary">Upload Image</label>_x000D_
    <input type="file" class="text-center form-control-file custom_file" id="upload" name="user_image">_x000D_
    <label for="file_default">No File Choosen </label>_x000D_
    <label for="file_name"><b></b></label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best place for storing uploaded images, SQL database or disk file system?

For auto resizing, try imagemagick... it is used for many major open source content/photo management systems... and I believe that there are some .net extensions for it.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

How can I have a newline in a string in sh?

On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh) and when executed as a sh script:

[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
Hello
World
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" > test-str.sh
[bash]§ cat test-str.sh 
STR="Hello\nWorld"
echo $STR
[bash]§ sh test-str.sh 
Hello
World

I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n happens in sh).

However, i noticed that this same script would behave differently when executed with bash and would print out Hello\nWorld instead:

[bash]§ bash test-str.sh
Hello\nWorld

I've managed to get the desired output with bash as follows:

[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"

Note the double quotes around $STR. This behaves identically if saved and run as a bash script.

The following also gives the desired output:

[bash]§ echo "Hello
> World"

Print raw string from variable? (not getting the answers)

In general, to make a raw string out of a string variable, I use this:

string = "C:\\Windows\Users\alexb"

raw_string = r"{}".format(string)

output:

'C:\\\\Windows\\Users\\alexb'

jQuery Dialog Box

Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:

$(document).ready({
    $('a.TOClink').click(function(){
        showTOC();
    });
});

function showTOC() {
    $('#example').dialog({modal:true});
}

A more concise example which accomplishes the desired effect using the jQuery UI dialog is:

   <div id="terms" style="display:none;">
       Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   </div>
   <a id="showTerms" href="#">Show Terms &amp; Conditions</a>      
   <script type="text/javascript">
       $(document).ready(function(){
           $('#showTerms').click(function(){
               $('#terms').dialog({modal:true});   
           });
       });
   </script>

Removing the textarea border in HTML

In CSS:

  textarea { 
    border-style: none; 
    border-color: Transparent; 
    overflow: auto;        
  }

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

In my case it was simply an error in the web.config.

I had:

<endpoint address="http://localhost/WebService/WebOnlineService.asmx" 

It should have been:

<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"

The port number (:10593) was missing from the address.

Oracle 'Partition By' and 'Row_Number' keyword

That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.

This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.

Hope that helps...

How can I determine the direction of a jQuery scroll event?

You can do it without having to keep track of the previous scroll top, as all the other examples require:

$(window).bind('mousewheel', function(event) {
    if (event.originalEvent.wheelDelta >= 0) {
        console.log('Scroll up');
    }
    else {
        console.log('Scroll down');
    }
});

I am not an expert on this so feel free to research it further, but it appears that when you use $(element).scroll, the event being listened for is a 'scroll' event.

But if you specifically listen for a mousewheel event by using bind, the originalEvent attribute of the event parameter to your callback contains different information. Part of that information is wheelDelta. If it's positive, you moved the mousewheel up. If it's negative, you moved the mousewheel down.

My guess is that mousewheel events will fire when the mouse wheel turns, even if the page does not scroll; a case in which 'scroll' events probably are not fired. If you want, you can call event.preventDefault() at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.

Calling one Bash script from another Script passing it arguments with quotes and spaces

Quote your args in Testscript 1:

echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

Separators for Navigation

I believe the best solution for this, is what I use, and that is a natural css border:

border-right:1px solid;

You might need to take care of padding like:

padding-left: 5px;
padding-right: 5px;

Finally, if you don't want the last li to have that seperating border, give it's last-child "none" in "border-right" like this:

li:last-child{
  border-right:none;
}

Good luck :)

2D Euclidean vector rotations

You're calculating the y-part of your new coordinate based on the 'new' x-part of the new coordinate. Basically this means your calculating the new output in terms of the new output...

Try to rewrite in terms of input and output:

vector2<double> multiply( vector2<double> input, double cs, double sn ) {
  vector2<double> result;
  result.x = input.x * cs - input.y * sn;
  result.y = input.x * sn + input.y * cs;
  return result;
}

Then you can do this:

vector2<double> input(0,1);
vector2<double> transformed = multiply( input, cs, sn );

Note how choosing proper names for your variables can avoid this problem alltogether!

Style child element when hover on parent

Yes, you can definitely do this. Just use something like

.parent:hover .child {
   /* ... */
}

According to this page it's supported by all major browsers.

ORA-00054: resource busy and acquire with NOWAIT specified

You'll have to wait. The session that was killed was in the middle of a transaction and updated lots of records. These records have to be rollbacked and some background process is taking care of that. In the meantime you cannot modify the records that were touched.

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

How to get param from url in angular 4?

use paramMap

This will provide param names and their values

//http://localhost:4200/categories/1
//{ path: 'categories/:category', component: CategoryComponent },

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) { }

ngOnInit() {

  this.route.paramMap.subscribe(params => {
        console.log(params)
  })
}

MultipartException: Current request is not a multipart request

That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.

I ended up solving it by going to the Body tab, change the param type from File to Text, then back to File and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

How to find length of dictionary values

d={1:'a',2:'b'}
sum=0
for i in range(0,len(d),1):
   sum=sum+1
i=i+1
print i

OUTPUT=2

HTML / CSS Popup div on text click

You can simply use jQuery UI Dialog

Example:

_x000D_
_x000D_
$(function() {_x000D_
  $("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8" />_x000D_
  <title>jQuery UI Dialog - Default functionality</title>_x000D_
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
  <link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="dialog" title="Basic dialog">_x000D_
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

'int' object has no attribute '__getitem__'

Some of the problems:

for i in range[6]:
            for j in range[6]:

should be:

range(6)

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

Int to Decimal Conversion - Insert decimal point at specified location

int i = 7122960;
decimal d = (decimal)i / 100;

log4j:WARN No appenders could be found for logger in web.xml

Or, you could be doing what I did and define the logger before the log configuration file has been loaded. This would be as they say: "Putting the cart before the horse."

In the code:

public static Logger logger = Logger.getLogger("RbReport");

... later on

PropertyConfigurator.configure(l4j);
logger = Logger.getLogger("RbReport");

Fix was to initialize the logger after the configuration was loaded.

For the geeks it was "Putting Descarte b4 d horse".

Global variables in Javascript across multiple files

Hi to pass values from one js file to another js file we can use Local storage concept

<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>

Two.js file

function myFunction() {
var test =localStorage.name;

 alert(test);
}

Three.js File

localStorage.name = 1;

How to add a new schema to sql server 2008?

You can try this:

use database
go

declare @temp as int
select @temp = count(1) from sys.schemas where name = 'newSchema'

if @temp = 0 
begin
    exec ('create SCHEMA temporal')
    print 'The schema newSchema was created in database'
end 
else 
print 'The schema newSchema already exists in database'
go

Why can't radio buttons be "readonly"?

The best solution is to set the checked or unchecked state (either from client or server) and to not let the user change it after wards (i.e make it readonly) do the following:

<input type="radio" name="name" onclick="javascript: return false;" />

How to load an ImageView by URL in Android?

public class LoadWebImg extends Activity {

String image_URL=
 "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       ImageView bmImage = (ImageView)findViewById(R.id.image);
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    Bitmap bm = LoadImage(image_URL, bmOptions);
    bmImage.setImageBitmap(bm);
   }

   private Bitmap LoadImage(String URL, BitmapFactory.Options options)
   {       
    Bitmap bitmap = null;
    InputStream in = null;       
       try {
           in = OpenHttpConnection(URL);
           bitmap = BitmapFactory.decodeStream(in, null, options);
           in.close();
       } catch (IOException e1) {
       }
       return bitmap;               
   }

private InputStream OpenHttpConnection(String strURL) throws IOException{
 InputStream inputStream = null;
 URL url = new URL(strURL);
 URLConnection conn = url.openConnection();

 try{
  HttpURLConnection httpConn = (HttpURLConnection)conn;
  httpConn.setRequestMethod("GET");
  httpConn.connect();

  if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
   inputStream = httpConn.getInputStream();
  }
 }
 catch (Exception ex)
 {
 }
 return inputStream;
}
}

jQuery - keydown / keypress /keyup ENTERKEY detection?

I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.

z-index not working with position absolute

Old question but this answer might help someone.

If you are trying to display the contents of the container outside of the boundaries of the container, make sure that it doesn't have overflow:hidden, otherwise anything outside of it will be cut off.

Received an invalid column length from the bcp client for colid 6

Great piece of code, thanks for sharing!

I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.

_x000D_
_x000D_
static string GetDataMemberName(string colName, object t) {_x000D_
  foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
    if (propertyInfo.CanRead) {_x000D_
      if (propertyInfo.Name == colName) {_x000D_
        var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
        if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
          return attributes.Name;_x000D_
        return colName;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return colName;_x000D_
}
_x000D_
_x000D_
_x000D_

Create a new txt file using VB.NET

open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()

This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...

Is there a way to detach matplotlib plots so that the computation can continue?

In my case, I wanted to have several windows pop up as they are being computed. For reference, this is the way:

from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1 = f1.add_subplot(111)
af2 = f2.add_subplot(111)
af1.plot([1,2,3])
af2.plot([6,5,4])
draw() 
print 'continuing computation'
show()

PS. A quite useful guide to matplotlib's OO interface.