Programs & Examples On #Jsonstore

JSONStore is an API in the IBM Worklight product. It provides offline encrypted storage on Android and iOS devices with an natural JavaScript API.

django order_by query set, ascending and descending

Adding the - will order it in descending order. You can also set this by adding a default ordering to the meta of your model. This will mean that when you do a query you just do MyModel.objects.all() and it will come out in the correct order.

class MyModel(models.Model):

    check_in = models.DateField()

    class Meta:
        ordering = ('-check_in',)

UUID max character length

Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.

MongoDB: Combine data from multiple collections into one..how?

Yes you can: Take this utility function that I have written today:

function shangMergeCol() {
  tcol= db.getCollection(arguments[0]);
  for (var i=1; i<arguments.length; i++){
    scol= db.getCollection(arguments[i]);
    scol.find().forEach(
        function (d) {
            tcol.insert(d);
        }
    )
  }
}

You can pass to this function any number of collections, the first one is going to be the target one. All the rest collections are sources to be transferred to the target one.

Validating parameters to a Bash script

You can validate point a and b compactly by doing something like the following:

#!/bin/sh
MYVAL=$(echo ${1} | awk '/^[0-9]+$/')
MYVAL=${MYVAL:?"Usage - testparms <number>"}
echo ${MYVAL}

Which gives us ...

$ ./testparams.sh 
Usage - testparms <number>

$ ./testparams.sh 1234
1234

$ ./testparams.sh abcd
Usage - testparms <number>

This method should work fine in sh.

Inline labels in Matplotlib

A simpler approach like the one Ioannis Filippidis do :

import matplotlib.pyplot as plt
import numpy as np

# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)

# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')

factor=3/4 ;offset=20  # text position in view  
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22  t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()

code python 3 on sageCell

Chrome: Uncaught SyntaxError: Unexpected end of input

In my case, i had low internet speed, when i turn off the other user's internet connection then error has gone, strange

Make index.html default, but allow index.php to be visited if typed in

Hi,

Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.

Here how I do that...

# Accesible Index Page
<IfModule dir_module>
 DirectoryIndex index.php index.html
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
 RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>

The above code simply captures any index.* and redirect it to the main domain.

Thank you

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

Class vs. static method in JavaScript

I use namespaces:

var Foo = {
     element: document.getElementById("id-here"),

     Talk: function(message) {
            alert("talking..." + message);
     },

     ChangeElement: function() {
            this.element.style.color = "red";
     }
};

And to use it:

Foo.Talk("Testing");

Or

Foo.ChangeElement();

Can't get Gulp to run: cannot find module 'gulp-util'

Try to install the missing module.

npm install 'module-name'

How to list the size of each file and directory and sort by descending size in Bash?

Apparently --max-depth option is not in Mac OS X's version of the du command. You can use the following instead.

du -h -d 1 | sort -n

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.10</version>
    </dependency>

reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api

How do I get the application exit code from a Windows command line?

A pseudo environment variable named errorlevel stores the exit code:

echo Exit Code is %errorlevel%

Also, the if command has a special syntax:

if errorlevel

See if /? for details.

Example

@echo off
my_nify_exe.exe
if errorlevel 1 (
   echo Failure Reason Given is %errorlevel%
   exit /b %errorlevel%
)

Warning: If you set an environment variable name errorlevel, %errorlevel% will return that value and not the exit code. Use (set errorlevel=) to clear the environment variable, allowing access to the true value of errorlevel via the %errorlevel% environment variable.

Spring Boot War deployed to Tomcat

Your Application.java class should extend the SpringBootServletInitializer class ex:

public class Application extends SpringBootServletInitializer {}

How to disable an Android button?

With Kotlin you can do,

// to disable clicks
myButton.isClickable = false 

// to disable button
myButton.isEnabled = false

// to enable clicks
myButton.isClickable = true 

// to enable button
myButton.isEnabled = true

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I received such an error in a Python-based web API's response .text, but it led me here, so this may help others with a similar issue (it's very difficult to filter response and request issues in a search when using requests..)

Using json.dumps() on the request data arg to create a correctly-escaped string of JSON before POSTing fixed the issue for me

requests.post(url, data=json.dumps(data))

How to debug in Android Studio using adb over WiFi

In Android Studio 3.0.1 > Goto > (Short cut key (Alt+Cltr+S)) Settings > Goto Plugins > Click on Browser repositories... > Search "ADB WIFI" and install the plugin. After the installation restart your android studio.

enter image description here

Click the icon enter image description here and connect your device.

SeekBar and media player in android

Code in Kotlin:

var updateSongTime = object : Runnable {
            override fun run() {
                val getCurrent = mediaPlayer?.currentPosition
                startTimeText?.setText(String.format("%d:%d",
                        TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long),
                        TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong()) -
                                TimeUnit.MINUTES.toSeconds(
                                        TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong()))))
                seekBar?.setProgress(getCurrent?.toInt() as Int)
                Handler().postDelayed(this, 1000)
            }
        }

For changing media player audio file every second

If user drags the seek bar then following code snippet can be use

Statified.seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                if(b && Statified.mediaPlayer != null){
                    Statified.mediaPlayer?.seekTo(i)
                }

            }
            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

Should Jquery code go in header or footer?

Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .

I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.

and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.

Calling Javascript function from server side

You can call the function from code behind like this :

MyForm.aspx.cs

protected void MyButton_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "AnotherFunction();", true);
}

MyForm.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function Test() {
        alert("hi");
        $("#ButtonRow").show();
    }
    function AnotherFunction()
    {
        alert("This is another function");
    }
</script>
</head>
<body>
<form id="form2" runat="server">
<table>
    <tr><td>
            <asp:RadioButtonList ID="SearchCategory" runat="server" onchange="Test()"  RepeatDirection="Horizontal"  BorderStyle="Solid">
               <asp:ListItem>Merchant</asp:ListItem>
               <asp:ListItem>Store</asp:ListItem>
               <asp:ListItem>Terminal</asp:ListItem>
            </asp:RadioButtonList>
        </td>
    </tr>
    <tr id="ButtonRow"style="display:none">
         <td>
            <asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
        </td>
    </tr>
    </table> 
</form>

How do I add button on each row in datatable?

my recipe:

datatable declaration:

defaultContent: "<button type='button'....

events:

$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }

What is the best way to use a HashMap in C++?

A hash_map is an older, unstandardized version of what for standardization purposes is called an unordered_map (originally in TR1, and included in the standard since C++11). As the name implies, it's different from std::map primarily in being unordered -- if, for example, you iterate through a map from begin() to end(), you get items in order by key1, but if you iterate through an unordered_map from begin() to end(), you get items in a more or less arbitrary order.

An unordered_map is normally expected to have constant complexity. That is, an insertion, lookup, etc., typically takes essentially a fixed amount of time, regardless of how many items are in the table. An std::map has complexity that's logarithmic on the number of items being stored -- which means the time to insert or retrieve an item grows, but quite slowly, as the map grows larger. For example, if it takes 1 microsecond to lookup one of 1 million items, then you can expect it to take around 2 microseconds to lookup one of 2 million items, 3 microseconds for one of 4 million items, 4 microseconds for one of 8 million items, etc.

From a practical viewpoint, that's not really the whole story though. By nature, a simple hash table has a fixed size. Adapting it to the variable-size requirements for a general purpose container is somewhat non-trivial. As a result, operations that (potentially) grow the table (e.g., insertion) are potentially relatively slow (that is, most are fairly fast, but periodically one will be much slower). Lookups, which cannot change the size of the table, are generally much faster. As a result, most hash-based tables tend to be at their best when you do a lot of lookups compared to the number of insertions. For situations where you insert a lot of data, then iterate through the table once to retrieve results (e.g., counting the number of unique words in a file) chances are that an std::map will be just as fast, and quite possibly even faster (but, again, the computational complexity is different, so that can also depend on the number of unique words in the file).


1 Where the order is defined by the third template parameter when you create the map, std::less<T> by default.

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

Difference between decimal, float and double in .NET?

This has been an interesting thread for me, as today, we've just had a nasty little bug, concerning decimal having less precision than a float.

In our C# code, we are reading numeric values from an Excel spreadsheet, converting them into a decimal, then sending this decimal back to a Service to save into a SQL Server database.

Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
    decimal value = 0;
    Decimal.TryParse(cellValue.ToString(), out value);
}

Now, for almost all of our Excel values, this worked beautifully. But for some, very small Excel values, using decimal.TryParse lost the value completely. One such example is

  • cellValue = 0.00006317592

  • Decimal.TryParse(cellValue.ToString(), out value); // would return 0

The solution, bizarrely, was to convert the Excel values into a double first, and then into a decimal:

Microsoft.Office.Interop.Excel.Range cell = …
object cellValue = cell.Value2;
if (cellValue != null)
{
    double valueDouble = 0;
    double.TryParse(cellValue.ToString(), out valueDouble);
    decimal value = (decimal) valueDouble;
    …
}

Even though double has less precision than a decimal, this actually ensured small numbers would still be recognised. For some reason, double.TryParse was actually able to retrieve such small numbers, whereas decimal.TryParse would set them to zero.

Odd. Very odd.

Collapse all methods in Visual Studio Code

  • Fold All:

    • Windows: Ctrl + K + 0
    • Mac: ? + K + 0
  • Unfold All:

    • Windows: Ctrl + K + J
    • Mac: ? + K + J

To see all available shortcuts in the editor:

  • Windows: Ctrl + K + S
  • Mac: ? + K + S

Screenshot of Visual Studio keyboard shortcuts

All shortcuts kept up to date by the Visual Studio Code team: Visual Studio Code Shortcuts

Why is Spring's ApplicationContext.getBean considered bad?

I mentioned this in a comment on the other question, but the whole idea of Inversion of Control is to have none of your classes know or care how they get the objects they depend on. This makes it easy to change what type of implementation of a given dependency you use at any time. It also makes the classes easy to test, as you can provide mock implementations of dependencies. Finally, it makes the classes simpler and more focused on their core responsibility.

Calling ApplicationContext.getBean() is not Inversion of Control! While it's still easy to change what implemenation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can't get it any other way. You can't just make your own mock implementation in a test class and pass that to it yourself. This basically defeats Spring's purpose as a dependency injection container.

Everywhere you want to say:

MyClass myClass = applicationContext.getBean("myClass");

you should instead, for example, declare a method:

public void setMyClass(MyClass myClass) {
   this.myClass = myClass;
}

And then in your configuration:

<bean id="myClass" class="MyClass">...</bean>

<bean id="myOtherClass" class="MyOtherClass">
   <property name="myClass" ref="myClass"/>
</bean>

Spring will then automatically inject myClass into myOtherClass.

Declare everything in this way, and at the root of it all have something like:

<bean id="myApplication" class="MyApplication">
   <property name="myCentralClass" ref="myCentralClass"/>
   <property name="myOtherCentralClass" ref="myOtherCentralClass"/>
</bean>

MyApplication is the most central class, and depends at least indirectly on every other service in your program. When bootstrapping, in your main method, you can call applicationContext.getBean("myApplication") but you should not need to call getBean() anywhere else!

Why can templates only be implemented in the header file?

Although standard C++ has no such requirement, some compilers require that all function and class templates need to be made available in every translation unit they are used. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files

There is an export keyword which is supposed to mitigate this problem, but it's nowhere close to being portable.

Setting the value of checkbox to true or false with jQuery

Use $('#id-of-the-checkbox').prop('checked', true_or_false);

In case you are using an ancient jQuery version, you'll need to use .attr('checked', 'checked') to check and .removeAttr('checked') to uncheck.

php - insert a variable in an echo string

Here's the 3 best ways of doing this.

Method One:

$x = '+3';
echo "1+2$x";

Double Quotes (") allows you to just pass the variable directly inside it.


Method Two:

$x = '+3';
echo '1+2'.$x;

When you don't want to use double quotes for whatever reason go with this. The (.) simply means "Add" basically. So if you were to want to add something like, 1+2+3+4+5 and have your variable in the middle all you need to do is:

$x = '+3';
echo '1+2'.$x.'+4+5';

Method 3: (Adding a variable directly inside the called variable)

$x = '+3';
$y = '+4';
$z = '+5';
echo "1+2${"x".$y.$z}";
Output: 1+2+3+4+5

Here we are adding $y and $z to $x using the "."; The {} prioritize's the work inside it before rendering the undefined variable.

This personally is a very useful function for calling functions like:

//Add the Get request to a variable.
$x = $_GET['tool'];

//Edit: If you want this if to contain multiple $xresult's change the if's
//Conditon in the "()" to isset($get). Simple. Now just add $xresultprogram
//or whatever.
if($x == 'app') {
    $xresultapp = 'User requested tool: App';
}

//Somewhere down far in HTML maybe...

echo ${"xresult".$x}; // so this outputs: $xresultapp's value

//Note: doing ${"xresult".$_GET['tool']} directly wont work.
//I believe this is because since some direct non-echo html was loaded
//before we got to this php section it cant load cause it has already
//Started loading client side HTML and JS.

This would output $xresultapp's 'User requested tool: App' if the url query is: example.com?tool=app. You can modify with an else statement to define what happens when some value other than 'app' is requested. Remember, everything is case-sensitive so if they request 'App' in capitals it won't output $xresultapp.

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

node.js - how to write an array to file

To do what you want, using the fs.createWriteStream(path[, options]) function in a ES6 way:

const fs = require('fs');
const writeStream = fs.createWriteStream('file.txt');
const pathName = writeStream.path;
 
let array = ['1','2','3','4','5','6','7'];
  
// write each value of the array on the file breaking line
array.forEach(value => writeStream.write(`${value}\n`));

// the finish event is emitted when all data has been flushed from the stream
writeStream.on('finish', () => {
   console.log(`wrote all the array data to file ${pathName}`);
});

// handle the errors on the write process
writeStream.on('error', (err) => {
    console.error(`There is an error writing the file ${pathName} => ${err}`)
});

// close the stream
writeStream.end();

Changing the default icon in a Windows Forms application

The Icon displayed in the Taskbar and Windowtitle is that of the main Form. By changing its Icon you also set the Icon shown in the Taskbar, when already included in your *.resx:

System.ComponentModel.ComponentResourceManager resources = 
    new System.ComponentModel.ComponentResourceManager(typeof(MyForm));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("statusnormal.Icon")));

or, by directly reading from your Resources:

this.Icon = new Icon("Resources/statusnormal.ico");

If you cannot immediately find the code of the Form, search your whole project (CTRL+SHIFT+F) for the shown Window-Title (presuming that the text is static)

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

Be aware of that if you use nested transactions, a ROLLBACK operation rolls back all the nested transactions including the outer-most one.

This might, with usage in combination with TRY/CATCH, result in the error you described. See more here.

Postgresql: Scripting psql execution with password

This also works for other postgresql clis for example you can run pgbench in non-interactive mode.

export PGPASSWORD=yourpassword
/usr/pgsql-9.5/bin/pgbench -h $REMOTE_PG_HOST -p 5432 -U postgres -c 12 -j 4 -t 10000 example > pgbench.out 2>&1 &

Check if pull needed in Git

You can also find a Phing script who does that now.

I needed a solution to update my production environments automatically and we're very happy thanks to this script that I'm sharing.

The script is written in XML and needs Phing.

Django set default form values

You can use initial which is explained here

You have two options either populate the value when calling form constructor:

form = JournalForm(initial={'tank': 123})

or set the value in the form definition:

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

How to redirect output to a file and stdout

Using tail -f output should work.

Javascript decoding html entities

Using jQuery the easiest will be:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';

var output = $("<div />").html(text).text();
console.log(output);

DEMO: http://jsfiddle.net/LKGZx/

How do I programmatically get the GUID of an application in .NET 2.0

Or, just as easy:

string assyGuid = Assembly.GetExecutingAssembly().GetCustomAttribute<GuidAttribute>().Value.ToUpper();

It works for me...

/bin/sh: pushd: not found

pushd is a bash enhancement to the POSIX-specified Bourne Shell. pushd cannot be easily implemented as a command, because the current working directory is a feature of a process that cannot be changed by child processes. (A hypothetical pushd command might do the chdir(2) call and then start a new shell, but ... it wouldn't be very usable.) pushd is a shell builtin, just like cd.

So, either change your script to start with #!/bin/bash or store the current working directory in a variable, do your work, then change back. Depends if you want a shell script that works on very reduced systems (say, a Debian build server) or if you're fine always requiring bash.

How to make a HTTP PUT request?


protected void UpdateButton_Click(object sender, EventArgs e)
        {
            var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
            var bytes = Encoding.ASCII.GetBytes(values);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
            request.Method = "PUT";
            request.ContentType = "application/x-www-form-urlencoded";
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }
            var response =  (HttpWebResponse) request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
                UpdateResponseLabel.Text = "Update completed";
            else
                UpdateResponseLabel.Text = "Error in update";
        }

What is the difference between git clone and checkout?

checkout can be use for many case :

1st case : switch between branch in local repository For instance : git checkout exists_branch_to_switch

You can also create new branch and switch out in throught this case with -b

git checkout -b new_branch_to_switch

2nd case : restore file from x rev

git checkout rev file_to_restore ...

Convert string to nullable type (int, double, etc...)

There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/

This allows you to write very clean code like this:

string value = null;
int? x = value.ConvertOrDefault<int?>();

and also:

object obj = 1;  

string value = null;
int x = 5;
if (value.TryConvert(out x))
    Console.WriteLine("TryConvert example: " + x); 

bool boolean = "false".ConvertOrDefault<bool>();
bool? nullableBoolean = "".ConvertOrDefault<bool?>();
int integer = obj.ConvertOrDefault<int>();
int negativeInteger = "-12123".ConvertOrDefault<int>();
int? nullableInteger = value.ConvertOrDefault<int?>();
MyEnum enumValue = "SecondValue".ConvertOrDefault<MyEnum>();

MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault<MyObjectClassA>();

Stop MySQL service windows

Start Powershell as administrator and run:

net start [MySQL-service-name]

Find the service name:

run 'services.msc', look for MySQL and click on properties

enter image description here

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Under Apache 2+ you can simply do as below (Using Linux Terminal):

sudo a2enmod rewrite && sudo service apache2 restart

or

sudo a2enmod rewrite && sudo /etc/init.d/apache2 restart

Mock a constructor with parameter

With mockito you can use withSettings(), for example if the CounterService required 2 dependencies, you can pass them as a mock:

UserService userService = Mockito.mock(UserService.class); SearchService searchService = Mockito.mock(SearchService.class); CounterService counterService = Mockito.mock(CounterService.class, withSettings().useConstructor(userService, searchService));

Any way to exit bash script, but not quitting the terminal

This is just like you put a run function inside your script run2.sh. You use exit code inside run while source your run2.sh file in the bash tty. If the give the run function its power to exit your script and give the run2.sh its power to exit the terminator. Then of cuz the run function has power to exit your teminator.

    #! /bin/sh
    # use . run2.sh

    run()
    {
        echo "this is run"
        #return 0
        exit 0
    }

    echo "this is begin"
    run
    echo "this is end"

Anyway, I approve with Kaz it's a design problem.

How to rename with prefix/suffix?

I know there is great answers here but I found no reference to handle filename extensions when adding suffix.

I needed to add '_en' suffix to all wav files in a folder before the file extension.

The magic is here: %.*

for filename in *.wav; do mv $filename ${filename%.*}_en.wav; done;

If you need to handle different file extensions, check this answer. A bit less intuitive.

Functional programming vs Object Oriented programming

Object Oriented Programming offers:

  1. Encapsulation, to
    • control mutation of internal state
    • limit coupling to internal representation
  2. Subtyping, allowing:
    • substitution of compatible types (polymorphism)
    • a crude means of sharing implementation between classes (implementation inheritance)

Functional Programming, in Haskell or even in Scala, can allow substitution through more general mechanism of type classes. Mutable internal state is either discouraged or forbidden. Encapsulation of internal representation can also be achieved. See Haskell vs OOP for a good comparison.

Norman's assertion that "Adding a new kind of thing to a functional program may require editing many function definitions to add a new case." depends on how well the functional code has employed type classes. If Pattern Matching on a particular Abstract Data Type is spread throughout a codebase, you will indeed suffer from this problem, but it is perhaps a poor design to start with.

EDITED Removed reference to implicit conversions when discussing type classes. In Scala, type classes are encoded with implicit parameters, not conversions, although implicit conversions are another means to acheiving substitution of compatible types.

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

Best way to get value from Collection by index

I agree with Matthew Flaschen's answer and just wanted to show examples of the options for the case you cannot switch to List (because a library returns you a Collection):

List list = new ArrayList(theCollection);
list.get(5);

Or

Object[] list2 = theCollection.toArray();
doSomethingWith(list[2]);

If you know what generics is I can provide samples for that too.

Edit: It's another question what the intent and semantics of the original collection is.

Convert a string to datetime in PowerShell

You can simply cast strings to DateTime:

[DateTime]"2020-7-16"

or

[DateTime]"Jul-16"

or

$myDate = [DateTime]"Jul-16";

And you can format the resulting DateTime variable by doing something like this:

'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'

or

([DateTime]"Jul-16").ToString('yyyy-MM-dd')

or

$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate

Find kth smallest element in a binary search tree in Optimum way

While this is definitely not the optimal solution to the problem, it is another potential solution which I thought some people might find interesting:

/**
 * Treat the bst as a sorted list in descending order and find the element 
 * in position k.
 *
 * Time complexity BigO ( n^2 )
 *
 * 2n + sum( 1 * n/2 + 2 * n/4 + ... ( 2^n-1) * n/n ) = 
 * 2n + sigma a=1 to n ( (2^(a-1)) * n / 2^a ) = 2n + n(n-1)/4
 *
 * @param t The root of the binary search tree.
 * @param k The position of the element to find.
 * @return The value of the element at position k.
 */
public static int kElement2( Node t, int k ) {
    int treeSize = sizeOfTree( t );

    return kElement2( t, k, treeSize, 0 ).intValue();
}

/**
 * Find the value at position k in the bst by doing an in-order traversal 
 * of the tree and mapping the ascending order index to the descending order 
 * index.
 *
 *
 * @param t Root of the bst to search in.
 * @param k Index of the element being searched for.
 * @param treeSize Size of the entire bst.
 * @param count The number of node already visited.
 * @return Either the value of the kth node, or Double.POSITIVE_INFINITY if 
 *         not found in this sub-tree.
 */
private static Double kElement2( Node t, int k, int treeSize, int count ) {
    // Double.POSITIVE_INFINITY is a marker value indicating that the kth 
    // element wasn't found in this sub-tree.
    if ( t == null )
        return Double.POSITIVE_INFINITY;

    Double kea = kElement2( t.getLeftSon(), k, treeSize, count );

    if ( kea != Double.POSITIVE_INFINITY )
        return kea;

    // The index of the current node.
    count += 1 + sizeOfTree( t.getLeftSon() );

    // Given any index from the ascending in order traversal of the bst, 
    // treeSize + 1 - index gives the
    // corresponding index in the descending order list.
    if ( ( treeSize + 1 - count ) == k )
        return (double)t.getNumber();

    return kElement2( t.getRightSon(), k, treeSize, count );
}

How to convert a JSON string to a Map<String, String> with Jackson JSON

Try TypeFactory. Here's the code for Jackson JSON (2.8.4).

Map<String, String> result;
ObjectMapper mapper;
TypeFactory factory;
MapType type;

factory = TypeFactory.defaultInstance();
type    = factory.constructMapType(HashMap.class, String.class, String.class);
mapper  = new ObjectMapper();
result  = mapper.readValue(data, type);

Here's the code for an older version of Jackson JSON.

Map<String, String> result = new ObjectMapper().readValue(
    data, TypeFactory.mapType(HashMap.class, String.class, String.class));

Xcode warning: "Multiple build commands for output file"

This is not a bug. Xcode assists can assist you. Select the target, to the left in the project Navigator. Click on "Validate settings" at the bottom of the settings. Xcode will check the settings and removes duplicates if possible.

Can You Get A Users Local LAN IP Address Via JavaScript?

Now supported in internal-ip!

An RTCPeerConnection can be used. In browsers like Chrome where a getUserMedia permission is required, we can just detect available input devices and request for them.

const internalIp = async () => {
    if (!RTCPeerConnection) {
        throw new Error("Not supported.")
    }

    const peerConnection = new RTCPeerConnection({ iceServers: [] })

    peerConnection.createDataChannel('')
    peerConnection.createOffer(peerConnection.setLocalDescription.bind(peerConnection), () => { })

    peerConnection.addEventListener("icecandidateerror", (event) => {
        throw new Error(event.errorText)
    })

    return new Promise(async resolve => {
        peerConnection.addEventListener("icecandidate", async ({candidate}) => {
            peerConnection.close()
            
            if (candidate && candidate.candidate) {
                const result = candidate.candidate.split(" ")[4]
                if (result.endsWith(".local")) {
                    const inputDevices = await navigator.mediaDevices.enumerateDevices()
                    const inputDeviceTypes = inputDevices.map(({ kind }) => kind)

                    const constraints = {}

                    if (inputDeviceTypes.includes("audioinput")) {
                        constraints.audio = true
                    } else if (inputDeviceTypes.includes("videoinput")) {
                        constraints.video = true
                    } else {
                        throw new Error("An audio or video input device is required!")
                    }

                    const mediaStream = await navigator.mediaDevices.getUserMedia(constraints)
                    mediaStream.getTracks().forEach(track => track.stop())
                    resolve(internalIp())
                }
                resolve(result)
            }
        })
    })
}

Sample database for exercise

You want huge?

Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));

insert into foo(crap) values ('');

-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;

run it twenty more times, you have over a million rows to play with.

Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)

Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".

Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.

Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.

Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.

For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.

Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.

By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.

How can I get the number of records affected by a stored procedure?

For Microsoft SQL Server you can return the @@ROWCOUNT variable to return the number of rows affected by the last statement in the stored procedure.

IOS 7 Navigation Bar text and arrow color

enter image description here

This one took me about half a day to figure out but this is what worked for me. Inside the rootViewController that initializes the navigationController, I put this code inside my viewDidAppear method:

//set bar color
[self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:85.0/255.0 green:143.0/255.0 blue:220.0/255.0 alpha:1.0]];
//optional, i don't want my bar to be translucent
[self.navigationController.navigationBar setTranslucent:NO];
//set title and title color
[self.navigationItem setTitle:@"Title"];
[self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor]];
//set back button color
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor,nil] forState:UIControlStateNormal];
//set back button arrow color
[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];

My full post on this here

How to iterate through an ArrayList of Objects of ArrayList of Objects?

You want to follow the same pattern as before:

for (Type curInstance: CollectionOf<Type>) {
  // use currInstance
}

In this case it would be:

for (Bullet bullet : gunList.get(2).getBullet()) {
   System.out.println(bullet);
}

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

Project Properties -> Compile -> Target CPU -> Any CPU And uncheck Prefer 32 bit

Done

How can I use optional parameters in a T-SQL stored procedure?

Five years late to the party.

It is mentioned in the provided links of the accepted answer, but I think it deserves an explicit answer on SO - dynamically building the query based on provided parameters. E.g.:

Setup

-- drop table Person
create table Person
(
    PersonId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Person PRIMARY KEY,
    FirstName NVARCHAR(64) NOT NULL,
    LastName NVARCHAR(64) NOT NULL,
    Title NVARCHAR(64) NULL
)
GO

INSERT INTO Person (FirstName, LastName, Title)
VALUES ('Dick', 'Ormsby', 'Mr'), ('Serena', 'Kroeger', 'Ms'), 
    ('Marina', 'Losoya', 'Mrs'), ('Shakita', 'Grate', 'Ms'), 
    ('Bethann', 'Zellner', 'Ms'), ('Dexter', 'Shaw', 'Mr'),
    ('Zona', 'Halligan', 'Ms'), ('Fiona', 'Cassity', 'Ms'),
    ('Sherron', 'Janowski', 'Ms'), ('Melinda', 'Cormier', 'Ms')
GO

Procedure

ALTER PROCEDURE spDoSearch
    @FirstName varchar(64) = null,
    @LastName varchar(64) = null,
    @Title varchar(64) = null,
    @TopCount INT = 100
AS
BEGIN
    DECLARE @SQL NVARCHAR(4000) = '
        SELECT TOP ' + CAST(@TopCount AS VARCHAR) + ' *
        FROM Person
        WHERE 1 = 1'

    PRINT @SQL

    IF (@FirstName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @FirstName'
    IF (@LastName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @LastName'
    IF (@Title IS NOT NULL) SET @SQL = @SQL + ' AND Title = @Title'

    EXEC sp_executesql @SQL, N'@TopCount INT, @FirstName varchar(25), @LastName varchar(25), @Title varchar(64)', 
         @TopCount, @FirstName, @LastName, @Title
END
GO

Usage

exec spDoSearch @TopCount = 3
exec spDoSearch @FirstName = 'Dick'

Pros:

  • easy to write and understand
  • flexibility - easily generate the query for trickier filterings (e.g. dynamic TOP)

Cons:

  • possible performance problems depending on provided parameters, indexes and data volume

Not direct answer, but related to the problem aka the big picture

Usually, these filtering stored procedures do not float around, but are being called from some service layer. This leaves the option of moving away business logic (filtering) from SQL to service layer.

One example is using LINQ2SQL to generate the query based on provided filters:

    public IList<SomeServiceModel> GetServiceModels(CustomFilter filters)
    {
        var query = DataAccess.SomeRepository.AllNoTracking;

        // partial and insensitive search 
        if (!string.IsNullOrWhiteSpace(filters.SomeName))
            query = query.Where(item => item.SomeName.IndexOf(filters.SomeName, StringComparison.OrdinalIgnoreCase) != -1);
        // filter by multiple selection
        if ((filters.CreatedByList?.Count ?? 0) > 0)
            query = query.Where(item => filters.CreatedByList.Contains(item.CreatedById));
        if (filters.EnabledOnly)
            query = query.Where(item => item.IsEnabled);

        var modelList = query.ToList();
        var serviceModelList = MappingService.MapEx<SomeDataModel, SomeServiceModel>(modelList);
        return serviceModelList;
    }

Pros:

  • dynamically generated query based on provided filters. No parameter sniffing or recompile hints needed
  • somewhat easier to write for those in the OOP world
  • typically performance friendly, since "simple" queries will be issued (appropriate indexes are still needed though)

Cons:

  • LINQ2QL limitations may be reached and forcing a downgrade to LINQ2Objects or going back to pure SQL solution depending on the case
  • careless writing of LINQ might generate awful queries (or many queries, if navigation properties loaded)

What is the difference between procedural programming and functional programming?

Funtional Programming

num = 1 
def function_to_add_one(num):
    num += 1
    return num


function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)
function_to_add_one(num)

#Final Output: 2

Procedural Programming

num = 1 
def procedure_to_add_one():
    global num
    num += 1
    return num


procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()
procedure_to_add_one()

#Final Output: 6

function_to_add_one is a function

procedure_to_add_one is a procedure

Even if you run the function five times, every time it will return 2

If you run the procedure five times, at the end of fifth run it will give you 6.

DISCLAIMER: Obviously this is a hyper-simplified view of reality. This answer just gives a taste of "functions" as opposed to "procedures". Nothing more. Once you have tasted this superficial yet deeply penetrative intuition, start exploring the two paradigms, and you will start to see the difference quite clearly.

Helps my students, hope it helps you too.

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

What certificates are trusted in truststore?

Is there any equivalent for the truststore? How can I view the trusted certificates?

Yes there is.The exact same command since keystore and truststore differ only in what they store i.e. private key or signed public key (certificate)

No other difference

How to add a default "Select" option to this ASP.NET DropDownList control?

Private Sub YourWebPage_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete

     If Not IsPostBack Then
     DropDownList1.Items.Insert(0, "Select")
     End If

End Sub

What is the simplest SQL Query to find the second largest value?

SELECT 
    * 
FROM 
    table 
WHERE 
    column < (SELECT max(columnq) FROM table) 
ORDER BY 
    column DESC LIMIT 1

SQLite error 'attempt to write a readonly database' during insert?

I used:

echo exec('whoami');

to find out who is running the script (say username), and then gave the user permissions to the entire application directory, like:

sudo chown -R :username /var/www/html/myapp

Hope this helps someone out there.

Rails 3.1 and Image Assets

The asset pipeline in rails offers a method for this exact thing.

You simply add image_path('image filename') to your css or scss file and rails takes care of everything. For example:

.logo{ background:url(image_path('admin/logo.png'));

(note that it works just like in a .erb view, and you don't use "/assets" or "/assets/images" in the path)

Rails also offers other helper methods, and there's another answer here: How do I use reference images in Sass when using Rails 3.1?

How to detect when a UIScrollView has finished scrolling

To recap (and for newbies). It's not that painful. Just add the protocol, then add the functions you need for detection.

In the view (class) that contains the UIScrolView, add the protocol, then added any the functions from here to your view (class).

// --------------------------------
// In the "h" file:
// --------------------------------
@interface myViewClass : UIViewController  <UIScrollViewDelegate> // <-- Adding the protocol here

// Scroll view
@property (nonatomic, retain) UIScrollView *myScrollView;
@property (nonatomic, assign) BOOL isScrolling;

// Protocol functions
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView;


// --------------------------------
// In the "m" file:
// --------------------------------
@implementation BlockerViewController

- (void)viewDidLoad {
    CGRect scrollRect = self.view.frame; // Same size as this view
    self.myScrollView = [[UIScrollView alloc] initWithFrame:scrollRect];
    self.myScrollView.delegate = self;
    self.myScrollView.contentSize = CGSizeMake(scrollRect.size.width, scrollRect.size.height);
    self.myScrollView.contentInset = UIEdgeInsetsMake(0.0,22.0,0.0,22.0);
    // Allow dragging button to display outside the boundaries
    self.myScrollView.clipsToBounds = NO;
    // Prevent buttons from activating scroller:
    self.myScrollView.canCancelContentTouches = NO;
    self.myScrollView.delaysContentTouches = NO;
    [self.myScrollView setBackgroundColor:[UIColor darkGrayColor]];
    [self.view addSubview:self.myScrollView];

    // Add stuff to scrollview
    UIImage *myImage = [UIImage imageNamed:@"foo.png"];
    [self.myScrollView addSubview:myImage];
}

// Protocol functions
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"start drag");
    _isScrolling = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"end decel");
    _isScrolling = NO;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"end dragging");
    if (!decelerate) {
       _isScrolling = NO;
    }
}

// All of the available functions are here:
// https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScrollViewDelegate_Protocol/Reference/UIScrollViewDelegate.html

Android set bitmap to Imageview

this code works with me

 ImageView carView = (ImageView) v.findViewById(R.id.car_icon);

                            byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                            InputStream input=new ByteArrayInputStream(decodedString);
                            Bitmap ext_pic = BitmapFactory.decodeStream(input);
                            carView.setImageBitmap(ext_pic);

File Not Found when running PHP with Nginx

After upgrading to PHP72, we had an issue where the php-fpm.d/www.conf lost the settings for user/group which was causing this error. Be sure to double check those if your setup involves php-fpm.

UILabel text margin

If you're using autolayout in iOS 6+, you can do this by adjusting the intrinsicContentSize in a subclass of UILabel.

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.textAlignment = NSTextAlignmentRight;
    }
    return self;
}

- (CGSize)intrinsicContentSize 
{
    CGSize size = [super intrinsicContentSize];
    return CGSizeMake(size.width + 10.0, size.height);
}

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

psql: FATAL: Ident authentication failed for user "postgres"

I've spent more time solving this error that I care to admit.

The order of authentication configuration in pg_hba.conf is relevant in your case I think. The default configuration file includes several lines in a vanilla install. These defaults can match the conditions of your authentication attempts resulting in a failure to authenticate. It fails regardless of additional configuration added at the end of the .conf file.

To check which line of configuration is use make sure to look at the default log file for messages. You might see something like this

LOG:  could not connect to Ident server at address "127.0.0.1", port 113: Connection refused
FATAL:  Ident authentication failed for user "acme" 
DETAIL:  Connection matched pg_hba.conf line 82: "host     all             all             127.0.0.1/32            ident"

It turns out this default line is causing the rejection.

host    all             all             127.0.0.1/32            ident

try commenting it out.

Count number of records returned by group by

Try this query:

select top 1 TotalRows = count(*) over () 
from yourTable
group by column1, column2

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

Take note of what is printed for x. You are trying to convert an array (basically just a list) into an int. length-1 would be an array of a single number, which I assume numpy just treats as a float. You could do this, but it's not a purely-numpy solution.

EDIT: I was involved in a post a couple of weeks back where numpy was slower an operation than I had expected and I realised I had fallen into a default mindset that numpy was always the way to go for speed. Since my answer was not as clean as ayhan's, I thought I'd use this space to show that this is another such instance to illustrate that vectorize is around 10% slower than building a list in Python. I don't know enough about numpy to explain why this is the case but perhaps someone else does?

import numpy as np
import matplotlib.pyplot as plt
import datetime

time_start = datetime.datetime.now()

# My original answer
def f(x):
    rebuilt_to_plot = []
    for num in x:
        rebuilt_to_plot.append(np.int(num))
    return rebuilt_to_plot

for t in range(10000):
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f(x))

time_end = datetime.datetime.now()

# Answer by ayhan
def f_1(x):
    return np.int(x)

for t in range(10000):
    f2 = np.vectorize(f_1)
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f2(x))

time_end_2 = datetime.datetime.now()

print time_end - time_start
print time_end_2 - time_end

"replace" function examples

If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<- function which is described at ?"[". [ is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:

You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":

> replace( 1:20, 10:15, 1:2)
 [1]  1  2  3  4  5  6  7  8  9  1  2  1  2  1  2 16 17 18 19 20

Character indexing for a named vector:

> replace(c(a=1, b=2, c=3, d=4), "b", 10)
 a  b  c  d 
 1 10  3  4 

Logical indexing:

> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
 a  b  c  d 
 1  2 10 10 

What is the difference between Sublime text and Github's Atom

Atom is open source (has been for a few hours by now), whereas Sublime Text is not.

How to use a variable in the replacement side of the Perl substitution operator?

See THIS previous SO post on using a variable on the replacement side of s///in Perl. Look both at the accepted answer and the rebuttal answer.

What you are trying to do is possible with the s///ee form that performs a double eval on the right hand string. See perlop quote like operators for more examples.

Be warned that there are security impilcations of evaland this will not work in taint mode.

MySQL date formats - difficulty Inserting a date

The date format for mysql insert query is YYYY-MM-DD

example:

INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Faced the same issue and resolved by upgrading my Maven from 3.0.4 to 3.1.1. Please try with v3.1.1 or any higher version if available

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Presenting a UIAlertController properly on an iPad using iOS 8

For me I just needed to add the following:

if let popoverController = alertController.popoverPresentationController {
    popoverController.barButtonItem = navigationItem.rightBarButtonItem
}

How to read from input until newline is found using scanf()?

Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().

Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.

How to change the current URL in javascript?

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

You can then call it like this:

window.location.href = nextImage();

Demo here: http://jsfiddle.net/jfriend00/3VPEq/

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

T-SQL to list all the user mappings with database roles/permissions for a Login

I wrote a little query to find permission of a user on a specific database.

    SELECT * FROM   
    (
    SELECT 
    perm.permission_name AS 'PERMISSION'
    ,perm.state_desc AS 'RIGHT'
    ,perm.class_desc AS 'RIGHT_ON'
    ,p.NAME AS 'GRANTEE'
    ,m.NAME AS 'USERNAME'
    ,s.name AS 'SCHEMA'
    ,o.name AS 'OBJECT'
    ,IIF(perm.class = 0, db_name(), NULL) AS 'DATABASE'
    FROM
    sys.database_permissions perm
    INNER JOIN sys.database_principals p ON p.principal_id = perm.grantee_principal_id
    LEFT JOIN sys.database_role_members rm ON rm.role_principal_id = p.principal_id
    LEFT JOIN sys.database_principals m ON rm.member_principal_id = m.principal_id
    LEFT JOIN sys.schemas s ON perm.class = 3 AND perm.major_id = s.schema_id
    LEFT JOIN sys.objects AS o ON perm.class = 1 AND perm.major_id = o.object_id
    UNION ALL
    SELECT 
    perm.permission_name AS 'PERMISSION'
    ,perm.state_desc AS 'RIGHT'
    ,perm.class_desc AS 'RIGHT_ON'
    ,'SELF-GRANTED' AS 'GRANTEE'
    ,p.NAME AS 'USERNAME'
    ,s.name AS 'SCHEMA'
    ,o.name AS 'OBJECT'
    ,IIF(perm.class = 0, db_name(), NULL) AS 'DATABASE'
    FROM
    sys.database_permissions perm
    INNER JOIN sys.database_principals p ON p.principal_id = perm.grantee_principal_id
    LEFT JOIN sys.schemas s ON perm.class = 3 AND perm.major_id = s.schema_id
    LEFT JOIN sys.objects AS o ON perm.class = 1 AND perm.major_id = o.object_id
    ) AS [union]
    WHERE [union].USERNAME = 'Username' -- Username you will search for
    ORDER BY [union].RIGHT_ON, [union].PERMISSION, [union].GRANTEE

The permissions of fixed database roles do not appear in sys.database_permissions. Therefore, database principals may have additional permissions not listed here.

I does not prefer

    EXECUTE AS USER = 'userName';
    SELECT * FROM fn_my_permissions(NULL, 'DATABASE') 

Because it's just retrieving which permissions the user has not where they come from!

Maybe i find out how to join the fixed database roles permission granted for the user one day...

Pls enjoy Life and hate the Users :D

Set the value of an input field

You can also try:

document.getElementById('theID').value = 'new value';

docker mounting volumes on host

The VOLUME command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.

The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.

You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from command when you run a container.

The fundamental difference between VOLUME and -v is this: -v will mount existing files from your operating system inside your docker container and VOLUME will create a new, empty volume on your host and mount it inside your container.

Example:

  1. You have a Dockerfile that defines a VOLUME /var/lib/mysql.
  2. You build the docker image and tag it some-volume
  3. You run the container

And then,

  1. You have another docker image that you want to use this volume
  2. You run the docker container with the following: docker run --volumes-from some-volume docker-image-name:tag
  3. Now you have a docker container running that will have the volume from some-volume mounted in /var/lib/mysql

Note: Using --volumes-from will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql, it will be replaced with the contents of the volume.

Using Get-childitem to get a list of files modified in the last 3 days

Try this:

(Get-ChildItem -Path c:\pstbak\*.* -Filter *.pst | ? {
  $_.LastWriteTime -gt (Get-Date).AddDays(-3) 
}).Count

How to hide Bootstrap modal with javascript?

I realize this is an old question, but I found that none of these were really what I was looking for exactly. It seems to be caused by trying to close the modal before it's finished showing.

My solution was based on @schoonie23's answer but I had to change a few things.

First, I declared a global variable at the top of my script:

<script>
    var closeModal = false;
    ...Other Code...

Then in my modal code:

$('#myModal').on('show.bs.modal', function (event) {
    ...Some Code...
    if (someReasonToHideModal) {
        closeModal = true;
        return;
    }
    ...Other Code...

Then this: (Note the name 'shown.bs.modal' indicating that the modal has shown completely as opposed to 'show' that triggers when the show event is called. (I originally tried just 'shown' but it did not work.)

$('#myModal').on('shown.bs.modal', function (event) {
    if (closeEditModal) {
        $('#myModal').modal('hide');
        closeModal = false;
    }
});

Hope this saves someone the extra research some day. I spent a bit looking for a solution before I came up with this.

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

How to declare a variable in a template in Angular

If you need autocomplete support from within in your templates from the Angular Language Service:

Synchronous:

myVar = { hello: '' };

<ng-container *ngIf="myVar; let var;">
  {{var.hello}}
</ng-container>

Using async pipe:

myVar$ = of({ hello: '' });

<ng-container *ngIf="myVar$ | async; let var;">
  {{var.hello}}
</ng-container>

Is there a way to get a list of column names in sqlite?

As far as I can tell Sqlite doesn't support INFORMATION_SCHEMA. Instead it has sqlite_master.

I don't think you can get the list you want in just one command. You can get the information you need using sql or pragma, then use regex to split it into the format you need

SELECT sql FROM sqlite_master WHERE name='tablename';

gives you something like

CREATE TABLE tablename(
        col1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        col2 NVARCHAR(100) NOT NULL,
        col3 NVARCHAR(100) NOT NULL,
)

Or using pragma

PRAGMA table_info(tablename);

gives you something like

0|col1|INTEGER|1||1
1|col2|NVARCHAR(100)|1||0
2|col3|NVARCHAR(100)|1||0

Try-catch-finally-return clarification

Here is some code that show how it works.

class Test
{
    public static void main(String args[]) 
    { 
        System.out.println(Test.test()); 
    }

    public static String test()
    {
        try {
            System.out.println("try");
            throw new Exception();
        } catch(Exception e) {
            System.out.println("catch");
            return "return"; 
        } finally {  
            System.out.println("finally");
            return "return in finally"; 
        }
    }
}

The results is:

try
catch
finally
return in finally

Obtain form input fields using jQuery?

If you need to get multiple values from inputs and you're using []'s to define the inputs with multiple values, you can use the following:

$('#contentform').find('input, textarea, select').each(function(x, field) {
    if (field.name) {
        if (field.name.indexOf('[]')>0) {
            if (!$.isArray(data[field.name])) {
               data[field.name]=new Array();
            }
            data[field.name].push(field.value);
        } else {
            data[field.name]=field.value;
        }
    }                   
});

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

maximum value of int

O.K. I neither have rep to comment on previous answer (of Philippe De Muyter) nor raise it's score, hence a new example using his define for SIGNED_MAX trivially extended for unsigned types:

// We can use it to define limits based on actual compiler built-in types also: 
#define INT_MAX   SIGNED_MAX(int)
// based on the above, we can extend it for unsigned types also:
#define UNSIGNED_MAX(x) (  (SIGNED_MAX(x)<<1) | 1 ) // We reuse SIGNED_MAX
#define UINT_MAX  UNSIGNED_MAX(unsigned int) // on ARM: 4294967295
// then we can have:
unsigned int width = UINT_MAX;

Unlike using this or that header, here we use the real type from the compiler.

Specifying width and height as percentages without skewing photo proportions in HTML

You can set one or the other (just not both) and that should get the result you want.

<img src="#" height="50%">

Remove 'b' character do in front of a string literal in Python 3

Here u Go

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

PHP: Inserting Values from the Form into MySQL

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)
    VALUES (?,?,?)";

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

How to split a string of space separated numbers into integers?

I suggest checking if the substring is a digit:

In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]

angularjs - ng-repeat: access key and value from JSON array object

try this..

<tr ng-repeat='item in items'>
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>

How to display a PDF via Android web browser without "downloading" first

  • Download the acrobat reader .apk file for android to display pdf file
  • Put your pdf files on an sd card
  • Use the snippet of code below

    File file= new File("/sdcard/test.pdf");
    Uri path=Uri.fromFile(file);
    Intent i =new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(path,"application/pdf");
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    

How can I see function arguments in IPython Notebook Server 3?

Shift-Tab works for me to view the dcoumentation

Load image from url

Try this:

InputStream input = contentResolver.openInputStream(httpuri);
Bitmap b = BitmapFactory.decodeStream(input, null, options);

How to debug PDO database queries?

You say this :

I never see the final query as it's sent to the database

Well, actually, when using prepared statements, there is no such thing as a "final query" :

  • First, a statement is sent to the DB, and prepared there
    • The database parses the query, and builds an internal representation of it
  • And, when you bind variables and execute the statement, only the variables are sent to the database
    • And the database "injects" the values into its internal representation of the statement


So, to answer your question :

Is there a way capture the complete SQL query sent by PDO to the database and log it to a file?

No : as there is no "complete SQL query" anywhere, there is no way to capture it.


The best thing you can do, for debugging purposes, is "re-construct" an "real" SQL query, by injecting the values into the SQL string of the statement.

What I usually do, in this kind of situations, is :

  • echo the SQL code that corresponds to the statement, with placeholders
  • and use var_dump (or an equivalent) just after, to display the values of the parameters
  • This is generally enough to see a possible error, even if you don't have any "real" query that you can execute.

This is not great, when it comes to debugging -- but that's the price of prepared statements and the advantages they bring.

firestore: PERMISSION_DENIED: Missing or insufficient permissions

npm i --save firebase @angular/fire

in app.module make sure you imported

import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

in imports

AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    AngularFireAuthModule,

in realtime database rules make sure you have

{
  /* Visit  rules. */
  "rules": {
    ".read": true,
    ".write": true
  }
}

in cloud firestore rules make sure you have

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Android Studio Gradle Already disposed Module

Although the accepted answer didn't work for me (unfortunately I can't leave a comment), it led me in the right direction.

in .idea/libraries i found that there were some duplicate xml files (the duplicates were named with a 2 before the _aar.xml bit).

deleting those, restarting android studio and sync fixed the error

Add button to navigationbar programmatically

Swift version, add this in viewDidLoad:

var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneButton:")
navigationItem.rightBarButtonItem = doneButton

And this in your View Controller class

func doneButton(sender: UIBarButtonItem) {
    println(111)
}

Ubuntu - Run command on start-up with "sudo"

Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:

Using '@reboot' you can Run a command once, at startup.

Wrapping up: run $ sudo crontab -e -u root

And add a line at the end of the file with your command as follows:

@reboot sudo searchd

When should an IllegalArgumentException be thrown?

Any API should check the validity of the every parameter of any public method before executing it:

void setPercentage(int pct, AnObject object) {
    if( pct < 0 || pct > 100) {
        throw new IllegalArgumentException("pct has an invalid value");
    }
    if (object == null) {
        throw new IllegalArgumentException("object is null");
    }
}

They represent 99.9% of the times errors in the application because it is asking for impossible operations so in the end they are bugs that should crash the application (so it is a non recoverable error).

In this case and following the approach of fail fast you should let the application finish to avoid corrupting the application state.

Notification bar icon turns white in Android 5 Lollipop

If you're using GoogleFireBaseMessaging, you can set "icon id" in the "notification" payload (it helps me to solve the white bar icon problem):

{
    "to":"<fb_id>",
    "priority" : "high",
    "notification" : 
    {
        "title" : "title",
        "body" : "body" ,
        "sound" : "default",
        "icon" : "ic_notification"
    }
}

set ic_notification to your own id from R.drawable.

Ruby: How to post a file via HTTP as multipart/form-data?

Fast forward to 2017, ruby stdlib net/http has this built-in since 1.9.3

Net::HTTPRequest#set_form): Added to support both application/x-www-form-urlencoded and multipart/form-data.

https://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTPHeader.html#method-i-set_form

We can even use IO which does not support :size to stream the form data.

Hoping that this answer can really help someone :)

P.S. I only tested this in ruby 2.3.1

How to convert the background to transparent?

Quick solution without downloading anything is to use online editors that has "Magic Wand Tool".

Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

Safely override C++ virtual functions

Something like C#'s override keyword is not part of C++.

In gcc, -Woverloaded-virtual warns against hiding a base class virtual function with a function of the same name but a sufficiently different signature that it doesn't override it. It won't, though, protect you against failing to override a function due to mis-spelling the function name itself.

Go to beginning of line without opening new line in VI

I just found 0(zero) and shift+0 works on vim.

How to use JNDI DataSource provided by Tomcat in Spring?

I found this solution very helpful in a clean way to remove xml configuration entirely.

Please check this db configuration using JNDI and spring framework. http://www.unotions.com/design/how-to-create-oracleothersql-db-configuration-using-spring-and-maven/

By this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.

How to check if a value exists in a dictionary (python)

>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> 'one' in d.values()
True

Out of curiosity, some comparative timing:

>>> T(lambda : 'one' in d.itervalues()).repeat()
[0.28107285499572754, 0.29107213020324707, 0.27941107749938965]
>>> T(lambda : 'one' in d.values()).repeat()
[0.38303399085998535, 0.37257885932922363, 0.37096405029296875]
>>> T(lambda : 'one' in d.viewvalues()).repeat()
[0.32004380226135254, 0.31716084480285645, 0.3171098232269287]

EDIT: And in case you wonder why... the reason is that each of the above returns a different type of object, which may or may not be well suited for lookup operations:

>>> type(d.viewvalues())
<type 'dict_values'>
>>> type(d.values())
<type 'list'>
>>> type(d.itervalues())
<type 'dictionary-valueiterator'>

EDIT2: As per request in comments...

>>> T(lambda : 'four' in d.itervalues()).repeat()
[0.41178202629089355, 0.3959040641784668, 0.3970959186553955]
>>> T(lambda : 'four' in d.values()).repeat()
[0.4631338119506836, 0.43541407585144043, 0.4359898567199707]
>>> T(lambda : 'four' in d.viewvalues()).repeat()
[0.43414998054504395, 0.4213531017303467, 0.41684913635253906]

C# Interfaces. Implicit implementation versus Explicit implementation

The previous answers explain why implementing an interface explicitly in C# may be preferrable (for mostly formal reasons). However, there is one situation where explicit implementation is mandatory: In order to avoid leaking the encapsulation when the interface is non-public, but the implementing class is public.

// Given:
internal interface I { void M(); }

// Then explicit implementation correctly observes encapsulation of I:
// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.
public class CExplicit: I { void I.M() { } }

// However, implicit implementation breaks encapsulation of I, because
// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.
public class CImplicit: I { public void M() { } }

The above leakage is unavoidable because, according to the C# specification, "All interface members implicitly have public access." As a consequence, implicit implementations must also give public access, even if the interface itself is e.g. internal.

Implicit interface implementation in C# is a great convenience. In practice, many programmers use it all the time/everywhere without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, don't even allow it.

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

cannot download, $GOPATH not set

If you run into this problem after having $GOPATH set up, it may be because you're running it with an unsupported shell. I was using fish and it did not work, launching it with bash worked fine.

Finding the 'type' of an input element

Check the type property. Would that suffice?

HTML Mobile -forcing the soft keyboard to hide

example how i made it , After i fill a Maximum length it will blur from my Field (and the Keyboard will disappear ) , if you have more than one field , you can just add the line that i add '//'

var MaxLength = 8;
    $(document).ready(function () {
        $('#MyTB').keyup(function () {
            if ($(this).val().length >= MaxLength) {
               $('#MyTB').blur();
             //  $('#MyTB2').focus();
         }
          }); });

move a virtual machine from one vCenter to another vCenter

I've figure it out the solution to my problem:

  • Step 1: from within the vSphere client, while connected to vCenter1, select the VM and then from "File" menu select "Export"->"Export OVF Template" (Note: make sure the VM is Powered Off otherwise this feature is not available - it will be gray). This action will allow you to save on your machine/laptop the VM (as an .vmdk, .ovf and a .mf file).
  • Step 2: Connect to the vCenter2 with your vSphere client and from "File" menu select "Deploy OVF Template..." and then select the location where the VM was saved in the previous step.

That was all!
Thanks!

HTML to PDF with Node.js

Create PDF from External URL

Here's an adaptation of the previous answers which utilizes html-pdf, but also combines it with requestify so it works with an external URL:

Install your dependencies

npm i -S html-pdf requestify

Then, create the script:

//MakePDF.js

var pdf = require('html-pdf');
var requestify = require('requestify');
var externalURL= 'http://www.google.com';

requestify.get(externalURL).then(function (response) {
   // Get the raw HTML response body
   var html = response.body; 
   var config = {format: 'A4'}; // or format: 'letter' - see https://github.com/marcbachmann/node-html-pdf#options

// Create the PDF
   pdf.create(html, config).toFile('pathtooutput/generated.pdf', function (err, res) {
      if (err) return console.log(err);
      console.log(res); // { filename: '/pathtooutput/generated.pdf' }
   });
});

Then you just run from the command line:

node MakePDF.js

Watch your beautify pixel perfect PDF be created for you (for free!)

Hibernate: hbm2ddl.auto=update in production?

I agree with Vladimir. The administrators in my company would definitely not appreciate it if I even suggested such a course.

Further, creating an SQL script in stead of blindly trusting Hibernate gives you the opportunity to remove fields which are no longer in use. Hibernate does not do that.

And I find comparing the production schema with the new schema gives you even better insight to wat you changed in the data model. You know, of course, because you made it, but now you see all the changes in one go. Even the ones which make you go like "What the heck?!".

There are tools which can make a schema delta for you, so it isn't even hard work. And then you know exactly what's going to happen.

Converting Select results into Insert script - SQL Server

Using visual studio, do the following

Create a project of type SQL Server-->SQL Server Database Project

open the sql server explorer CTL-\ , CTL-S

add a SQL Server by right clicking on the SQL SERVER icon. Selcet ADD NEW SERVER

navigate down to the table you are interested in

right click--> VIEW DATA

Click the top left cell to highlight everything (ctl-A doesnt seem to work)

Right Click -->SCript

This is fabulous. I have tried everything listed above over the years. I know there is a tool out there that will do this and much more, cant think of the name of it. But it is very expensive.

Good luck. I just figured this out. Have not tested it extensively w/ text fields etc, but it looks like it gets you a long ways down the road.

Greg

Could not find module FindOpenCV.cmake ( Error in configuration process)

find / -name "OpenCVConfig.cmake"

export OpenCV_DIR=/path/found/above

Moment.js - How to convert date string into date?

Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');

Dec 4, 2020 4:58 PM

OtherFormats

moment.locale();         // en
moment().format('LT');   // 4:59 PM
moment().format('LTS');  // 4:59:47 PM
moment().format('L');    // 12/08/2020
moment().format('l');    // 12/8/2020
moment().format('LL');   // December 8, 2020
moment().format('ll');   // Dec 8, 2020
moment().format('LLL');  // December 8, 2020 4:59 PM
moment().format('lll');  // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM

Suppress Scientific Notation in Numpy When Creating Array From Nested List

You could write a function that converts a scientific notation to regular, something like

def sc2std(x):
    s = str(x)
    if 'e' in s:
        num,ex = s.split('e')
        if '-' in num:
            negprefix = '-'
        else:
            negprefix = ''
        num = num.replace('-','')
        if '.' in num:
            dotlocation = num.index('.')
        else:
            dotlocation = len(num)
        newdotlocation = dotlocation + int(ex)
        num = num.replace('.','')
        if (newdotlocation < 1):
            return negprefix+'0.'+'0'*(-newdotlocation)+num
        if (newdotlocation > len(num)):
            return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
        return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
    else:
        return s

can you add HTTPS functionality to a python flask web server?

Deploy Flask on a real web server, rather than with the built-in (development) server.

See the Deployment Options chapter of the Flask documentation. Servers like Nginx and Apache both can handle setting up HTTPS servers rather than HTTP servers for your site.

The standalone WSGI servers listed would typically be deployed behind Nginx and Apache in a proxy-forwarding configuration, where the front-end server handles the SSL encryption for you still.

How to extract svg as file from web page

1. Inspect the page with the svg on.

2. Click on the link that displays the imagine in full resolution.

3. Do CMD/CTRL+S

4. You are done!

Django, creating a custom 500/404 error page

settings.py:

DEBUG = False
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = ['localhost']  #provide your host name

and just add your 404.html and 500.html pages in templates folder. remove 404.html and 500.html from templates in polls app.

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

How to generate XML from an Excel VBA macro?

Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)

Script:

Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
    Dim Q As String
    Q = Chr$(34)

    Dim sXML As String

    sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
    sXML = sXML & "<rows>"


    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1
    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend

    Dim iRow As Integer
    iRow = iDataStartRow

    While Cells(iRow, 1) > ""
        sXML = sXML & "<row id=" & Q & iRow & Q & ">"

        For icol = 1 To iColCount - 1
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
           sXML = sXML & Trim$(Cells(iRow, icol))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
        Next

        sXML = sXML & "</row>"
        iRow = iRow + 1
    Wend
    sXML = sXML & "</rows>"

    Dim nDestFile As Integer, sText As String

    ''Close any open text files
    Close

    ''Get the number of the next free text file
    nDestFile = FreeFile

    ''Write the entire file to sText
    Open sOutputFileName For Output As #nDestFile
    Print #nDestFile, sXML
    Close
End Sub

Sub test()
    MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

Java - Convert integer to string

One that I use often:

 Integer.parseInt("1234");

Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you'd have to ask someone else.

Return different type of data from a method in java?

This can be one of the solution. But your present solution is good enough. You can also add new variables and still keep it clean, which cannot be done with present code.

private static final int INDEX_OF_STRING_PARAM = 0;
private static final int INDEX_OF_INT_PARAM = 1;

public static Object[] myMethod() {
    Object[] values = new Object[2];
    values[INDEX_OF_STRING_PARAM] = "value";
    values[INDEX_OF_INT_PARAM] = 12;
    return values;
}

CSS performance relative to translateZ(0)

On mobile devices sending everything to the GPU will cause a memory overload and crash the application. I encountered this on an iPad app in Cordova. Best to only send the required items to the GPU, the divs that you're specifically moving around.

Better yet, use the 3d transitions transforms to do the animations like translateX(50px) as opposed to left:50px;

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

In your configurations, specify the port number your database is on. You can find the port number at the top left corner of phpMyAdmin. It would look something like this

const DB_HOST = 'localhost:3308';

Convert multiple rows into one with comma as separator

building on mwigdahls answer. if you also need to do grouping here is how to get it to look like

group, csv
'group1', 'paul, john'
'group2', 'mary'

    --drop table #user
create table #user (groupName varchar(25), username varchar(25))

insert into #user (groupname, username) values ('apostles', 'Paul')
insert into #user (groupname, username) values ('apostles', 'John')
insert into #user (groupname, username) values ('family','Mary')


select
    g1.groupname
    , stuff((
        select ', ' + g.username
        from #user g        
        where g.groupName = g1.groupname        
        order by g.username
        for xml path('')
    ),1,2,'') as name_csv
from #user g1
group by g1.groupname

Meaning of delta or epsilon argument of assertEquals for double values

Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!

From the JUnit javadoc:

delta - the maximum delta between expected and actual for which both numbers are still considered equal.

It's probably overkill, but I typically use a really small number, e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertEquals(123.456, 123.456, DELTA);
}

If you're using hamcrest assertions, you can just use the standard equalTo() with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo() (see javadoc), e.g.

private static final double DELTA = 1e-15;

@Test
public void testDelta(){
    assertThat(123.456, equalTo(123.456));
    assertThat(123.456, closeTo(123.456, DELTA));
}

FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals() with two doubles. The implementation (if you're interested) is:

private static boolean doublesAreEqual(double value1, double value2) {
    return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties
}

interface ResponseOrders {
  results: Order[];
}

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       params
    }).pipe(
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))
    );
} 

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().

ORIGINAL ANSWER:

In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties
}

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
       params
    })
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
  }
} 

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

How do I change the JAVA_HOME for ant?

JAVA_HOME should point at where the JDK is installed not not a JRE.

So, if you type ls $JAVA_HOME what do you see? if you do ls $JAVA_HOME/bin/ do you see javac?

If the first doesn't work then you don't have JAVA_HOME pointing at the right directory. If the second doesn't work then you need to point JAVA_HOME at a JDK instead of a JRE.

Send JSON data with jQuery

You need to set the correct content type and stringify your object.

var arr = {City:'Moscow', Age:25};
$.ajax({
    url: "Ajax.ashx",
    type: "POST",
    data: JSON.stringify(arr),
    dataType: 'json',
    async: false,
    contentType: 'application/json; charset=utf-8',
    success: function(msg) {
        alert(msg);
    }
});

How to compile a c++ program in Linux?

Try this:

g++ -o hi hi.cpp

gcc is only for C

Setting default values for columns in JPA

In 2017, JPA 2.1 still has only @Column(columnDefinition='...') to which you put the literal SQL definition of the column. Which is quite unflexible and forces you to also declare the other aspects like type, short-circuiting the JPA implementation's view on that matter.

Hibernate though, has this:

@Column(length = 4096, nullable = false)
@org.hibernate.annotations.ColumnDefault("")
private String description;

Identifies the DEFAULT value to apply to the associated column via DDL.

Two notes to that:

1) Don't be afraid of going non-standard. Working as a JBoss developer, I've seen quite some specification processes. The specification is basically the baseline that the big players in given field are willing to commit to support for the next decade or so. It's true for security, for messaging, ORM is no difference (although JPA covers quite a lot). My experience as a developer is that in a complex application, sooner or later you will need a non-standard API anyway. And @ColumnDefault is an example when it outweigts the negatives of using a non-standard solution.

2) It's nice how everyone waves @PrePersist or constructor member initialization. But that's NOT the same. How about bulk SQL updates? How about statements that don't set the column? DEFAULT has it's role and that's not substitutable by initializing a Java class member.

ALTER TABLE add constraint

alter table User 
    add constraint userProperties
    foreign key (properties)
    references Properties(ID)

CSS: fixed to bottom and centered

A jQuery solution

$(function(){
    $(window).resize(function(){
        placeFooter();
    });
    placeFooter();
    // hide it before it's positioned
    $('#footer').css('display','inline');
});

function placeFooter() {    
    var windHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var offset = parseInt(windHeight) - parseInt(footerHeight);
    $('#footer').css('top',offset);
}

<div id='footer' style='position: fixed; display: none;'>I am a footer</div>

Sometimes it's easier to implement JS than to hack old CSS.

http://jsfiddle.net/gLhEZ/

How exactly does __attribute__((constructor)) work?

.init/.fini isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init/.fini is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor)). It's old-school but it has some benefits.

.ctors/.dtors mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor)) is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init/.fini instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini).

On system supporting both methods, one possible benefit is that code in .init is run before .ctors and code in .fini after .dtors. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.

A major drawback is that you can't easily have more than one _init and one _fini function per each loadable module and would probably have to fragment code in more .so than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini default functions (provided by crti.o). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here

Notice in the link above that a cascading to the original _init() is not needed as it's still in place. The call in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.

.init/.fini and .ctors/.detors mechanisms are similar, but not quite. Code in .init/.fini runs "as is". I.e. you can have several functions in .init/.fini, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so files.

.ctors/.dtors are differently organized than .init/.fini. .ctors/.dtors sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.

The following snippet adds new function pointers to the .ctors function array, principally the same way as __attribute__((constructor)) does (method can coexist with __attribute__((constructor))).

#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
   printf("Hello\n");
}
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors/.dtors loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).

I'd prefer __attribute__((constructor))/((destructor)) where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.

Some good reference in the book Linkers & loaders.

Extract regression coefficient values

The package broom comes in handy here (it uses the "tidy" format).

tidy(mg) will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).

Example from broom's github repo:

lmfit <- lm(mpg ~ wt, mtcars)
require(broom)    
tidy(lmfit)

      term estimate std.error statistic   p.value
1 (Intercept)   37.285   1.8776    19.858 8.242e-19
2          wt   -5.344   0.5591    -9.559 1.294e-10

is.data.frame(tidy(lmfit))
[1] TRUE

How do you make a HTTP request with C++?

Generally I'd recommend something cross-platform like cURL, POCO, or Qt. However, here is a Windows example!:

#include <atlbase.h>
#include <msxml6.h>
#include <comutil.h> // _bstr_t

HRESULT hr;
CComPtr<IXMLHTTPRequest> request;

hr = request.CoCreateInstance(CLSID_XMLHTTP60);
hr = request->open(
    _bstr_t("GET"),
    _bstr_t("https://www.google.com/images/srpr/logo11w.png"),
    _variant_t(VARIANT_FALSE),
    _variant_t(),
    _variant_t());
hr = request->send(_variant_t());

// get status - 200 if succuss
long status;
hr = request->get_status(&status);

// load image data (if url points to an image)
VARIANT responseVariant;
hr = request->get_responseStream(&responseVariant);
IStream* stream = (IStream*)responseVariant.punkVal;
CImage *image = new CImage();
image->Load(stream);
stream->Release();

What is "git remote add ..." and "git push origin master"?

  1. The .git at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git. The git client and protocol honours this convention by testing for project.git when only project is specified.

  2. git://[email protected]/peter/first_app.git is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git is the ssh url mentioned on that page.

  3. git is flexible. It allows you to track your local branch against almost any branch of any repository. While master (your local default branch) tracking origin/master (the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push is so verbose. It tells git what to do with the local master branch when you do a git pull or a git push.

  4. The default for git push and git pull is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.

git is fairly elegant and comprehensible but there is a learning curve to walk through.

How to do URL decoding in Java?

%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /

String decoded = java.net.URLDecoder.decode(url, "UTF-8");

How to convert hex strings to byte values in Java

Since there was no answer for hex string to single byte conversion, here is mine:

private static byte hexStringToByte(String data) {
    return (byte) ((Character.digit(data.charAt(0), 16) << 4)
                  | Character.digit(data.charAt(1), 16));
}

Sample usage:

hexStringToByte("aa"); // 170
hexStringToByte("ff"); // 255
hexStringToByte("10"); // 16

Or you can also try the Integer.parseInt(String number, int radix) imo, is way better than others.

// first parameter is a number represented in string
// second is the radix or the base number system to be use
Integer.parseInt("de", 16); // 222
Integer.parseInt("ad", 16); // 173
Integer.parseInt("c9", 16); // 201

How to flip background image using CSS?

According to w3schools: http://www.w3schools.com/cssref/css3_pr_transform.asp

The transform property is supported in Internet Explorer 10, Firefox, and Opera. Internet Explorer 9 supports an alternative, the -ms-transform property (2D transforms only). Safari and Chrome support an alternative, the -webkit-transform property (3D and 2D transforms). Opera supports 2D transforms only.

This is a 2D transform, so it should work, with the vendor prefixes, on Chrome, Firefox, Opera, Safari, and IE9+.

Other answers used :before to stop it from flipping the inner content. I used this on my footer (to vertically-mirror the image from my header):

HTML:

<footer>
<p><a href="page">Footer Link</a></p>
<p>&copy; 2014 Company</p>
</footer>

CSS:

footer {
background:url(/img/headerbg.png) repeat-x 0 0;

/* flip background vertically */
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

/* undo the vertical flip for all child elements */
footer * {
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

So you end up flipping the element and then re-flipping all its children. Works with nested elements, too.

What is the difference between HTTP and REST?

No, REST is the way HTTP should be used.

Today we only use a tiny bit of the HTTP protocol's methods – namely GET and POST. The REST way to do it is to use all of the protocol's methods.

For example, REST dictates the usage of DELETE to erase a document (be it a file, state, etc.) behind a URI, whereas, with HTTP, you would misuse a GET or POST query like ...product/?delete_id=22.

What is the difference between response.sendRedirect() and request.getRequestDispatcher().forward(request,response)

1.redirect return the request to the browser from server,then resend the request to the server from browser.

2.forward send the request to another servlet (servlet to servlet).

Path to MSBuild

The Registry locations

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5

give the location for the executable.

But if you need the location where to save the Task extensions, it's on

%ProgramFiles%\MSBuild

How to read text file in JavaScript

This can be done quite easily using javascript XMLHttpRequest() class (AJAX):

function FileHelper()

{
    FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
    {
        var request = new XMLHttpRequest();
        request.open("GET", pathOfFileToReadFrom, false);
        request.send(null);
        var returnValue = request.responseText;

        return returnValue;
    }
}

...

var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );

Detect iPhone/iPad purely by css

Many devices with different screen sizes/ratios/resolutions have come out even in the last five years, including new types of iPhones and iPads. It would be very difficult to customize a website for each device.

Meanwhile, media queries for device-width, device-height, and device-aspect-ratio have been deprecated, so they may not work in future browser versions. (Source: MDN)

TLDR: Design based on browser widths, not devices. Here's a good introduction to this topic.

:before and background-image... should it work?

For some reason, I need float property of a pseudo-element to be set to left or right for the image to appear. height and width of the pseudo-element should be both set but not in percentage. I'm on Firefox 67.

Get counts of all tables in a schema

select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;

This is the fastest way to retrieve the row counts but there are a few important caveats:

  1. NUM_ROWS is only 100% accurate if statistics were gathered in 11g and above with ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE (the default), or in earlier versions with ESTIMATE_PERCENT => 100. See this post for an explanation of how the AUTO_SAMPLE_SIZE algorithm works in 11g.
  2. Results were generated as of LAST_ANALYZED, the current results may be different.

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

give polpetta a try ...

npm install -g polpetta

then you can

polpetta ~/folder

and you are ready to go :-)

how to hide keyboard after typing in EditText in android?

This should work.

InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS); 

Just make sure that this.getCurrentFocus() does not return null, which it would if nothing has focus.

Bind a function to Twitter Bootstrap Modal Close

I was having the same issues as some with

$('#myModal').on('hidden.bs.modal', function () {
// do something… })

You need to place this at the bottom of the page, placing it at the top never fires the event.

Altering a column: null to not null

I had the same problem, but the field used to default to null, and now I want to default it to 0. That required adding one more line after mdb's solution:

ALTER TABLE [Table] ADD CONSTRAINT [Constraint] DEFAULT 0 FOR [Column];

How to get the real path of Java application at runtime?

It isn't clear what you're asking for. I don't know what 'with respect to the web application we are using' means if getServletContext().getRealPath() isn't the answer, but:

  • The current user's current working directory is given by System.getProperty("user.dir")
  • The current user's home directory is given by System.getProperty("user.home")
  • The location of the JAR file from which the current class was loaded is given by this.getClass().getProtectionDomain().getCodeSource().getLocation().

Comparing object properties in c#

This method will get properties of the class and compare the values for each property. If any of the values are different, it will return false, else it will return true.

public static bool Compare<T>(T Object1, T object2)
{
    //Get the type of the object
    Type type = typeof(T);

    //return false if any of the object is false
    if (Object1 == null || object2 == null)
        return false;

    //Loop through each properties inside class and get values for the property from both the objects and compare
    foreach (System.Reflection.PropertyInfo property in type.GetProperties())
    {
        if (property.Name != "ExtensionData")
        {
            string Object1Value = string.Empty;
            string Object2Value = string.Empty;
            if (type.GetProperty(property.Name).GetValue(Object1, null) != null)
                Object1Value = type.GetProperty(property.Name).GetValue(Object1, null).ToString();
            if (type.GetProperty(property.Name).GetValue(object2, null) != null)
                Object2Value = type.GetProperty(property.Name).GetValue(object2, null).ToString();
            if (Object1Value.Trim() != Object2Value.Trim())
            {
                return false;
            }
        }
    }
    return true;
}

Usage:

bool isEqual = Compare<Employee>(Object1, Object2)

Eclipse: Frustration with Java 1.7 (unbound library)

Updated eclipse.ini file with key-value property

-Dosgi.requiredJavaVersion=1.5 

to

-Dosgi.requiredJavaVersion=1.8

because, that is my JAVA version.

Also, selected JRE 1.8 as my project library

Getting full URL of action in ASP.NET MVC

I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.

Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).

I may have cheated a little, but it is exactly what I needed to force a https url:

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.

Remove Project from Android Studio

Select your project in the projects window > File > Project Structure > (in the Modules section) select your project and click the minus button.

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

How correctly produce JSON by RESTful web service?

You can annotate your bean with jaxb annotations.

  @XmlRootElement
  public class MyJaxbBean {
    public String name;
    public int age;

    public MyJaxbBean() {} // JAXB needs this

    public MyJaxbBean(String name, int age) {
      this.name = name;
      this.age = age;
    }
  }

and then your method would look like this:

   @GET @Produces("application/json")
   public MyJaxbBean getMyBean() {
      return new MyJaxbBean("Agamemnon", 32);
   }

There is a chapter in the latest documentation that deals with this:

https://jersey.java.net/documentation/latest/user-guide.html#json

What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

Turn off constraints temporarily (MS SQL)

Disabling and Enabling All Foreign Keys

CREATE PROCEDURE pr_Disable_Triggers_v2
    @disable BIT = 1
AS
    DECLARE @sql VARCHAR(500)
        ,   @tableName VARCHAR(128)
        ,   @tableSchema VARCHAR(128)

    -- List of all tables
    DECLARE triggerCursor CURSOR FOR
        SELECT  t.TABLE_NAME AS TableName
            ,   t.TABLE_SCHEMA AS TableSchema
        FROM    INFORMATION_SCHEMA.TABLES t
        ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA

    OPEN    triggerCursor
    FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
    WHILE ( @@FETCH_STATUS = 0 )
    BEGIN

        SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
        IF @disable = 1
            SET @sql = @sql + ' DISABLE TRIGGER ALL'
        ELSE
            SET @sql = @sql + ' ENABLE TRIGGER ALL'

        PRINT 'Executing Statement - ' + @sql
        EXECUTE ( @sql )

        FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema

    END

    CLOSE triggerCursor
    DEALLOCATE triggerCursor

First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:

0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missing

Inside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.

see Disabling Constraints and Triggers from MSDN Magazine

Convert array values from string to int?

You can achieve this by following code,

$integerIDs = array_map('intval', explode(',', $string));

The Network Adapter could not establish the connection when connecting with Oracle DB

If it is on a Linux box, I would suggest you add the database IP name and IP resolution to the /etc/hosts.

I have the same error and when we do the above, it works fine.

Call method in directive controller from other controller

You could also expose the directive's controller to the parent scope, like ngForm with name attribute does: http://docs.angularjs.org/api/ng.directive:ngForm

Here you could find a very basic example how it could be achieved http://plnkr.co/edit/Ps8OXrfpnePFvvdFgYJf?p=preview

In this example I have myDirective with dedicated controller with $clear method (sort of very simple public API for the directive). I can publish this controller to the parent scope and use call this method outside the directive.

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

How to plot two columns of a pandas data frame using points?

You can specify the style of the plotted line when calling df.plot:

df.plot(x='col_name_1', y='col_name_2', style='o')

The style argument can also be a dict or list, e.g.:

import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot.

Output

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

colleagues.

I have faced with this trouble during a development of automation tests for our REST API. JDK 7_80 was installed at my machine only. Before I installed JDK 8, everything worked just fine and I had a possibility to obtain OAuth 2.0 tokens with a JMeter. After I installed JDK 8, the nightmare with Certificates does not conform to algorithm constraints began.

Both JMeter and Serenity did not have a possibility to obtain a token. JMeter uses the JDK library to make the request. The library just raises an exception when the library call is made to connect to endpoints that use it, ignoring the request.

The next thing was to comment all the lines dedicated to disabledAlgorithms in ALL java.security files.

C:\Java\jre7\lib\security\java.security
C:\Java\jre8\lib\security\java.security
C:\Java\jdk8\jre\lib\security\java.security
C:\Java\jdk7\jre\lib\security\java.security

Then it started to work at last. I know, that's a brute force approach, but it was the most simple way to fix it.

# jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
# jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024

How can I preview a merge in git?

I do not want to use the git merge command as the precursor to reviewing conflicting files. I don't want to do a merge, I want to identify potential problems before I merge - problems that auto-merge might hide from me. The solution I have been searching for is how to have git spit out a list of files that have been changed in both branches that will be merged together in the future, relative to some common ancestor. Once I have that list, I can use other file comparison tools to scout things out further. I have searched multiple times, and I still haven't found what I want in a native git command.

Here is my workaround, in case it helps anyone else out there:

In this scenario I have a branch called QA that has many changes in it since the last production release. Our last production release is tagged with "15.20.1". I have another development branch called new_stuff that I want to merge into the QA branch. Both QA and new_stuff point to commits that "follow" (as reported by gitk) the 15.20.1 tag.

git checkout QA
git pull
git diff 15.20.1 --name-only > QA_files
git checkout new_stuff
git pull
git diff 15.20.1 --name-only > new_stuff_files
comm -12 QA_files new_stuff_files

Here are some discussions that hit on why I'm interested in targeting these specific files:

How can I trust Git merge?

https://softwareengineering.stackexchange.com/questions/199780/how-far-do-you-trust-automerge

Django: multiple models in one template using forms

According to Django documentation, inline formsets are for this purpose: "Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key".

See https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.

(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)

In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.

For example, lets say you have the following query:

SELECT emp_id FROM employees WHERE months_of_service = 6;

(The months_of_service column has a NOT NULL constraint on it and an ordinary index on it.)

There are two basic plans the optimiser might choose here:

  • Plan 1: Read all the rows from the "employees" table, for each, check if the predicate is true (months_of_service=6).
  • Plan 2: Read the index where months_of_service=6 (this results in a set of ROWIDs), then access the table based on the ROWIDs returned.

Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.

The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.

The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.

As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.

If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".

The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.

How can I easily switch between PHP versions on Mac OSX?

If you install PHP with homebrew, you can switch between versions very easily. Say you want php56 to point to Version 5.6.17, you just do:

brew switch php56 5.6.17

How to convert a String into an array of Strings containing one character each

String[] result = input.split("(?!^)");

What this does is split the input String on all empty Strings that are not preceded by the beginning of the String.

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

How can I create a border around an Android LinearLayout?

Don't want to create a drawable resource?

  <FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/black"
    android:minHeight="128dp">

    <FrameLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="1dp"
      android:background="@android:color/white">

      <TextView ... />
    </FrameLayout>
  </FrameLayout>

How to use jQuery in AngularJS

This should be working. Please have a look at this fiddle.

$(function() {
   $( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code

Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.

python pandas dataframe to dictionary

Another (slightly shorter) solution for not losing duplicate entries:

>>> ptest = pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
>>> ptest
  id  value
0  a      1
1  a      2
2  b      3

>>> pdict = dict()
>>> for i in ptest['id'].unique().tolist():
...     ptest_slice = ptest[ptest['id'] == i]
...     pdict[i] = ptest_slice['value'].tolist()
...

>>> pdict
{'b': [3], 'a': [1, 2]}

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

How to get source code of a Windows executable?

You can't get the C++ source from an exe, and you can only get some version of the C# source via reflection.