Programs & Examples On #Postback

A postback is a technique in web development in which a page sends an HTTP POST back to the same form on the server.

A potentially dangerous Request.Form value was detected from the client

You can automatically HTML encode field in custom Model Binder. My solution some different, I put error in ModelState and display error message near the field. It`s easy to modify this code for automatically encode

 public class AppModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            try
            {
                return base.CreateModel(controllerContext, bindingContext, modelType);
            }
            catch (HttpRequestValidationException e)
            {
                HandleHttpRequestValidationException(bindingContext, e);
                return null; // Encode here
            }
        }
        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            try
            {
                return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
            }
            catch (HttpRequestValidationException e)
            {
                HandleHttpRequestValidationException(bindingContext, e);
                return null; // Encode here
            }
        }

        protected void HandleHttpRequestValidationException(ModelBindingContext bindingContext, HttpRequestValidationException ex)
        {
            var valueProviderCollection = bindingContext.ValueProvider as ValueProviderCollection;
            if (valueProviderCollection != null)
            {
                ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            }

            string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0} contains invalid symbols: <, &",
                     bindingContext.ModelMetadata.DisplayName);

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);
        }
    }

In Application_Start:

ModelBinders.Binders.DefaultBinder = new AppModelBinder();

Note that it works only for form fields. Dangerous value not passed to controller model, but stored in ModelState and can be redisplayed on form with error message.

Dangerous chars in URL may be handled this way:

private void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    HttpContext httpContext = HttpContext.Current;

    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Error");
        var httpCode = httpException.GetHttpCode();
        switch (httpCode)
        {
            case (int)HttpStatusCode.BadRequest /* 400 */:
                if (httpException.Message.Contains("Request.Path"))
                {
                    httpContext.Response.Clear();
                    RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
                    requestContext.RouteData.Values["action"] ="InvalidUrl";
                    requestContext.RouteData.Values["controller"] ="Error";
                    IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
                    IController controller = factory.CreateController(requestContext, "Error");
                    controller.Execute(requestContext);
                    httpContext.Server.ClearError();
                    Response.StatusCode = (int)HttpStatusCode.BadRequest /* 400 */;
                }
                break;
        }
    }
}

ErrorController:

public class ErrorController : Controller
 {
   public ActionResult InvalidUrl()
   {
      return View();
   }
}   

Forcing a postback

You can try redirecting to same page.

Response.Redirect(Request.RawUrl);

How to use __doPostBack()

Old question, but I'd like to add something: when calling doPostBack() you can use the server handler method for the action.

For an example:

__doPostBack('<%= btn.UniqueID%>', 'my args');

Will fire, on server:

protected void btn_Click(object sender, EventArgs e)

I didn't find a better way to get the argument, so I'm still using Request["__EVENTARGUMENT"].

OnclientClick and OnClick is not working at the same time?

There are two issues here:

Disabling the button on the client side prevents the postback

To overcome this, disable the button after the JavaScript onclick event. An easy way to do this is to use setTimeout as suggested by this answer.

Also, the OnClientClick code runs even if ASP.NET validation fails, so it's probably a good idea to add a check for Page_IsValid. This ensures that the button will not be disabled if validation fails.

OnClientClick="(function(button) { setTimeout(function () { if (Page_IsValid) button.disabled = true; }, 0); })(this);"

It's neater to put all of this JavaScript code in its own function as the question shows:

OnClientClick="disable(this);"

function disable(button) {
    setTimeout(function () {
        if (Page_IsValid)
            button.disabled = true;
    }, 0);
}

Disabling the button on the client side doesn't disable it on the server side

To overcome this, disable the button on the server side. For example, in the OnClick event handler:

OnClick="Button1_Click"

protected void Button1_Click(object sender, EventArgs e)
{
    ((Button)sender).Enabled = false;
}

Lastly, keep in mind that preventing duplicate button presses doesn't prevent two different users from submitting the same data at the same time. Make sure to account for that on the server side.

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

A simple solution for this problem is to use the IsPostBack check on your page load. That will solve this problem.

jQuery UI Dialog with ASP.NET button postback

$('#divname').parent().appendTo($("form:first"));

Using this code solved my problem and it worked in every browser, Internet Explorer 7, Firefox 3, and Google Chrome. I start to love jQuery... It's a cool framework.

I have tested with partial render too, exactly what I was looking for. Great!

<script type="text/javascript">
    function openModalDiv(divname) {
        $('#' + divname).dialog({ autoOpen: false, bgiframe: true, modal: true });
        $('#' + divname).dialog('open');
        $('#' + divname).parent().appendTo($("form:first"));
    }

    function closeModalDiv(divname) {
        $('#' + divname).dialog('close');
    }
</script>
...
...
<input id="Button1" type="button" value="Open 1" onclick="javascript:openModalDiv('Div1');" />
...
...
<div id="Div1" title="Basic dialog" >
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
       <ContentTemplate>
          postback test<br />
          <asp:Button ID="but_OK" runat="server" Text="Send request" /><br />
          <asp:TextBox ID="tb_send" runat="server"></asp:TextBox><br />
          <asp:Label ID="lbl_result" runat="server" Text="prova" BackColor="#ff0000></asp:Label>
        </ContentTemplate>
    <asp:UpdatePanel>
    <input id="Button2" type="button" value="cancel" onclick="javascript:closeModalDiv('Div1');" />
</div>

ASP.NET postback with JavaScript

You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

How should I use Outlook to send code snippets?

When I paste code into Outlook or have sentences containing code or technical syntax I get annoyed by all of the red squiggles that identify spelling errors. If you want Outlook to clear all of the red spellcheck squiggles you can add a button to the Quick Access Toolbar that calls a VBA macro and removes all squiggles from the current document.

I prefer to run this macro separate from my style choice because I often use it on a selection of text that has mixed content.

For syntax highlighting I use the Notepad++ technique already listed by @srujanreddy, though I discovered that the right-click context menu option a bit handier than navigating the Plugins menu.

Image showing you can right-click on selected text and choose to copy text with syntax highlighting

If you get annoyed by spell check while you are preparing your email you can add a button to your quick access toolbar that will remove the red squiggles from the message body.
See this article: https://stackoverflow.com/a/49865743/1898524

Remove Spell Check Squiggles

How to pass an object from one activity to another on Android

Create your own class Customer as following:

import import java.io.Serializable;
public class Customer implements Serializable
{
    private String name;
    private String city;

    public Customer()
    {

    }
    public Customer(String name, String city)
    {
        this.name= name;
        this.city=city;
    }
    public String getName() 
    {
        return name;
    }
    public void setName(String name) 
    {
        this.name = name;
    }
    public String getCity() 
    {
        return city;
    }
    public void setCity(String city) 
    {
        this.city= city;
    }

}

In your onCreate() method

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

    Customer cust=new Customer();
    cust.setName("abc");
    cust.setCity("xyz");

    Intent intent=new Intent(abc.this,xyz.class);
    intent.putExtra("bundle",cust);
    startActivity(intent); 
}

In xyz activity class you need to use the following code:

Intent intent=getIntent();
Customer cust=(Customer)intent.getSerializableExtra("bundle");
textViewName.setText(cust.getName());
textViewCity.setText(cust.getCity());

Permission denied at hdfs

I had similar situation and here is my approach which is somewhat different:

 HADOOP_USER_NAME=hdfs hdfs dfs -put /root/MyHadoop/file1.txt /

What you actually do is you read local file in accordance to your local permissions but when placing file on HDFS you are authenticated like user hdfs. You can do this with other ID (beware of real auth schemes configuration but this is usually not a case).

Advantages:

  1. Permissions are kept on HDFS.
  2. You don't need sudo.
  3. You don't need actually appropriate local user 'hdfs' at all.
  4. You don't need to copy anything or change permissions because of previous points.

How to copy directory recursively in python and overwrite all?

Here's a simple solution to recursively overwrite a destination with a source, creating any necessary directories as it goes. This does not handle symlinks, but it would be a simple extension (see answer by @Michael above).

def recursive_overwrite(src, dest, ignore=None):
    if os.path.isdir(src):
        if not os.path.isdir(dest):
            os.makedirs(dest)
        files = os.listdir(src)
        if ignore is not None:
            ignored = ignore(src, files)
        else:
            ignored = set()
        for f in files:
            if f not in ignored:
                recursive_overwrite(os.path.join(src, f), 
                                    os.path.join(dest, f), 
                                    ignore)
    else:
        shutil.copyfile(src, dest)

Disable Buttons in jQuery Mobile

For disabling a button add css class disabled to it . write

$("button").addClass('disabled')

How to run python script in webpage

using flask library in Python you can achieve that. remember to store your HTML page to a folder named "templates" inside where you are running your python script.

so your folder would look like

  1. templates (folder which would contain your HTML file)
  2. your python script

this is a small example of your python script. This simply checks for plagiarism.

from flask import Flask
from flask import request
from flask import render_template
import stringComparison

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template("my-form.html") # this should be the name of your html file

@app.route('/', methods=['POST'])
def my_form_post():
    text1 = request.form['text1']
    text2 = request.form['text2']
    plagiarismPercent = stringComparison.extremelySimplePlagiarismChecker(text1,text2)
    if plagiarismPercent > 50 :
        return "<h1>Plagiarism Detected !</h1>"
    else :
        return "<h1>No Plagiarism Detected !</h1>"

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

This a small template of HTML file that is used

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>Enter the texts to be compared</h1>
    <form action="." method="POST">
        <input type="text" name="text1">
        <input type="text" name="text2">
        <input type="submit" name="my-form" value="Check !">
    </form>
</body>
</html>

This is a small little way through which you can achieve a simple task of comparing two string and which can be easily changed to suit your requirements

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Show all current locks from get_lock

Reference taken from this post:

You can also use this script to find lock in MySQL.

SELECT 
    pl.id
    ,pl.user
    ,pl.state
    ,it.trx_id 
    ,it.trx_mysql_thread_id 
    ,it.trx_query AS query
    ,it.trx_id AS blocking_trx_id
    ,it.trx_mysql_thread_id AS blocking_thread
    ,it.trx_query AS blocking_query
FROM information_schema.processlist AS pl 
INNER JOIN information_schema.innodb_trx AS it
    ON pl.id = it.trx_mysql_thread_id
INNER JOIN information_schema.innodb_lock_waits AS ilw
    ON it.trx_id = ilw.requesting_trx_id 
        AND it.trx_id = ilw.blocking_trx_id

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I had the same problem when I was writing Java application on Netbeans.Here is the solution:

  1. Find your project in projects selection tab

  2. Right click "Libraries"

  3. Click "Add JAR/Folder..."

  4. Choose "derbyclient.jar"

  5. Click "Open", then you will see "derbyclient.jar" under your "Libraries"

  6. Make sure your URL, user name, pass word is correct, and run your code:)

Android studio doesn't list my phone under "Choose Device"

That worked for my TP-Link Neffos C5:

The first step in configuring a Windows based development system to connect to an Android device using ADB is to install the appropriate USB drivers on the system. In the case of some devices, the Google USB Driver must be installed (a full listing of devices supported by the Google USB driver can be found online at http://developer.android.com/sdk/win-usb.html).

To install this driver, perform the following steps:

  1. Launch Android Studio and open the Android SDK Manager, either by selected Configure -> SDK Manager from the Welcome screen, or using the Tools -> Android -> SDK Manager menu option when working on an existing project.
  2. Scroll down to the Extras section and check the status of the Google USB Driver package to make sure that it is listed as Installed.
  3. If the driver is not installed, select it and click on the Install packages button to initiate the installation.
  4. Once installation is complete, close the Android SDK Manager.

Complete instructions on http://www.techotopia.com/index.php/Testing_Android_Studio_Apps_on_a_Physical_Android_Device (check "Windows ADB Configuration" section).

I basically updated a lot of stuff and then it worked in both Android Studio and Eclipse!

Button Center CSS

when all else fails I just

<center> content </center>

I know its not "up to standards" any more, but if it works it works

Regular expression for only characters a-z, A-Z

This /[^a-z]/g solves the problem.

_x000D_
_x000D_
function pangram(str) {
    let regExp = /[^a-z]/g;
    let letters = str.toLowerCase().replace(regExp, '');
    document.getElementById('letters').innerHTML = letters;
}
pangram('GHV 2@# %hfr efg uor7 489(*&^% knt lhtkjj ngnm!@#$%^&*()_');
_x000D_
<h4 id="letters"></h4>
_x000D_
_x000D_
_x000D_

Get list of filenames in folder with Javascript

No, Javascript doesn't have access to the filesystem. Server side Javascript is a whole different story but I guess you don't mean that.

How to view the assembly behind the code using Visual C++?

The earlier version of this answer (a "hack" for rextester.com) is mostly redundant now that http://gcc.godbolt.org/ provides CL 19 RC for ARM, x86, and x86-64 (targeting the Windows calling convention, unlike gcc, clang, and icc on that site).

The Godbolt compiler explorer is designed for nicely formatting compiler asm output, removing the "noise" of directives, so I'd highly recommend using it to look at asm for simple functions that take args and return a value (so they won't be optimized away).

For a while, CL was available on http://gcc.beta.godbolt.org/ but not the main site, but now it's on both.


To get MSVC asm output from the http://rextester.com/l/cpp_online_compiler_visual online compiler: Add /FAs to the command line options. Have your program find its own path and work out the path to the .asm and dump it. Or run a disassembler on the .exe.

e.g. http://rextester.com/OKI40941

#include <string>
#include <boost/filesystem.hpp>
#include <Windows.h>

using namespace std;

static string my_exe(void){
    char buf[MAX_PATH];
    DWORD tmp = GetModuleFileNameA( NULL, // self
                                  buf, MAX_PATH);
    return buf;
}

int main() {
    string dircmd = "dir ";
    boost::filesystem::path p( my_exe() );
    //boost::filesystem::path dir = p.parent_path();

    // transform c:\foo\bar\1234\a.exe 
    // into      c:\foo\bar\1234\1234.asm
    p.remove_filename();
    system ( (dircmd + p.string()).c_str() );

    auto subdir = p.end();      // pointing at one-past the end
    subdir--;                   // pointing at the last directory name
    p /= *subdir;               // append the last dir name as a filename
    p.replace_extension(".asm");
    system ( (string("type ") + p.string()).c_str() );
//    std::cout << "Hello, world!\n";
}

... code of functions you want to see the asm for goes here ...

type is the DOS version of cat. I didn't want to include more code that would make it harder to find the functions I wanted to see the asm for. (Although using std::string and boost run counter to those goals! Some C-style string manipulation that makes more assumptions about the string it's processing (and ignores max-length safety / allocation by using a big buffer) on the result of GetModuleFileNameA would be much less total machine code.)

IDK why, but cout << p.string() << endl only shows the basename (i.e. the filename, without the directories), even though printing its length shows it's not just the bare name. (Chromium48 on Ubuntu 15.10). There's probably some backslash-escape processing at some point in cout, or between the program's stdout and the web browser.

Event listener for when element becomes visible?

Javascript events deal with User Interaction, if your code is organised enough you should be able to call the initialising function in the same place where the visibility changes (i.e. you shouldn't change myElement.style.display on many places, instead, call a function/method that does this and anything else you might want).

How to create a sticky left sidebar menu using bootstrap 3?

Bootstrap 3

Here is a working left sidebar example:

http://bootply.com/90936 (similar to the Bootstrap docs)

The trick is using the affix component along with some CSS to position it:

  #sidebar.affix-top {
    position: static;
    margin-top:30px;
    width:228px;
  }

  #sidebar.affix {
    position: fixed;
    top:70px;
    width:228px;
  }

EDIT- Another example with footer and affix-bottom


Bootstrap 4

The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top class is explained in this answer.

Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?

JavaScript checking for null vs. undefined and difference between == and ===

How do I check a variable if it's null or undefined...

Is the variable null:

if (a === null)
// or
if (a == null) // but see note below

...but note the latter will also be true if a is undefined.

Is it undefined:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

...but again, note that the last one is vague; it will also be true if a is null.

Now, despite the above, the usual way to check for those is to use the fact that they're falsey:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

This is defined by ToBoolean in the spec.

...and what is the difference between the null and undefined?

They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)

null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference — either a valid one (if it found the DOM element), or null (if it didn't).

Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.

What is the difference between "==" and "==="

The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.

Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).

More in the spec:

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

How to select an item from a dropdown list using Selenium WebDriver with java?

To find a particular dropdown box element:

Select gender = new Select(driver.findElement(By.id("gender")));

To get the list of all the elements contained in the dropdown box:

for(int j=1;j<3;j++)
    System.out.println(gender.getOptions().get(j).getText());

To select it through visible text displayed when you click on it:

gender.selectByVisibleText("Male");

To select it by index (starting at 0):

gender.selectByIndex(1);

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

Turning multiple lines into one comma separated line

based on your input example, this awk line works. (without trailing comma)

awk -vRS="" -vOFS=',' '$1=$1' file

test:

kent$  echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1' 
foo,bar,qux,zuu,sdf,sdfasdf

Android Material: Status bar color won't change

As others have also mentioned, this can be readily solved by adding the following to the onCreate() of the Activity:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.primary_dark));
    }

However, the important point I want to add here is that in some cases, even the above does not change the status bar color. For example, when using MikePenz library for Navigation Drawer, it implicityly overrides the status bar color, so that you need to manually add the following for it to work:

.withStatusBarColorRes(R.color.status_bar_color)

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

On your remote machine, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:

  • Install Oracle Client , and add bin location to Path environment varaible of windows OR
  • Copy oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version), oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

On your local machine most probably path to Oracle Client is already added in Path environment variable to there required dll are available to application but not on remote machine

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

FromBody string parameter is giving null

Referencing Parameter Binding in ASP.NET Web API

Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

[Route("Edit/Test")]
[HttpPost]
public IHttpActionResult Test(int id, [FromBody] string jsonString) { ... }

In this example, Web API will use a media-type formatter to read the value of jsonString from the request body. Here is an example client request.

POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Type: application/json
Content-Length: 6

"test"

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

In the above example no model is needed if the data is provided in the correct format in the body.

For URL encoded a request would look like this

POST http://localhost:8000/Edit/Test?id=111 HTTP/1.1
User-Agent: Fiddler
Host: localhost:8000
Content-Type: application/x-www-form-urlencoded
Content-Length: 5

=test

Reliable method to get machine's MAC address in C#

You could go for the NIC ID:

 foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
     if (nic.OperationalStatus == OperationalStatus.Up){
         if (nic.Id == "yay!")
     }
 }

It's not the MAC address, but it is a unique identifier, if that's what you're looking for.

Are there .NET implementation of TLS 1.2?

You can enable TLS 1.2 in IIS by following these instructions. I presume this would be sufficient if you have an ASP.NET-based application that runs on top of IIS, although it looks like it does not really meet your needs.

How do you add Boost libraries in CMakeLists.txt?

Adapting @LainIwakura's answer for modern CMake syntax with imported targets, this would be:

set(Boost_USE_STATIC_LIBS OFF) 
set(Boost_USE_MULTITHREADED ON)  
set(Boost_USE_STATIC_RUNTIME OFF) 
find_package(Boost 1.45.0 COMPONENTS filesystem regex) 

if(Boost_FOUND)
    add_executable(progname file1.cxx file2.cxx) 
    target_link_libraries(progname Boost::filesystem Boost::regex)
endif()

Note that it is not necessary anymore to specify the include directories manually, since it is already taken care of through the imported targets Boost::filesystem and Boost::regex.
regex and filesystem can be replaced by any boost libraries you need.

Select 2 columns in one and combine them

Your syntax should work, maybe add a space between the colums like

SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable

How to find my realm file?

Updated answer to the newest Realm:

For Android:

checkout stetho and https://github.com/uPhyca/stetho-realm Video tutorial here: https://www.youtube.com/watch?v=9pFJz5VexRw

For IOS (Swift)

Either:

debugPrint("Path to realm file: " + realm.configuration.fileURL!.absoluteString)

or

Step 1: Have a constant called dev somewhere. Let's say Constant file

public class Constants {

    public static var dev: Bool = true

}

Step 2: Create another class called RealmFunctions.swift

import RealmSwift


func realmAndPath() -> Realm {
    if Constants.dev {
        // location of my desktop
        let testRealmURL = NSURL(fileURLWithPath: "/Users/#####/Desktop/TestRealm.realm")
        return try! Realm(fileURL: testRealmURL)
    } else {
        return try! Realm()
    }
}

Step 3: finally in your view controller:

let realm = realmAndPath()

thanks to Stewart Lynch for the original answer

Finding the second highest number in array

Use following function
`

public static int secHigh(int arr[]){
            int firstHigh = 0,secHigh = 0;
            for(int x: arr){
                if(x > firstHigh){
                    secHigh = firstHigh;
                    firstHigh = x;
                }else if(x > secHigh){
                    secHigh = x;
                }
            }
            return secHigh;
        }

Function Call

int secondHigh = secHigh(arr);

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Just finally fixed this for my single solution that was having this. Two of the projects in the solution were set as sites in IIS. I went in and enabled ASP.Net Impersonation under Authentication for both projects...and VIOLA! FINALLY, no more of this annoying error!

App crashing when trying to use RecyclerView on android 5.0

My problem was in my XML lyout I have an android:animateLayoutChanges set to true and I've called notifyDataSetChanged() on the RecyclerView's adapter in the Java code.

So, I've just removed android:animateLayoutChanges from my layout and that resloved my problem.

Recursive mkdir() system call on Unix

Here's my shot at a more general solution:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>

typedef int (*dirhandler_t)( const char*, void* );
/// calls itfunc for each directory in path (except for . and ..)
int iterate_path( const char* path, dirhandler_t itfunc, void* udata )
{
    int rv = 0;
    char tmp[ 256 ];
    char *p = tmp;
    char *lp = tmp;
    size_t len;
    size_t sublen;
    int ignore_entry;

    strncpy( tmp, path, 255 );

    tmp[ 255 ] = '\0';
    len = strlen( tmp );

    if( 0 == len ||
        (1 == len && '/' == tmp[ 0 ]) )
        return 0;

    if( tmp[ len - 1 ] == '/' )
        tmp[ len - 1 ] = 0;

    while( (p = strchr( p, '/' )) != NULL )
    {
        ignore_entry = 0;
        *p = '\0';
        lp = strrchr( tmp, '/' );

        if( NULL == lp ) { lp = tmp; }
        else { lp++; }

        sublen = strlen( lp );

        if( 0 == sublen )   /* ignore things like '//' */
            ignore_entry = 1;
        else if( 1 == sublen &&  /* ignore things like '/./' */
                 '.' == lp[ 0 ] )
            ignore_entry = 1;
        else if( 2 == sublen &&    /* also ignore things like '/../' */
                 '.' == lp[ 0 ] &&
                 '.' == lp[ 1 ] )
            ignore_entry = 1;

        if( ! ignore_entry )
        {
            if( (rv = itfunc( tmp, udata )) != 0 )
                return rv;
        }

        *p = '/';
        p++;
        lp = p;
    }

    if( strcmp( lp, "." ) && strcmp( lp, ".." ) )
        return itfunc( tmp, udata );

    return 0;
}

mode_t get_file_mode( const char* path )
{
    struct stat statbuf;
    memset( &statbuf, 0, sizeof( statbuf ) );

    if( NULL == path ) { return 0; }

    if( 0 != stat( path, &statbuf ) )
    {
        fprintf( stderr, "failed to stat '%s': %s\n",
                 path, strerror( errno ) );
        return 0;
    }

    return statbuf.st_mode;
}

static int mymkdir( const char* path, void* udata )
{
    (void)udata;
    int rv = mkdir( path, S_IRWXU );
    int errnum = errno;

    if( 0 != rv )
    {
        if( EEXIST == errno &&
            S_ISDIR( get_file_mode( path ) ) )  /* it's all good, the directory already exists */
            return 0;

        fprintf( stderr, "mkdir( %s ) failed: %s\n",
                 path, strerror( errnum ) );
    }
//     else
//     {
//         fprintf( stderr, "created directory: %s\n", path );
//     }

    return rv;
}

int mkdir_with_leading( const char* path )
{
    return iterate_path( path, mymkdir, NULL );
}

int main( int argc, const char** argv )
{
    size_t i;
    int rv;

    if( argc < 2 )
    {
        fprintf( stderr, "usage: %s <path> [<path>...]\n",
                 argv[ 0 ] );
        exit( 1 );
    }

    for( i = 1; i < argc; i++ )
    {
        rv = mkdir_with_leading( argv[ i ] );
        if( 0 != rv )
            return rv;
    }

    return 0;
}

How to make a div 100% height of the browser window

You can use vh in this case which is relative to 1% of the height of the viewport...

That means if you want to cover off the height, just simply use 100vh.

Look at the image below I draw for you here:

How to make a div 100% height of the browser window?

Try the snippet I created for you as below:

_x000D_
_x000D_
.left {_x000D_
  height: 100vh;_x000D_
  width: 50%;_x000D_
  background-color: grey;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.right {_x000D_
  height: 100vh;_x000D_
  width: 50%;_x000D_
  background-color: red;_x000D_
  float: right;_x000D_
}
_x000D_
<div class="left"></div>_x000D_
<div class="right"></div>
_x000D_
_x000D_
_x000D_

Psql could not connect to server: No such file or directory, 5432 error?

The same thing happened to me as I had changed something in the /etc/hosts file. After changing it back to 127.0.0.1 localhost it worked for me.

Custom thread pool in Java 8 parallel stream

I tried the custom ForkJoinPool as follows to adjust the pool size:

private static Set<String> ThreadNameSet = new HashSet<>();
private static Callable<Long> getSum() {
    List<Long> aList = LongStream.rangeClosed(0, 10_000_000).boxed().collect(Collectors.toList());
    return () -> aList.parallelStream()
            .peek((i) -> {
                String threadName = Thread.currentThread().getName();
                ThreadNameSet.add(threadName);
            })
            .reduce(0L, Long::sum);
}

private static void testForkJoinPool() {
    final int parallelism = 10;

    ForkJoinPool forkJoinPool = null;
    Long result = 0L;
    try {
        forkJoinPool = new ForkJoinPool(parallelism);
        result = forkJoinPool.submit(getSum()).get(); //this makes it an overall blocking call

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    } finally {
        if (forkJoinPool != null) {
            forkJoinPool.shutdown(); //always remember to shutdown the pool
        }
    }
    out.println(result);
    out.println(ThreadNameSet);
}

Here is the output saying the pool is using more threads than the default 4.

50000005000000
[ForkJoinPool-1-worker-8, ForkJoinPool-1-worker-9, ForkJoinPool-1-worker-6, ForkJoinPool-1-worker-11, ForkJoinPool-1-worker-10, ForkJoinPool-1-worker-1, ForkJoinPool-1-worker-15, ForkJoinPool-1-worker-13, ForkJoinPool-1-worker-4, ForkJoinPool-1-worker-2]

But actually there is a weirdo, when I tried to achieve the same result using ThreadPoolExecutor as follows:

BlockingDeque blockingDeque = new LinkedBlockingDeque(1000);
ThreadPoolExecutor fixedSizePool = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS, blockingDeque, new MyThreadFactory("my-thread"));

but I failed.

It will only start the parallelStream in a new thread and then everything else is just the same, which again proves that the parallelStream will use the ForkJoinPool to start its child threads.

How to count no of lines in text file and store the value into a variable using batch script?

One nice surprise is for one who has git bash on his windows: just plain old linux wc -l <filename> will works for you there

How to set Java SDK path in AndroidStudio?

Generally speaking, it is set in the "Project Structure" dialog.

Go to File > Project Structure > SDK Location. The third field is "JDK Location" where you can set it. This will set it for the current project.

enter image description here

To set the default for new projects, go to File > Other Settings > Default Project Structure > SDK Location and set the "JDK Location".

Older Versions

Go to File > Project Structure > [Platform Settings] > SDKs. You'll need to either update you current SDK configuration to use the new directory, or define a new one and then change your project's settings to use the new one. This will set it for the current project.

To set the default for new projects, go to File > Other Settings > Structure for New Projects > [Platform Settings] > SDKs and set the SDK to use when creating a new project.

How to run a script file remotely using SSH

I was able to invoke a shell script using this command:

ssh ${serverhost} "./sh/checkScript.ksh"

Of course, checkScript.ksh must exist in the $HOME/sh directory.

What is The Rule of Three?

When do I need to declare them myself?

The Rule of Three states that if you declare any of a

  1. copy constructor
  2. copy assignment operator
  3. destructor

then you should declare all three. It grew out of the observation that the need to take over the meaning of a copy operation almost always stemmed from the class performing some kind of resource management, and that almost always implied that

  • whatever resource management was being done in one copy operation probably needed to be done in the other copy operation and

  • the class destructor would also be participating in management of the resource (usually releasing it). The classic resource to be managed was memory, and this is why all Standard Library classes that manage memory (e.g., the STL containers that perform dynamic memory management) all declare “the big three”: both copy operations and a destructor.

A consequence of the Rule of Three is that the presence of a user-declared destructor indicates that simple member wise copy is unlikely to be appropriate for the copying operations in the class. That, in turn, suggests that if a class declares a destructor, the copy operations probably shouldn’t be automatically generated, because they wouldn’t do the right thing. At the time C++98 was adopted, the significance of this line of reasoning was not fully appreciated, so in C++98, the existence of a user declared destructor had no impact on compilers’ willingness to generate copy operations. That continues to be the case in C++11, but only because restricting the conditions under which the copy operations are generated would break too much legacy code.

How can I prevent my objects from being copied?

Declare copy constructor & copy assignment operator as private access specifier.

class MemoryBlock
{
public:

//code here

private:
MemoryBlock(const MemoryBlock& other)
{
   cout<<"copy constructor"<<endl;
}

// Copy assignment operator.
MemoryBlock& operator=(const MemoryBlock& other)
{
 return *this;
}
};

int main()
{
   MemoryBlock a;
   MemoryBlock b(a);
}

In C++11 onwards you can also declare copy constructor & assignment operator deleted

class MemoryBlock
{
public:
MemoryBlock(const MemoryBlock& other) = delete

// Copy assignment operator.
MemoryBlock& operator=(const MemoryBlock& other) =delete
};


int main()
{
   MemoryBlock a;
   MemoryBlock b(a);
}

ggplot2: sorting a plot

This seems to be what you're looking for:

g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()

The reorder() function will reorder your x axis items according to the value of variable.

Matplotlib connect scatterplot points with line - Python

For red lines an points

plt.plot(dates, values, '.r-') 

or for x markers and blue lines

plt.plot(dates, values, 'xb-')

How can I get form data with JavaScript/jQuery?

Based on jQuery.serializeArray, returns key-value pairs.

var data = $('#form').serializeArray().reduce(function(obj, item) {
    obj[item.name] = item.value;
    return obj;
}, {});

How to clear/remove observable bindings in Knockout.js?

You could try using the with binding that knockout offers: http://knockoutjs.com/documentation/with-binding.html The idea is to use apply bindings once, and whenever your data changes, just update your model.

Lets say you have a top level view model storeViewModel, your cart represented by cartViewModel, and a list of items in that cart - say cartItemsViewModel.

You would bind the top level model - the storeViewModel to the whole page. Then, you could separate the parts of your page that are responsible for cart or cart items.

Lets assume that the cartItemsViewModel has the following structure:

var actualCartItemsModel = { CartItems: [
  { ItemName: "FirstItem", Price: 12 }, 
  { ItemName: "SecondItem", Price: 10 }
] }

The cartItemsViewModel can be empty at the beginning.

The steps would look like this:

  1. Define bindings in html. Separate the cartItemsViewModel binding.

      
        <div data-bind="with: cartItemsViewModel">
          <div data-bind="foreach: CartItems">
            <span data-bind="text: ItemName"></span>
            <span data-bind="text: Price"></span>
          </div>
        </div>
      
    
  2. The store model comes from your server (or is created in any other way).

    var storeViewModel = ko.mapping.fromJS(modelFromServer)

  3. Define empty models on your top level view model. Then a structure of that model can be updated with actual data.

      
        storeViewModel.cartItemsViewModel = ko.observable();
        storeViewModel.cartViewModel = ko.observable();
     
    
  4. Bind the top level view model.

    ko.applyBindings(storeViewModel);

  5. When the cartItemsViewModel object is available then assign it to the previously defined placeholder.

    storeViewModel.cartItemsViewModel(actualCartItemsModel);

If you would like to clear the cart items: storeViewModel.cartItemsViewModel(null);

Knockout will take care of html - i.e. it will appear when model is not empty and the contents of div (the one with the "with binding") will disappear.

How to represent multiple conditions in a shell if statement?

In Bash:

if [[ ( $g == 1 && $c == 123 ) || ( $g == 2 && $c == 456 ) ]]

How to prevent scrollbar from repositioning web page?

If changing size or after loading some data it is adding the scroll bar then you can try following, create class and apply this class.

.auto-scroll {
   overflow-y: overlay;
   overflow-x: overlay;
}

How to fix getImageData() error The canvas has been tainted by cross-origin data?

As matt burns says in his answer, you may need to enable CORS on the server where the problem images are hosted.

If the server is Apache, this can be done by adding the following snippet (from here) to either your VirtualHost config or an .htaccess file:

<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS
        </FilesMatch>
    </IfModule>
</IfModule>

...if adding it to a VirtualHost, you'll probably need to reload Apache's config too (eg. sudo service apache2 reload if Apache's running on a Linux server)

Java Try Catch Finally blocks without Catch

Java versions before version 7 allow for these three combinations of try-catch-finally...

try - catch
try - catch - finally
try - finally

finally block will be always executed no matter of what's going on in the try or/and catch block. so if there is no catch block, the exception won't be handled here.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

  • Java try block must be followed by either catch or finally block.
  • For each try block there can be zero or more catch blocks, but only one finally block.
  • The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Elegant solution for line-breaks (PHP)

in php line breaks we can use PHP_EOL (END of LINE) .it working as "\n" but it cannot be shown on the ht ml page .because we have to give HTML break to break the Line..

so you can use it using define

define ("EOL","<br>");

then you can call it

Vertically align text within input field of fixed-height without display: table or padding?

I ran into this problem myself. I found that not specifying an input height, but using the font-height and padding combined, results in vertically aligned text.

For instance, lets say you want to have a 42px tall input box, with a font-size of 20px. You could simply find the difference between the input height and the font-size, divide it by two, and set your padding to that amount. In this case, you would have 22px total worth of padding, which is 11px on each side.

<input type="text" style="padding: 11px 0px 11px 0px; font-size: 20px;" />

That would give you a 42px tall input box with perfect vertical alignment.

Hope that helps.

iterating quickly through list of tuples

Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a dict out of your list of tuples and then looking up the value is as simple as looking up a key from the dict. Something like:

dct = dict(tuples)
val = dct.get(key) # None if item not found else the corresponding value

EDIT: To create a reverse mapping, use something like:

revDct = dict((val, key) for (key, val) in tuples)

AttributeError: Module Pip has no attribute 'main'

Edit file: C:\Users\kpate\hw6\python-zulip-api\zulip_bots\setup.py in line 108

to

rcode = pip.main(['install', '-r', req_path, '--quiet'])

do

rcode = getattr(pip, '_main', pip.main)(['install', '-r', req_path, '--quiet'])´

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

To add server using sp_addlinkedserver

-- check if server exists in table sys.server

select * from sys.servers

-- set database security

    EXEC sp_configure 'show advanced options', 1
    RECONFIGURE
    GO

    EXEC sp_configure 'ad hoc distributed queries', 1
    RECONFIGURE
    GO

-- add the external dbserver

EXEC sp_addlinkedserver @server='#servername#'

-- add login on external server

EXEC sp_addlinkedsrvlogin '#Servername#', 'false', NULL, '#username#', '#password@123"'

-- control query on remote table

select top (1000) * from [#server#].[#database#].[#schema#].[#table#]

Fixed GridView Header with horizontal and vertical scrolling in asp.net

// create this Js and add reference

var GridViewScrollOptions = /** @class */ (function () {
    function GridViewScrollOptions() {
    }
    return GridViewScrollOptions;
}());

var GridViewScroll = /** @class */ (function ()
 {

    function GridViewScroll(options) {
        this._initialized = false;
        if (options.elementID == null)
            options.elementID = "";
        if (options.width == null)
            options.width = "700";
        if (options.height == null)
            options.height = "350";
        if (options.freezeColumnCssClass == null)
            options.freezeColumnCssClass = "";
        if (options.freezeFooterCssClass == null)
            options.freezeFooterCssClass = "";
        if (options.freezeHeaderRowCount == null)
            options.freezeHeaderRowCount = 1;
        if (options.freezeColumnCount == null)
            options.freezeColumnCount = 1;
        this.initializeOptions(options);
    }
    GridViewScroll.prototype.initializeOptions = function (options) {
        this.GridID = options.elementID;
        this.GridWidth = options.width;
        this.GridHeight = options.height;
        this.FreezeColumn = options.freezeColumn;
        this.FreezeFooter = options.freezeFooter;
        this.FreezeColumnCssClass = options.freezeColumnCssClass;
        this.FreezeFooterCssClass = options.freezeFooterCssClass;
        this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
        this.FreezeColumnCount = options.freezeColumnCount;
    };

    GridViewScroll.prototype.enhance = function () 
{

        this.FreezeCellWidths = [];
        this.IsVerticalScrollbarEnabled = false;
        this.IsHorizontalScrollbarEnabled = false;
        if (this.GridID == null || this.GridID == "")
 {

            return;
        }

        this.ContentGrid = document.getElementById(this.GridID);
        if (this.ContentGrid == null) {

            return;
        }
        if (this.ContentGrid.rows.length < 2) {


            return;
        }
        if (this._initialized) {

            this.undo();
        }

        this._initialized = true;
        this.Parent = this.ContentGrid.parentNode;
        this.ContentGrid.style.display = "none";
        if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
            var percentage = parseInt(this.GridWidth);
            this.Width = this.Parent.offsetWidth * percentage / 100;
        }
        else {

            this.Width = parseInt(this.GridWidth);
        }
        if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {


            var percentage = parseInt(this.GridHeight);
            this.Height = this.Parent.offsetHeight * percentage / 100;
        }
        else {

            this.Height = parseInt(this.GridHeight);
        }

        this.ContentGrid.style.display = "";
        this.ContentGridHeaderRows = this.getGridHeaderRows();
        this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
        var footerIndex = this.ContentGrid.rows.length - 1;
        this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
        this.Content = document.createElement('div');
        this.Content.id = this.GridID + "_Content";
        this.Content.style.position = "relative";
        this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
        this.ContentFixed = document.createElement('div');
        this.ContentFixed.id = this.GridID + "_Content_Fixed";
        this.ContentFixed.style.overflow = "auto";
        this.ContentFixed = this.Content.appendChild(this.ContentFixed);
        this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
        this.ContentFixed.style.width = String(this.Width) + "px";
        if (this.ContentGrid.offsetWidth > this.Width) {

            this.IsHorizontalScrollbarEnabled = true;
        }

        if (this.ContentGrid.offsetHeight > this.Height) {

            this.IsVerticalScrollbarEnabled = true;
        }

        this.Header = document.createElement('div');
        this.Header.id = this.GridID + "_Header";
        this.Header.style.backgroundColor = "#F0F0F0";
        this.Header.style.position = "relative";
        this.HeaderFixed = document.createElement('div');
        this.HeaderFixed.id = this.GridID + "_Header_Fixed";
        this.HeaderFixed.style.overflow = "hidden";
        this.Header = this.Parent.insertBefore(this.Header, this.Content);
        this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
        this.ScrollbarWidth = this.getScrollbarWidth();
        this.prepareHeader();
        this.calculateHeader();
        this.Header.style.width = String(this.Width) + "px";
        if (this.IsVerticalScrollbarEnabled) {

            this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
            if (this.IsHorizontalScrollbarEnabled) {

                this.ContentFixed.style.width = this.HeaderFixed.style.width;
                if (this.isRTL()) {

                    this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
                }

                else {

                    this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
                }

            }

            this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
        }

        else {

            this.HeaderFixed.style.width = this.Header.style.width;
            this.ContentFixed.style.width = this.Header.style.width;
        }

        if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {

            this.appendFreezeHeader();
            this.appendFreezeContent();
        }
        if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {

            this.appendFreezeFooter();
            if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {


                this.appendFreezeFooterColumn();
            }
        }
        var self = this;
        this.ContentFixed.onscroll = function (event) {

            self.HeaderFixed.scrollLeft = self.ContentFixed.scrollLeft;
            if (self.ContentFreeze != null)
                self.ContentFreeze.scrollTop = self.ContentFixed.scrollTop;
            if (self.FooterFreeze != null)
                self.FooterFreeze.scrollLeft = self.ContentFixed.scrollLeft;
        };
    };
    GridViewScroll.prototype.getGridHeaderRows = function () {



        var gridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            gridHeaderRows.push(this.ContentGrid.rows.item(i));

        }
        return gridHeaderRows;
    };
    GridViewScroll.prototype.prepareHeader = function () {

        this.HeaderGrid = this.ContentGrid.cloneNode(false);
        this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
        this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
        this.prepareHeaderGridRows();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
            this.appendHelperElement(this.HeaderGridHeaderCells[i]);
        }
    };
    GridViewScroll.prototype.prepareHeaderGridRows = function () {

        this.HeaderGridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
            var gridHeaderRow = this.ContentGridHeaderRows[i];
            var headerGridHeaderRow = gridHeaderRow.cloneNode(true);
            this.HeaderGridHeaderRows.push(headerGridHeaderRow);
            this.HeaderGrid.appendChild(headerGridHeaderRow);
        }

        this.prepareHeaderGridCells();
    };
    GridViewScroll.prototype.prepareHeaderGridCells = function () {

        this.HeaderGridHeaderCells = new Array();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            for (var rowIndex in this.HeaderGridHeaderRows) {


                var cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
                var fixedCellIndex = 0;
                for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
                    var cgridHeaderCell = cgridHeaderRow.cells.item(cellIndex);
                    if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {

                        this.HeaderGridHeaderCells.push(cgridHeaderCell);
                    }
                    else {
                        fixedCellIndex += cgridHeaderCell.colSpan - 1;
                    }
                    fixedCellIndex++;
                }
            }
        }
    };
    GridViewScroll.prototype.calculateHeader = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            var helperWidth = parseInt(String(helperElement.offsetWidth));
            this.FreezeCellWidths.push(helperWidth);
            helperElement.style.width = helperWidth + "px";
            helperElement = this.HeaderGridHeaderCells[i].firstChild;
            helperElement.style.width = helperWidth + "px";
        }
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            this.ContentGridHeaderRows[i].style.display = "none";
        }
    };
    GridViewScroll.prototype.appendFreezeHeader = function () {

        this.HeaderFreeze = document.createElement('div');
        this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
        this.HeaderFreeze.style.position = "absolute";
        this.HeaderFreeze.style.overflow = "hidden";
        this.HeaderFreeze.style.top = "0px";
        this.HeaderFreeze.style.left = "0px";
        this.HeaderFreeze.style.width = "";
        this.HeaderFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
        this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
        this.HeaderFreezeGridHeaderRows = new Array();
        for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {

            var headerFreezeGridHeaderRow = this.HeaderGridHeaderRows[i].cloneNode(false);
            this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
                headerFreezeGridHeaderRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
        }
        this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
    };
    GridViewScroll.prototype.appendFreezeContent = function () {

        this.ContentFreeze = document.createElement('div');
        this.ContentFreeze.id = this.GridID + "_Content_Freeze";
        this.ContentFreeze.style.position = "absolute";
        this.ContentFreeze.style.overflow = "hidden";
        this.ContentFreeze.style.top = "0px";
        this.ContentFreeze.style.left = "0px";
        this.ContentFreeze.style.width = "";
        this.ContentFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
        this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
        var freezeCellHeights = [];
        var paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
        var paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var helperElement = void 0;
            if (gridItemCell.firstChild.className == "gridViewScrollHelper") {

                helperElement = gridItemCell.firstChild;
            }
            else {
                helperElement = this.appendHelperElement(gridItemCell);
            }
            var helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
            freezeCellHeights.push(helperHeight);
            var cgridItemRow = gridItemRow.cloneNode(false);
            var cgridItemCell = gridItemCell.cloneNode(true);
            if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
                cgridItemRow.className = this.FreezeColumnCssClass;
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = gridItemRow.cells.item(columnIndex).cloneNode(true);
                cgridItemRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.ContentFreezeGrid.appendChild(cgridItemRow);
        }
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var cgridItemRow = this.ContentFreezeGrid.rows.item(i);
            var cgridItemCell = cgridItemRow.cells.item(0);
            var helperElement = gridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
            helperElement = cgridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
        }
        if (this.IsVerticalScrollbarEnabled) {
            this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
        }
        else {
            this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
        }
        this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
    };
    GridViewScroll.prototype.appendFreezeFooter = function () {

        this.FooterFreeze = document.createElement('div');
        this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
        this.FooterFreeze.style.position = "absolute";
        this.FooterFreeze.style.overflow = "hidden";
        this.FooterFreeze.style.left = "0px";
        this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
        this.FooterFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
        this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
        this.FooterFreezeGridHeaderRow = this.ContentGridFooterRow.cloneNode(true);
        if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
            this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
        for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {

            var cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
            var helperElement = this.appendHelperElement(cgridHeaderCell);
            helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
        }
        this.FooterFreezeGridHeaderRow = this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
        this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
    };
    GridViewScroll.prototype.appendFreezeFooterColumn = function () {

        this.FooterFreezeColumn = document.createElement('div');
        this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
        this.FooterFreezeColumn.style.position = "absolute";
        this.FooterFreezeColumn.style.overflow = "hidden";
        this.FooterFreezeColumn.style.left = "0px";
        this.FooterFreezeColumn.style.width = "";
        this.FooterFreezeColumnGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
        this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeGridHeaderRow.cloneNode(false);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
        if (this.FreezeFooterCssClass != null)
            this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
        var columnIndex = 0;
        var columnCount = 0;
        while (columnCount < this.FreezeColumnCount) {

            var freezeColumn = this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
            this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
            columnCount += freezeColumn.colSpan;
            columnIndex++;
        }
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
        this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
    };
    GridViewScroll.prototype.appendHelperElement = function (gridItemCell) {

        var helperElement = document.createElement('div');
        helperElement.className = "gridViewScrollHelper";
        while (gridItemCell.hasChildNodes()) {

            helperElement.appendChild(gridItemCell.firstChild);
        }
        return gridItemCell.appendChild(helperElement);
    };
    GridViewScroll.prototype.getScrollbarWidth = function () {

        var innerElement = document.createElement('p');
        innerElement.style.width = "100%";
        innerElement.style.height = "200px";
        var outerElement = document.createElement('div');
        outerElement.style.position = "absolute";
        outerElement.style.top = "0px";
        outerElement.style.left = "0px";
        outerElement.style.visibility = "hidden";
        outerElement.style.width = "200px";
        outerElement.style.height = "150px";
        outerElement.style.overflow = "hidden";
        outerElement.appendChild(innerElement);
        document.body.appendChild(outerElement);
        var innerElementWidth = innerElement.offsetWidth;
        outerElement.style.overflow = 'scroll';
        var outerElementWidth = innerElement.offsetWidth;
        if (innerElementWidth === outerElementWidth)
            outerElementWidth = outerElement.clientWidth;
        document.body.removeChild(outerElement);
        return innerElementWidth - outerElementWidth;
    };
    GridViewScroll.prototype.isRTL = function () {

        var direction = "";
        if (window.getComputedStyle) {

            direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
        }
        else {
            direction = this.ContentGrid.currentStyle.direction;
        }
        return direction === "rtl";
    };
    GridViewScroll.prototype.getPaddingTop = function (element) {

        var value = "";
        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
        }
        else {

            value = element.currentStyle.paddingTop;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.getPaddingBottom = function (element) {
        var value = "";

        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
        }
        else {

            value = element.currentStyle.paddingBottom;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.undo = function () {

        this.undoHelperElement();
        for (var _i = 0, _a = this.ContentGridHeaderRows; _i < _a.length; _i++) {
            var contentGridHeaderRow = _a[_i];
            contentGridHeaderRow.style.display = "";
        }
        this.Parent.insertBefore(this.ContentGrid, this.Header);
        this.Parent.removeChild(this.Header);
        this.Parent.removeChild(this.Content);
        this._initialized = false;
    };
    GridViewScroll.prototype.undoHelperElement = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            while (helperElement.hasChildNodes()) {

                gridItemCell.appendChild(helperElement.firstChild);
            }
            gridItemCell.removeChild(helperElement);
        }
        if (this.FreezeColumn) {

            for (var i = 2; i < this.ContentGrid.rows.length; i++) {

                var gridItemRow = this.ContentGrid.rows.item(i);
                var gridItemCell = gridItemRow.cells.item(0);
                var helperElement = gridItemCell.firstChild;
                while (helperElement.hasChildNodes()) {


                    gridItemCell.appendChild(helperElement.firstChild);
                }
                gridItemCell.removeChild(helperElement);
            }
        }
    };
    return GridViewScroll;
}());

//add On Head

<head runat="server">
    <title></title>

    <script src="client/js/jquery-3.1.1.min.js"></script>

    <script src="js/gridviewscroll.js"></script>

    <script type="text/javascript">
        window.onload = function () {

            var gridViewScroll = new GridViewScroll({
                elementID: "GridView1" // [Header is fix column will be Freeze ][1]Target Control
            });
            gridViewScroll.enhance();
        }
    </script>

</head>

//Add on Body

<body>
    <form id="form1" runat="server">

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">

       // <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

           <%-- <Columns>
                <asp:BoundField DataField="SHIPMENT_ID" HeaderText="SHIPMENT_ID"
                    ReadOnly="True" SortExpression="SHIPMENT_ID" />
                <asp:BoundField DataField="TypeValue" HeaderText="TypeValue"
                    SortExpression="TypeValue" />
                <asp:BoundField DataField="CHAId" HeaderText="CHAId"
                    SortExpression="CHAId" />
                <asp:BoundField DataField="Status" HeaderText="Status"
                    SortExpression="Status" />
            </Columns>--%>
        </asp:GridView>

Concat a string to SELECT * MySql

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

How to get query params from url in Angular 2?

First off, what I have found working with Angular2 is that the url with a query string would be /path;query=value1

To access it in a component you use So is this, but now follows a code block:

    constructor(params: RouteParams){
    var val = params.get("query");
    }

As to why it would be removed when you load the component, that isn't default behavior. I checked specificly in a clean test project and wasn't redirected or changed. Is it a default route or something else that is special about the routing?

Read about routing with query strings and params in the Angular2 Tutorial at https://angular.io/docs/ts/latest/guide/router.html#!#query-parameters

How to wrap text in textview in Android

You must use 2 parameters :

  • android:ellipsize="none" : the text is not cut on textview width

  • android:scrollHorizontally="false" the text wraps on as many lines as necessary

RegEx for matching UK Postcodes

I wanted a simple regex, where it's fine to allow too much, but not to deny a valid postcode. I went with this (the input is a stripped/trimmed string):

/^([a-z0-9]\s*){5,8}$/i

This allows the shortest possible postcodes like "L1 8JQ" as well as the longest ones like "OL14 5ET".

Because it allows up to 8 characters, it will also allow incorrect 8 character postcodes if there is no space: "OL145ETX". But again, this is a simplistic regex, for when that's good enough.

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

If using a class-based view:

#
# in settings.py
#
YOUR_CUSTOM_SETTING = 'some value'

#
# in views.py
#
from django.conf import settings #for getting settings vars

class YourView(DetailView): #assuming DetailView; whatever though

    # ...

    def get_context_data(self, **kwargs):

        context = super(YourView, self).get_context_data(**kwargs)
        context['YOUR_CUSTOM_SETTING'] = settings.YOUR_CUSTOM_SETTING

        return context

#
# in your_template.html, reference the setting like any other context variable
#
{{ YOUR_CUSTOM_SETTING }}

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

What is the meaning of CTOR?

Usually this region should contains the constructors of the class

How to add shortcut keys for java code in eclipse

Type "Sysout" and then Ctrl+Space. It expands to

System.out.println();

Why do I get the "Unhandled exception type IOException"?

Try again with this code snippet:

import java.io.*;

class IO {
    public static void main(String[] args) {    
        try {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));    
            String userInput;    
            while ((userInput = stdIn.readLine()) != null) {
                System.out.println(userInput);
            }
        } catch(IOException ie) {
            ie.printStackTrace();
        }   
    }
}

Using try-catch-finally is better than using throws. Finding errors and debugging are easier when you use try-catch-finally.

Brew install docker does not include docker engine?

To install Docker for Mac with homebrew:

brew cask install docker

To install the command line completion:

brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion

Find rows that have the same value on a column in MySQL

use this if your email column contains empty values

 select * from table where email in (
    select email from table group by email having count(*) > 1 and email != ''
    )

new Date() is working in Chrome but not Firefox

This works in most browsers as well

new Date('2001/01/31 12:00:00')

That is the format of

"yyyy/MM/dd HH:mm:ss"

OS specific instructions in CMAKE: How to?

You have some special words from CMAKE, take a look:

if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
    // do something for Linux
else
    // do something for other OS

Can you control how an SVG's stroke-width is drawn?

Here is a work around for inner bordered rect using symbol and use.

Example: https://jsbin.com/yopemiwame/edit?html,output

SVG:

<svg>
  <symbol id="inner-border-rect">
    <rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
  </symbol>
  ...
  <use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>

Note: Make sure to replace the ? in use with real values.

Background: The reason why this works is because symbol establishes a new viewport by replacing symbol with svg and creating an element in the shadow DOM. This svg of the shadow DOM is then linked into your current SVG element. Note that svgs can be nested and every svg creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

How to mark-up phone numbers?

My test results:

callto:

  • Nokia Browser: nothing happens
  • Google Chrome: asks to run skype to call the number
  • Firefox: asks to choose a program to call the number
  • IE: asks to run skype to call the number

tel:

  • Nokia Browser: working
  • Google Chrome: nothing happens
  • Firefox: "Firefox doesnt know how to open this url"
  • IE: could not find url

How do I generate a SALT in Java for Salted-Hash?

Another version using SHA-3, I am using bouncycastle:

The interface:

public interface IPasswords {

    /**
     * Generates a random salt.
     *
     * @return a byte array with a 64 byte length salt.
     */
    byte[] getSalt64();

    /**
     * Generates a random salt
     *
     * @return a byte array with a 32 byte length salt.
     */
    byte[] getSalt32();

    /**
     * Generates a new salt, minimum must be 32 bytes long, 64 bytes even better.
     *
     * @param size the size of the salt
     * @return a random salt.
     */
    byte[] getSalt(final int size);

    /**
     * Generates a new hashed password
     *
     * @param password to be hashed
     * @param salt the randomly generated salt
     * @return a hashed password
     */
    byte[] hash(final String password, final byte[] salt);

    /**
     * Expected password
     *
     * @param password to be verified
     * @param salt the generated salt (coming from database)
     * @param hash the generated hash (coming from database)
     * @return true if password matches, false otherwise
     */
    boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash);

    /**
     * Generates a random password
     *
     * @param length desired password length
     * @return a random password
     */
    String generateRandomPassword(final int length);
}

The implementation:

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import org.bouncycastle.jcajce.provider.digest.SHA3;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public final class Passwords implements IPasswords, Serializable {

    /*serialVersionUID*/
    private static final long serialVersionUID = 8036397974428641579L;
    private static final Logger LOGGER = Logger.getLogger(Passwords.class);
    private static final Random RANDOM = new SecureRandom();
    private static final int DEFAULT_SIZE = 64;
    private static final char[] symbols;

    static {
            final StringBuilder tmp = new StringBuilder();
            for (char ch = '0'; ch <= '9'; ++ch) {
                    tmp.append(ch);
            }
            for (char ch = 'a'; ch <= 'z'; ++ch) {
                    tmp.append(ch);
            }
            symbols = tmp.toString().toCharArray();
    }

    @Override public byte[] getSalt64() {
            return getSalt(DEFAULT_SIZE);
    }

    @Override public byte[] getSalt32() {
            return getSalt(32);
    }

    @Override public byte[] getSalt(int size) {
            final byte[] salt;
            if (size < 32) {
                    final String message = String.format("Size < 32, using default of: %d", DEFAULT_SIZE);
                    LOGGER.warn(message);
                    salt = new byte[DEFAULT_SIZE];
            } else {
                    salt = new byte[size];
            }
            RANDOM.nextBytes(salt);
            return salt;
    }

    @Override public byte[] hash(String password, byte[] salt) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);
                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    return md.digest();
            } catch (UnsupportedEncodingException e) {
                    final String message = String
                            .format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return new byte[0];
    }

    @Override public boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash) {

            Validate.notNull(password, "Password must not be null");
            Validate.notNull(salt, "Salt must not be null");
            Validate.notNull(hash, "Hash must not be null");

            try {
                    final byte[] passwordBytes = password.getBytes("UTF-8");
                    final byte[] all = ArrayUtils.addAll(passwordBytes, salt);

                    SHA3.DigestSHA3 md = new SHA3.Digest512();
                    md.update(all);
                    final byte[] digest = md.digest();
                    return Arrays.equals(digest, hash);
            }catch(UnsupportedEncodingException e){
                    final String message =
                            String.format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
                    LOGGER.error(message);
            }
            return false;


    }

    @Override public String generateRandomPassword(final int length) {

            if (length < 1) {
                    throw new IllegalArgumentException("length must be greater than 0");
            }

            final char[] buf = new char[length];
            for (int idx = 0; idx < buf.length; ++idx) {
                    buf[idx] = symbols[RANDOM.nextInt(symbols.length)];
            }
            return shuffle(new String(buf));
    }


    private String shuffle(final String input){
            final List<Character> characters = new ArrayList<Character>();
            for(char c:input.toCharArray()){
                    characters.add(c);
            }
            final StringBuilder output = new StringBuilder(input.length());
            while(characters.size()!=0){
                    int randPicker = (int)(Math.random()*characters.size());
                    output.append(characters.remove(randPicker));
            }
            return output.toString();
    }
}

The test cases:

public class PasswordsTest {

    private static final Logger LOGGER = Logger.getLogger(PasswordsTest.class);

    @Before
    public void setup(){
            BasicConfigurator.configure();
    }

    @Test
    public void testGeSalt() throws Exception {

            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt(0);
            int arrayLength = bytes.length;

            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testGeSalt32() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt32();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(32));
    }

    @Test
    public void testGeSalt64() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] bytes = passwords.getSalt64();
            int arrayLength = bytes.length;
            assertThat("Expected length is", arrayLength, is(64));
    }

    @Test
    public void testHash() throws Exception {
            IPasswords passwords = new Passwords();
            final byte[] hash = passwords.hash("holacomoestas", passwords.getSalt64());
            assertThat("Array is not null", hash, Matchers.notNullValue());
    }


    @Test
    public void testSHA3() throws UnsupportedEncodingException {
            SHA3.DigestSHA3 md = new SHA3.Digest256();
            md.update("holasa".getBytes("UTF-8"));
            final byte[] digest = md.digest();
             assertThat("expected digest is:",digest,Matchers.notNullValue());
    }

    @Test
    public void testIsExpectedPasswordIncorrect() throws Exception {

            String password = "givemebeer";
            IPasswords passwords = new Passwords();

            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.

            final boolean isPasswordCorrect = passwords.isExpectedPassword("jfjdsjfsd", salt64, hash);

            assertThat("Password is not correct", isPasswordCorrect, is(false));

    }

    @Test
    public void testIsExpectedPasswordCorrect() throws Exception {
            String password = "givemebeer";
            IPasswords passwords = new Passwords();
            final byte[] salt64 = passwords.getSalt64();
            final byte[] hash = passwords.hash(password, salt64);
            //The salt and the hash go to database.
            final boolean isPasswordCorrect = passwords.isExpectedPassword("givemebeer", salt64, hash);
            assertThat("Password is correct", isPasswordCorrect, is(true));
    }

    @Test
    public void testGenerateRandomPassword() throws Exception {
            IPasswords passwords = new Passwords();
            final String randomPassword = passwords.generateRandomPassword(10);
            LOGGER.info(randomPassword);
            assertThat("Random password is not null", randomPassword, Matchers.notNullValue());
    }
}

pom.xml (only dependencies):

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.1.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.51</version>
        <type>jar</type>
    </dependency>


    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.3.2</version>
    </dependency>


</dependencies>

replace special characters in a string python

You can replace the special characters with the desired characters as follows,

import string
specialCharacterText = "H#y #@w @re &*)?"
inCharSet = "!@#$%^&*()[]{};:,./<>?\|`~-=_+\""
outCharSet = "                               " #corresponding characters in inCharSet to be replaced
splCharReplaceList = string.maketrans(inCharSet, outCharSet)
splCharFreeString = specialCharacterText.translate(splCharReplaceList)

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

In my case, I created a new table with the same structure, created the relationships with the other tables, then extracted the data in CSV from the old table that has the problem, then imported the CSV to the new table and disabled foreign key checking and disabled import interruption, all my data are inserted to the new table that has no problem successfully, then deleted the old table.

It worked for me.

What is the best way to create and populate a numbers table?

I use numbers tables for primarily dummying up reports in BIRT without having to fiddle around with dynamic creation of recordsets.

I do the same with dates, having a table spanning from 10 years in the past to 10 years in the future (and hours of the day for more detailed reporting). It's a neat trick to be able to get values for all dates even if your 'real' data tables don't have data for them.

I have a script which I use to create these, something like (this is from memory):

drop table numbers; commit;
create table numbers (n integer primary key); commit;
insert into numbers values (0); commit;
insert into numbers select n+1 from numbers; commit;
insert into numbers select n+2 from numbers; commit;
insert into numbers select n+4 from numbers; commit;
insert into numbers select n+8 from numbers; commit;
insert into numbers select n+16 from numbers; commit;
insert into numbers select n+32 from numbers; commit;
insert into numbers select n+64 from numbers; commit;

The number of rows doubles with each line so it doesn't take a lot to produce truly huge tables.

I'm not sure I agree with you that it's important to be created fast since you only create it once. The cost of that is amortized over all the accesses to it, rendering that time fairly insignificant.

How To Convert A Number To an ASCII Character?

To get ascii to a number, you would just cast your char value into an integer.

char ascii = 'a'
int value = (int)ascii

Variable value will now have 97 which corresponds to the value of that ascii character

(Use this link for reference) http://www.asciitable.com/index/asciifull.gif

Reading rows from a CSV file in Python

Example:

import pandas as pd

data = pd.read_csv('data.csv')

# read row line by line
for d in data.values:
  # read column by index
  print(d[2])

How can I change the font size using seaborn FacetGrid?

The FacetGrid plot does produce pretty small labels. While @paul-h has described the use of sns.set as a way to the change the font scaling, it may not be the optimal solution since it will change the font_scale setting for all plots.

You could use the seaborn.plotting_context to change the settings for just the current plot:

with sns.plotting_context(font_scale=1.5):
    sns.factorplot(x, y ...)

Creating a simple configuration file and parser in C++

I've searched config parsing libraries for my project recently and found these libraries:

Iterate keys in a C++ map

Lots of good answers here, below is an approach using a couple of them which lets you write this:

void main()
{
    std::map<std::string, int> m { {"jim", 1000}, {"sally", 2000} };
    for (auto key : MapKeys(m))
        std::cout << key << std::endl;
}

If that's what you always wanted, then here is the code for MapKeys():

template <class MapType>
class MapKeyIterator {
public:
    class iterator {
    public:
        iterator(typename MapType::iterator it) : it(it) {}
        iterator operator++() { return ++it; }
        bool operator!=(const iterator & other) { return it != other.it; }
        typename MapType::key_type operator*() const { return it->first; }  // Return key part of map
    private:
        typename MapType::iterator it;
    };
private:
    MapType& map;
public:
    MapKeyIterator(MapType& m) : map(m) {}
    iterator begin() { return iterator(map.begin()); }
    iterator end() { return iterator(map.end()); }
};
template <class MapType>
MapKeyIterator<MapType> MapKeys(MapType& m)
{
    return MapKeyIterator<MapType>(m);
}

java - iterating a linked list

iterate LinkedList by using iterator

LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add(“Mumbai”);
linkedList.add(“Delhi”);
linkedList.add(“Noida”);
linkedList.add(“Gao”);
linkedList.add(“Patna”);

Iterator<String>  itr = linkedList.iterator();
 while (itr.hasNext()) {
 System.out.println(“Element is =”+itr.next());

 }

Reference : Java Linkedlist Examples

Add a tooltip to a div

You don't need JavaScript for this at all; just set the title attribute:

<div title="Hello, World!">
  <label>Name</label>
  <input type="text"/>
</div>

Note that the visual presentation of the tooltip is browser/OS dependent, so it might fade in and it might not. However, this is the semantic way to do tooltips, and it will work correctly with accessibility software like screen readers.

Demo in Stack Snippets

_x000D_
_x000D_
<div title="Hello, World!">_x000D_
  <label>Name</label>_x000D_
  <input type="text"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Increase distance between text and title on the y-axis

Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU

Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.

ggplot(mpg, aes(cty, hwy)) + 
    geom_point() + 
    xlab("\nYour_x_Label") + ylab("Your_y_Label\n")

Hope that helps!

How to use sed/grep to extract text between two words?

Through GNU awk,

$ echo "Here is a string" | awk -v FS="(Here|string)" '{print $2}'
 is a 

grep with -P(perl-regexp) parameter supports \K, which helps in discarding the previously matched characters. In our case , the previously matched string was Here so it got discarded from the final output.

$ echo "Here is a string" | grep -oP 'Here\K.*(?=string)'
 is a 
$ echo "Here is a string" | grep -oP 'Here\K(?:(?!string).)*'
 is a 

If you want the output to be is a then you could try the below,

$ echo "Here is a string" | grep -oP 'Here\s*\K.*(?=\s+string)'
is a
$ echo "Here is a string" | grep -oP 'Here\s*\K(?:(?!\s+string).)*'
is a

How to install latest version of Node using Brew

After installation/upgrading node via brew I ran into this issue exactly: the node command worked but not the npm command.

I used these commands to fix it.

brew uninstall node
brew update
brew upgrade
brew cleanup
brew install node
sudo chown -R $(whoami) /usr/local
brew link --overwrite node
brew postinstall node

I pieced together this solution after trial and error using...

Python pandas Filtering out nan from a data selection of a column of strings

Just drop them:

nms.dropna(thresh=2)

this will drop all rows where there are at least two non-NaN.

Then you could then drop where name is NaN:

In [87]:

nms
Out[87]:
  movie    name  rating
0   thg    John       3
1   thg     NaN       4
3   mol  Graham     NaN
4   lob     NaN     NaN
5   lob     NaN     NaN

[5 rows x 3 columns]
In [89]:

nms = nms.dropna(thresh=2)
In [90]:

nms[nms.name.notnull()]
Out[90]:
  movie    name  rating
0   thg    John       3
3   mol  Graham     NaN

[2 rows x 3 columns]

EDIT

Actually looking at what you originally want you can do just this without the dropna call:

nms[nms.name.notnull()]

UPDATE

Looking at this question 3 years later, there is a mistake, firstly thresh arg looks for at least n non-NaN values so in fact the output should be:

In [4]:
nms.dropna(thresh=2)

Out[4]:
  movie    name  rating
0   thg    John     3.0
1   thg     NaN     4.0
3   mol  Graham     NaN

It's possible that I was either mistaken 3 years ago or that the version of pandas I was running had a bug, both scenarios are entirely possible.

sort files by date in PHP

$files = array_diff(scandir($dir,SCANDIR_SORT_DESCENDING), array('..', '.'));
print_r($files);

scp (secure copy) to ec2 instance without password

To use PSCP, you need the private key you generated in Converting Your Private Key Using PuTTYgen. You also need the public DNS address of your Linux instance

pscp -i C:\path\my-key-pair.ppk C:\path\Sample_file.txt ec2-user@public_dns:/home/ec2-user/Sample_file.txt

How to cast int to enum in C++?

Spinning off the closing question, "how do I convert a to type Test::A" rather than being rigid about the requirement to have a cast in there, and answering several years late only because this seems to be a popular question and nobody else has mentioned the alternative, per the C++11 standard:

5.2.9 Static cast

... an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

Therefore directly using the form t(e) will also work, and you might prefer it for neatness:

auto result = Test(a);

Get a list of all the files in a directory (recursive)

This is what I came up with for a gradle build script:

task doLast {
    ext.FindFile = { list, curPath ->
        def files = file(curPath).listFiles().sort()

        files.each {  File file ->

            if (file.isFile()) {
                list << file
            }
            else {
                list << file  // If you want the directories in the list

                list = FindFile( list, file.path) 
            }
        }
        return list
    }

    def list = []
    def theFile = FindFile(list, "${project.projectDir}")

    list.each {
        println it.path
    }
}

Swift extract regex matches

If you want to extract substrings from a String, not just the position, (but the actual String including emojis). Then, the following maybe a simpler solution.

extension String {
  func regex (pattern: String) -> [String] {
    do {
      let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0))
      let nsstr = self as NSString
      let all = NSRange(location: 0, length: nsstr.length)
      var matches : [String] = [String]()
      regex.enumerateMatchesInString(self, options: NSMatchingOptions(rawValue: 0), range: all) {
        (result : NSTextCheckingResult?, _, _) in
        if let r = result {
          let result = nsstr.substringWithRange(r.range) as String
          matches.append(result)
        }
      }
      return matches
    } catch {
      return [String]()
    }
  }
} 

Example Usage:

"someText ?? pig".regex("??")

Will return the following:

["??"]

Note using "\w+" may produce an unexpected ""

"someText ?? pig".regex("\\w+")

Will return this String array

["someText", "?", "pig"]

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

Pass a variable to a PHP script running from the command line

You can use the following code to both work with the command line and a web browser. Put this code above your PHP code. It creates a $_GET variable for each command line parameter.

In your code you only need to check for $_GET variables then, not worrying about if the script is called from the web browser or command line.

if(isset($argv))
    foreach ($argv as $arg) {
        $e=explode("=",$arg);
        if(count($e)==2)
            $_GET[$e[0]]=$e[1];
        else
            $_GET[$e[0]]=0;
    }

how to File.listFiles in alphabetical order?

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

How do you properly use namespaces in C++?

Don't listen to every people telling you that namespaces are just name-spaces.

They are important because they are considered by the compiler to apply the interface principle. Basically, it can be explained by an example:

namespace ns {

class A
{
};

void print(A a)
{
}

}

If you wanted to print an A object, the code would be this one:

ns::A a;
print(a);

Note that we didn't explicitly mention the namespace when calling the function. This is the interface principle: C++ consider a function taking a type as an argument as being part of the interface for that type, so no need to specify the namespace because the parameter already implied the namespace.

Now why this principle is important? Imagine that the class A author did not provide a print() function for this class. You will have to provide one yourself. As you are a good programmer, you will define this function in your own namespace, or maybe in the global namespace.

namespace ns {

class A
{
};

}

void print(A a)
{
}

And your code can start calling the print(a) function wherever you want. Now imagine that years later, the author decides to provide a print() function, better than yours because he knows the internals of his class and can make a better version than yours.

Then C++ authors decided that his version of the print() function should be used instead of the one provided in another namespace, to respect the interface principle. And that this "upgrade" of the print() function should be as easy as possible, which means that you won't have to change every call to the print() function. That's why "interface functions" (function in the same namespace as a class) can be called without specifying the namespace in C++.

And that's why you should consider a C++ namespace as an "interface" when you use one and keep in mind the interface principle.

If you want better explanation of this behavior, you can refer to the book Exceptional C++ from Herb Sutter

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

What is fastest children() or find() in jQuery?

Both find() and children() methods are used to filter the child of the matched elements, except the former is travels any level down, the latter is travels a single level down.

To simplify:

  1. find() – search through the matched elements’ child, grandchild, great-grandchild... all levels down.
  2. children() – search through the matched elements’ child only (single level down).

Equivalent of *Nix 'which' command in PowerShell?

A quick-and-dirty match to Unix which is

New-Alias which where.exe

But it returns multiple lines if they exist so then it becomes

function which {where.exe command | select -first 1}

Where do I call the BatchNormalization function in Keras?

This thread is misleading. Tried commenting on Lucas Ramadan's answer, but I don't have the right privileges yet, so I'll just put this here.

Batch normalization works best after the activation function, and here or here is why: it was developed to prevent internal covariate shift. Internal covariate shift occurs when the distribution of the activations of a layer shifts significantly throughout training. Batch normalization is used so that the distribution of the inputs (and these inputs are literally the result of an activation function) to a specific layer doesn't change over time due to parameter updates from each batch (or at least, allows it to change in an advantageous way). It uses batch statistics to do the normalizing, and then uses the batch normalization parameters (gamma and beta in the original paper) "to make sure that the transformation inserted in the network can represent the identity transform" (quote from original paper). But the point is that we're trying to normalize the inputs to a layer, so it should always go immediately before the next layer in the network. Whether or not that's after an activation function is dependent on the architecture in question.

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

What does %5B and %5D in POST requests stand for?

As per this answer over here: str='foo%20%5B12%5D' encodes foo [12]:

%20 is space
%5B is '['
and %5D is ']'

This is called percent encoding and is used in encoding special characters in the url parameter values.

EDIT By the way as I was reading https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURI#Description, it just occurred to me why so many people make the same search. See the note on the bottom of the page:

Also note that if one wishes to follow the more recent RFC3986 for URL's, making square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following may help.

function fixedEncodeURI (str) {
    return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']');
}

Hopefully this will help people sort out their problems when they stumble upon this question.

What is the canonical way to check for errors using the CUDA runtime API?

The C++-canonical way: Don't check for errors...use the C++ bindings which throw exceptions.

I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.

So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd sample - with complete error checking of every runtime API call:

// (... prepare host-side buffers here ...)

auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);

cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);

// (... prepare a launch configuration here... )

cuda::launch(vectorAdd, launch_config,
    d_A.get(), d_B.get(), d_C.get(), numElements
);    
cuda::memory::copy(h_C.get(), d_C.get(), size);

// (... verify results here...)

Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none() command).

The code above uses my

Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)

Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.

A few links to how CUDA errors are automagically checked with these wrappers:

How do you use script variables in psql?

I really miss that feature. Only way to achieve something similar is to use functions.

I have used it in two ways:

  • perl functions that use $_SHARED variable
  • store your variables in table

Perl version:

   CREATE FUNCTION var(name text, val text) RETURNS void AS $$
        $_SHARED{$_[0]} = $_[1];
   $$ LANGUAGE plperl;
   CREATE FUNCTION var(name text) RETURNS text AS $$
        return $_SHARED{$_[0]};
   $$ LANGUAGE plperl;

Table version:

CREATE TABLE var (
  sess bigint NOT NULL,
  key varchar NOT NULL,
  val varchar,
  CONSTRAINT var_pkey PRIMARY KEY (sess, key)
);
CREATE FUNCTION var(key varchar, val anyelement) RETURNS void AS $$
  DELETE FROM var WHERE sess = pg_backend_pid() AND key = $1;
  INSERT INTO var (sess, key, val) VALUES (sessid(), $1, $2::varchar);
$$ LANGUAGE 'sql';

CREATE FUNCTION var(varname varchar) RETURNS varchar AS $$
  SELECT val FROM var WHERE sess = pg_backend_pid() AND key = $1;
$$ LANGUAGE 'sql';

Notes:

  • plperlu is faster than perl
  • pg_backend_pid is not best session identification, consider using pid combined with backend_start from pg_stat_activity
  • this table version is also bad because you have to clear this is up occasionally (and not delete currently working session variables)

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

Triggering change detection manually in Angular

I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:

  1. Import NgZone:

    import { Component, NgZone } from '@angular/core';
    
  2. Add it to your class constructor

    constructor(public zone: NgZone, ...args){}
    
  3. Run code with zone.run:

    this.zone.run(() => this.donations = donations)
    

See whether an item appears more than once in a database column

How about:

select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;

Java string replace and the NUL (NULL, ASCII 0) character?

Should be probably changed to

firstName = firstName.trim().replaceAll("\\.", "");

Set margins in a LinearLayout programmatically

I have set up margins directly using below code

LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);            
params.setMargins(3, 300, 3, 3); 
layout.setLayoutParams(params);

Only thing here is to notice that LayoutParams should be imported for following package android.widget.RelativeLayout.LayoutParams, or else there will be an error.

insert data into database with codeigniter

function order_summary_insert()
$OrderLines=$this->input->post('orderlines');
$CustomerName=$this->input->post('customer');
$data = array(
'OrderLines'=>$OrderLines,
'CustomerName'=>$CustomerName
);

$this->db->insert('Customer_Orders',$data);
}

Creating a new column based on if-elif-else condition

To formalize some of the approaches laid out above:

Create a function that operates on the rows of your dataframe like so:

def f(row):
    if row['A'] == row['B']:
        val = 0
    elif row['A'] > row['B']:
        val = 1
    else:
        val = -1
    return val

Then apply it to your dataframe passing in the axis=1 option:

In [1]: df['C'] = df.apply(f, axis=1)

In [2]: df
Out[2]:
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.

Edit

Here is the vectorized version

df['C'] = np.where(
    df['A'] == df['B'], 0, np.where(
    df['A'] >  df['B'], 1, -1)) 

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

This is the most simple, and it worked for me:

In the values-21:

<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        ...
        <item name="android:windowTranslucentStatus">true</item>
    </style>
    <dimen name="topMargin">25dp</dimen>
</resources>

In the values:

<resources>
    <dimen name="topMargin">0dp</dimen>
</resources>

And set to your toolbar

android:layout_marginTop="@dimen/topMargin"

What is the difference between a strongly typed language and a statically typed language?

What is the difference between a strongly typed language and a statically typed language?

A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.

There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static vs dynamic

The opposite of statically typed is "dynamically typed", which means that

  1. Values used at run time are classified into types.
  2. There are restrictions on how such values can be used.
  3. When those restrictions are violated, the violation is reported as a (dynamic) type error.

For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.

Strong vs weak

The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What's really going on here?

Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because

  • Amateurs often conflate them with "static" and "dynamic".

  • Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.

  • Professionals can't agree on exactly what the terms mean.

  • Overall you are unlikely to inform or enlighten your audience.

The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.

By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".

Does one imply the other?

On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:

  • They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.

  • They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.

Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.

Calculate time difference in Windows batch file

A re-hash of Aacini's code because most likely you are going to set the start time as a variable and want to save that data for output:

    @echo off

    rem ******************  MAIN CODE SECTION
    set STARTTIME=%TIME%

    rem Your code goes here (remove the ping line)
    ping -n 4 -w 1 127.0.0.1 >NUL

    set ENDTIME=%TIME%

    rem ******************  END MAIN CODE SECTION


    rem Change formatting for the start and end times
    for /F "tokens=1-4 delims=:.," %%a in ("%STARTTIME%") do (
       set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
    )

    for /F "tokens=1-4 delims=:.," %%a in ("%ENDTIME%") do ( 
       IF %ENDTIME% GTR %STARTTIME% set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
       IF %ENDTIME% LSS %STARTTIME% set /A "end=((((%%a+24)*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
    )

    rem Calculate the elapsed time by subtracting values
    set /A elapsed=end-start

    rem Format the results for output
    set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
    if %hh% lss 10 set hh=0%hh%
    if %mm% lss 10 set mm=0%mm%
    if %ss% lss 10 set ss=0%ss%
    if %cc% lss 10 set cc=0%cc%

    set DURATION=%hh%:%mm%:%ss%,%cc%

    echo Start    : %STARTTIME%
    echo Finish   : %ENDTIME%
    echo          ---------------
    echo Duration : %DURATION% 

Output:

    Start    : 11:02:45.92
    Finish   : 11:02:48.98
             ---------------
    Duration : 00:00:03,06

How do I check if a variable exists?

catch is called except in Python. other than that it's fine for such simple cases. There's the AttributeError that can be used to check if an object has an attribute.

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

Answer that worked here.

They recommend checking the installer file name. It needs to be the original name oddly enough for the setup to work.

Ascending and Descending Number Order in java

Just sort the array in ascending order and print it backwards.

Arrays.sort(arr);
for(int i = arr.length-1; i >= 0 ; i--) {
    //print arr[i]
}

Implicit type conversion rules in C++ operators

Arithmetic operations involving float results in float.

int + float = float
int * float = float
float * int = float
int / float = float
float / int = float
int / int = int

For more detail answer. Look at what the section §5/9 from the C++ Standard says

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result.

This pattern is called the usual arithmetic conversions, which are defined as follows:

— If either operand is of type long double, the other shall be converted to long double.

— Otherwise, if either operand is double, the other shall be converted to double.

— Otherwise, if either operand is float, the other shall be converted to float.

— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)

— Then, if either operand is unsigned long the other shall be converted to unsigned long.

— Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int; otherwise both operands shall be converted to unsigned long int.

— Otherwise, if either operand is long, the other shall be converted to long.

— Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

[Note: otherwise, the only remaining case is that both operands are int ]

How can one print a size_t variable portably using the printf family?

Use the z modifier:

size_t x = ...;
ssize_t y = ...;
printf("%zu\n", x);  // prints as unsigned decimal
printf("%zx\n", x);  // prints as hex
printf("%zd\n", y);  // prints as signed decimal

Scanner only reads first word instead of line

Use input.nextLine(); instead of input.next();

Git push requires username and password

If you've got 2FA enabled on your Github account, your regular password won't work for this purpose, but you can generate a Personal Access Token and use that in its place instead.

Visit the Settings -> Developer Settings -> Personal Access Tokens page in GitHub (https://github.com/settings/tokens/new), and generate a new Token with all Repo permissions:

generate GitHub personal access token

The page will then display the new token value. Save this value and use it in place of your password when pushing to your repository on GitHub:

> git push origin develop
Username for 'https://github.com': <your username>
Password for 'https://<your username>@github.com': <your personal access token>

Better way to cast object to int

Use Int32.TryParse as follows.

  int test;
  bool result = Int32.TryParse(value, out test);
  if (result)
  {
     Console.WriteLine("Sucess");         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Failure");
  }

Create array of regex matches

(4castle's answer is better than the below if you can assume Java >= 9)

You need to create a matcher and use that to iteratively find matches.

 import java.util.regex.Matcher;
 import java.util.regex.Pattern;

 ...

 List<String> allMatches = new ArrayList<String>();
 Matcher m = Pattern.compile("your regular expression here")
     .matcher(yourStringHere);
 while (m.find()) {
   allMatches.add(m.group());
 }

After this, allMatches contains the matches, and you can use allMatches.toArray(new String[0]) to get an array if you really need one.


You can also use MatchResult to write helper functions to loop over matches since Matcher.toMatchResult() returns a snapshot of the current group state.

For example you can write a lazy iterator to let you do

for (MatchResult match : allMatches(pattern, input)) {
  // Use match, and maybe break without doing the work to find all possible matches.
}

by doing something like this:

public static Iterable<MatchResult> allMatches(
      final Pattern p, final CharSequence input) {
  return new Iterable<MatchResult>() {
    public Iterator<MatchResult> iterator() {
      return new Iterator<MatchResult>() {
        // Use a matcher internally.
        final Matcher matcher = p.matcher(input);
        // Keep a match around that supports any interleaving of hasNext/next calls.
        MatchResult pending;

        public boolean hasNext() {
          // Lazily fill pending, and avoid calling find() multiple times if the
          // clients call hasNext() repeatedly before sampling via next().
          if (pending == null && matcher.find()) {
            pending = matcher.toMatchResult();
          }
          return pending != null;
        }

        public MatchResult next() {
          // Fill pending if necessary (as when clients call next() without
          // checking hasNext()), throw if not possible.
          if (!hasNext()) { throw new NoSuchElementException(); }
          // Consume pending so next call to hasNext() does a find().
          MatchResult next = pending;
          pending = null;
          return next;
        }

        /** Required to satisfy the interface, but unsupported. */
        public void remove() { throw new UnsupportedOperationException(); }
      };
    }
  };
}

With this,

for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
  System.out.println(match.group() + " at " + match.start());
}

yields

a at 0
b at 1
a at 3
c at 4
a at 5
a at 7
b at 8
a at 10

How to read text files with ANSI encoding and non-English letters?

If I remember correctly the XmlDocument.Load(string) method always assumes UTF-8, regardless of the XML encoding. You would have to create a StreamReader with the correct encoding and use that as the parameter.

xmlDoc.Load(new StreamReader(
                     File.Open("file.xml"), 
                     Encoding.GetEncoding("iso-8859-15"))); 

I just stumbled across KB308061 from Microsoft. There's an interesting passage: Specify the encoding declaration in the XML declaration section of the XML document. For example, the following declaration indicates that the document is in UTF-16 Unicode encoding format:

<?xml version="1.0" encoding="UTF-16"?>

Note that this declaration only specifies the encoding format of an XML document and does not modify or control the actual encoding format of the data.

Link Source:

XmlDocument.Load() method fails to decode € (euro)

Escaping single quote in PHP when inserting into MySQL

You should be escaping each of these strings (in both snippets) with mysql_real_escape_string().

http://us3.php.net/mysql-real-escape-string

The reason your two queries are behaving differently is likely because you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Brien" -> "O\'Brien").

Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Brien". So, you will need to pass it through mysql_real_escape_string().

Is there an onSelect event or equivalent for HTML <select>?

What works for me:

<select id='myID' onchange='doSomething();'>
    <option value='0' selected> Select Option </option>
    <option value='1' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > A </option>
    <option value='2' onclick='if (!document.getElementById("myID").onchange()) doSomething();' > B </option>
</select>

In that way, onchange calls 'doSomething()' when the option changes, and onclick calls 'doSomething()' when onchange event is false, in other words, when you select the same option

Passing a dictionary to a function as keyword parameters

In python, this is called "unpacking", and you can find a bit about it in the tutorial. The documentation of it sucks, I agree, especially because of how fantasically useful it is.

Convert laravel object to array

You need to iterate over the array

for ($i = 0, $c = count($array); $i < $c; ++$i) {
    $array[$i] = (array) $array[$i];
}

ans use (array) conversion because you have array of objects of Std class and not object itself

Example:

$users = DB::table('users')->get();

var_dump($users);

echo "<br /><br />";

for ($i = 0, $c = count($users); $i < $c; ++$i) {
    $users[$i] = (array) $users[$i];
}
var_dump($users);
exit;

Output for this is:

array(1) { [0]=> object(stdClass)#258 (8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } }

array(1) { [0]=> array(8) { ["id"]=> int(1) ["user_name"]=> string(5) "admin" ["email"]=> string(11) "admin@admin" ["passwd"]=> string(60) "$2y$10$T/0fW18gPGgz0CILTy2hguxNpcNjYZHsTyf5dvpor9lYMw/mtKYfi" ["balance"]=> string(4) "0.00" ["remember_token"]=> string(60) "moouXQOJFhtxkdl9ClEXYh9ioBSsRp28WZZbLPkJskcCr0325TyrxDK4al5H" ["created_at"]=> string(19) "2014-10-01 12:00:00" ["updated_at"]=> string(19) "2014-09-27 12:20:54" } } 

as expected. Object of stdClass has been converted to array.

How to copy commits from one branch to another?

Use

git cherry-pick <commit>

to apply <commit> to your current branch.

I myself would probably cross-check the commits I pick in gitk and cherry-pick them with right-clicks on the commit entry there instead.


If you want to go more automatic (with all its dangers) and assuming all commits since yesterday happened on wss you could generate the list of commits using git log (with --pretty suggested by Jefromi)

git log --reverse --since=yesterday --pretty=%H

so everything together assuming you use bash

for commit in $(git log --reverse --since=yesterday --pretty=%H);
do
    git cherry-pick $commit
done

If something goes wrong here (there is a lot of potential) you are in trouble since this works on the live checkout, so either do manual cherry-picks or use rebase like suggested by Jefromi.

Serializing to JSON in jQuery

Works on IE8+

No need for jQuery, use:

JSON.stringify(countries); 

How do I view / replay a chrome network debugger har file saved with content?

Chrome Dev Tool's "Network" tool now allows you to import HAR files by drag-and-dropping into the window.

Compare two files in Visual Studio

If you have VS installed, you could also call

"%VS110COMNTOOLS%..\IDE\vsdiffmerge.exe" "File1" "File2"

or for VS 2013

"%VS120COMNTOOLS%..\IDE\vsdiffmerge.exe" "File1" "File2"

Source: http://roadtoalm.com/2013/10/22/use-visual-studio-as-your-diff-and-merging-tool-for-local-files/

How to select Python version in PyCharm?

Go to:

Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter

There you can see which external libraries you have installed for python2 and which for python3.

Select the required python version according to your requirements.

Image

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

Mozila Firefox says that onreadystatechange is an alternative to DOMContentLoaded.

// alternative to DOMContentLoaded
document.onreadystatechange = function () {
    if (document.readyState == "complete") {
        initApplication();
    }
}

In DOMContentLoaded the Mozila's doc says:

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

I think load event should be used for a full document+resources loading.

Finding three elements in an array whose sum is closest to a given number

Note that we have a sorted array. This solution is similar to John's solution only that it looks for the sum and does not repeat the same element.

#include <stdio.h>;

int checkForSum (int arr[], int len, int sum) { //arr is sorted
    int i;
    for (i = 0; i < len ; i++) {
        int left = i + 1;
        int right = len - 1;
        while (right > left) {
            printf ("values are %d %d %d\n", arr[i], arr[left], arr[right]);
            if (arr[right] + arr[left] + arr[i] - sum == 0) {
                printf ("final values are %d %d %d\n", arr[i], arr[left], arr[right]);
                return 1;
            }
            if (arr[right] + arr[left] + arr[i] - sum > 0)
                right--;
            else
                left++;
        }
    }
    return -1;
}
int main (int argc, char **argv) {
    int arr[] = {-99, -45, -6, -5, 0, 9, 12, 16, 21, 29};
    int sum = 4;
    printf ("check for sum %d in arr is %d\n", sum, checkForSum(arr, 10, sum));
}

How to use Fiddler to monitor WCF service

I just tried the first answer from Brad Rem and came to this setting in the web.config under BasicHttpBinding:

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding bypassProxyOnLocal="False" useDefaultWebProxy="false" proxyAddress="http://127.0.0.1:8888" ...
        ...
      </basicHttpBinding>
    </bindings>
    ...
<system.serviceModel>

Hope this helps someone.

Finding diff between current and last version

This will also work for tags (remove the 'uniq' below and other parts if you need to see all changes):

 git diff v1.58 HEAD 

The below is the same, and that could be useful for continuous integration (CI) for microservices in a monolithic repository:

git diff v1.58 HEAD  --name-only | sort -u | awk 'BEGIN {FS="/"} {print $1}' | uniq
<Folder Name> 

(Credit - https://dzone.com/articles/build-test-and-deploy-apps-independently-from-a-mo)

Export pictures from excel file into jpg using VBA

''' Set Range you want to export to the folder

Workbooks("your workbook name").Sheets("yoursheet name").Select

Dim rgExp As Range: Set rgExp = Range("A1:H31")
''' Copy range as picture onto Clipboard
rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
''' Create an empty chart with exact size of range copied
With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
Width:=rgExp.Width, Height:=rgExp.Height)
.Name = "ChartVolumeMetricsDevEXPORT"
.Activate
End With
''' Paste into chart area, export to file, delete chart.
ActiveChart.Paste
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Chart.Export "C:\ExportmyChart.jpg"
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Delete

How can I get client information such as OS and browser

Update: The project is EOL and not maintained anymore. He recommends switching to the Browscap project.

You can use the bitwalker useragentutils library: https://github.com/HaraldWalker/user-agent-utils. It will provide you information about the Browser (name, type, version, manufacturer, etc.) and about the OperatingSystem. A good thing about it is that it is maintained. Access the link that I have provided to see the Maven dependency that you need to add to you project in order to use it.

See below sample code that returns the browser name and browser version.

    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    Browser browser = userAgent.getBrowser();

    String browserName = browser.getName();
    //or 
    // String browserName = browser.getGroup().getName();
    Version browserVersion = userAgent.getBrowserVersion();
    System.out.println("The user is using browser " + browserName + " - version " + browserVersion);

How can I trim beginning and ending double quotes from a string?

public String removeDoubleQuotes(String request) {
    return request.replace("\"", "");
}

Loop inside React JSX

Maybe the standard of today maximum developer, use a structure like this:

 let data = [
  {
    id: 1,
    name: "name1"
  },
  {
    id: 2,
    name: "name2"
  },
  {
    id: 3,
    name: "name3"
  },
  {
    id: 100,
    name: "another name"
  }
];

export const Row = data => {
  return (
    <tr key={data.id}>
      <td>{data.id}</td>
      <td>{data.name}</td>
    </tr>
  );
};

function App() {
  return (
    <table>
      <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>{data.map(item => Row(item))}</tbody>
    </table>
  );
}

In the JSX, write your JavaScript action inside HTML or any code here, {data.map(item => Row(item))}, use single curly braces and inside a map function. Get to know more about map.

And also see the following output here.

Difference between two dates in Python

Use - to get the difference between two datetime objects and take the days member.

from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

Can I nest a <button> element inside an <a> using HTML5?

Explanation and working solution here: Howto: div with onclick inside another div with onclick javascript

by executing this script in your inner click handler:

 if (!e) var e = window.event;
 e.cancelBubble = true;
 if (e.stopPropagation) e.stopPropagation();

CSS transition between left -> right and top -> bottom positions

You can animate the position (top, bottom, left, right) and then subtract the element's width or height through a CSS transformation.

Consider:

_x000D_
_x000D_
$('.animate').on('click', function(){
  $(this).toggleClass("move");
})
_x000D_
     .animate {
        height: 100px;
        width: 100px;
        background-color: #c00;
        transition: all 1s ease;
        position: absolute;
        cursor: pointer;
        font: 13px/100px sans-serif;
        color: white;
        text-align: center;
      }

                               /* ? just to position things  */
      .animate.left   { left: 0;   top: 50%;  margin-top: -100px;}
      .animate.right  { right: 0;  top: 50%;  }
      .animate.top    { top: 0;    left: 50%; }
      .animate.bottom { bottom: 0; left: 50%; margin-left: -100px;}


      .animate.left.move {
        left: 100%; 
        transform: translate(-100%, 0);
      }

      .animate.right.move {
        right: 100%; 
        transform: translate(100%, 0);
      }

      .animate.top.move {
        top: 100%; 
        transform: translate(0, -100%);
      }

      .animate.bottom.move {
        bottom: 100%; 
        transform: translate(0, 100%);
      }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click to animate
<div class="animate left">left</div>
<div class="animate top">top</div>
<div class="animate bottom">bottom</div>
<div class="animate right">right</div>
_x000D_
_x000D_
_x000D_

And then animate depending on the position...

Avoid trailing zeroes in printf()

I found problems in some of the solutions posted. I put this together based on answers above. It seems to work for me.

int doubleEquals(double i, double j) {
    return (fabs(i - j) < 0.000001);
}

void printTruncatedDouble(double dd, int max_len) {
    char str[50];
    int match = 0;
    for ( int ii = 0; ii < max_len; ii++ ) {
        if (doubleEquals(dd * pow(10,ii), floor(dd * pow(10,ii)))) {
            sprintf (str,"%f", round(dd*pow(10,ii))/pow(10,ii));
            match = 1;
            break;
        }
    }
    if ( match != 1 ) {
        sprintf (str,"%f", round(dd*pow(10,max_len))/pow(10,max_len));
    }
    char *pp;
    int count;
    pp = strchr (str,'.');
    if (pp != NULL) {
        count = max_len;
        while (count >= 0) {
             count--;
             if (*pp == '\0')
                 break;
             pp++;
        }
        *pp-- = '\0';
        while (*pp == '0')
            *pp-- = '\0';
        if (*pp == '.') {
            *pp = '\0';
        }
    }
    printf ("%s\n", str);
}

int main(int argc, char **argv)
{
    printTruncatedDouble( -1.999, 2 ); // prints -2
    printTruncatedDouble( -1.006, 2 ); // prints -1.01
    printTruncatedDouble( -1.005, 2 ); // prints -1
    printf("\n");
    printTruncatedDouble( 1.005, 2 ); // prints 1 (should be 1.01?)
    printTruncatedDouble( 1.006, 2 ); // prints 1.01
    printTruncatedDouble( 1.999, 2 ); // prints 2
    printf("\n");
    printTruncatedDouble( -1.999, 3 ); // prints -1.999
    printTruncatedDouble( -1.001, 3 ); // prints -1.001
    printTruncatedDouble( -1.0005, 3 ); // prints -1.001 (shound be -1?)
    printTruncatedDouble( -1.0004, 3 ); // prints -1
    printf("\n");
    printTruncatedDouble( 1.0004, 3 ); // prints 1
    printTruncatedDouble( 1.0005, 3 ); // prints 1.001
    printTruncatedDouble( 1.001, 3 ); // prints 1.001
    printTruncatedDouble( 1.999, 3 ); // prints 1.999
    printf("\n");
    exit(0);
}

Parallel foreach with asynchronous lambda

I've created an extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism

    /// <summary>
    /// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
    /// </summary>
    /// <typeparam name="T">Type of IEnumerable</typeparam>
    /// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
    /// <param name="action">an async <see cref="Action" /> to execute</param>
    /// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
    /// Must be grater than 0</param>
    /// <returns>A Task representing an async operation</returns>
    /// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
    public static async Task ForEachAsyncConcurrent<T>(
        this IEnumerable<T> enumerable,
        Func<T, Task> action,
        int? maxDegreeOfParallelism = null)
    {
        if (maxDegreeOfParallelism.HasValue)
        {
            using (var semaphoreSlim = new SemaphoreSlim(
                maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
            {
                var tasksWithThrottler = new List<Task>();

                foreach (var item in enumerable)
                {
                    // Increment the number of currently running tasks and wait if they are more than limit.
                    await semaphoreSlim.WaitAsync();

                    tasksWithThrottler.Add(Task.Run(async () =>
                    {
                        await action(item).ContinueWith(res =>
                        {
                            // action is completed, so decrement the number of currently running tasks
                            semaphoreSlim.Release();
                        });
                    }));
                }

                // Wait for all tasks to complete.
                await Task.WhenAll(tasksWithThrottler.ToArray());
            }
        }
        else
        {
            await Task.WhenAll(enumerable.Select(item => action(item)));
        }
    }

Sample Usage:

await enumerable.ForEachAsyncConcurrent(
    async item =>
    {
        await SomeAsyncMethod(item);
    },
    5);

Create a root password for PHPMyAdmin

PHPMyAdmin is telling you that your MySQL service is missing a root password. You can change it by accessing the MySQL command line interface. mysqladmin -u root password newpass

http://www.howtoforge.com/setting-changing-resetting-mysql-root-passwords

SQL Server: How to check if CLR is enabled?

select *
from sys.configurations
where name = 'clr enabled'

bash assign default value

Use a colon:

: ${A:=hello}

The colon is a null command that does nothing and ignores its arguments. It is built into bash so a new process is not created.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Remove a file from the list that will be committed

if you have already pushed your commit then. do

git checkout origin/<remote-branch> <filename>
git commit --amend

AND If you have not pushed the changes on the server you can use

git reset --soft HEAD~1

How do you use a variable in a regular expression?

And the coffeescript version of Steven Penny's answer, since this is #2 google result....even if coffee is just javascript with a lot of characters removed...;)

baz = "foo"
filter = new RegExp(baz + "d")
"food fight".match(filter)[0] // food

and in my particular case

robot.name=hubot
filter = new RegExp(robot.name)
if msg.match.input.match(filter)
  console.log "True!"

Understanding string reversal via slicing

I would do it like this:

variable = "string"
message = ""
for b in variable:
    message = b+message
print (message)

and it prints: gnirts

How can I style even and odd elements?

 <ul class="names" id="names_list">
          <a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="1">Ashwin Nair</li></a>
           <a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="2">Anil Reddy</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="3">Chirag</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="4">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="15">Ashwin</li></a>
            <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="16">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="17">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="18">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="19">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="188">Anil Reddy</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="111">Bhavesh</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="122">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="133">Ashwin</li></a>
            <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="144">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="199">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="156">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="174">Ashwin</li></a>

         </ul>    
$(document).ready(function(){
      var a=0;
      var ac;
      var ac2;
        $(".names li").click(function(){
           var b=0;
            if(a==0)
            {
              var accc="#"+ac2;
     if(ac=='part2')
     {
    $(accc).css({

    "background": "#322f28",
    "color":"#fff",
    });
     }
     if(ac=='part1')
     {

      $(accc).css({

      "background": "#3e3b34",
      "color":"#fff",
    });
     }

              $(this).css({
                "background":"#d3b730",
                "color":"#000",
            });
              ac=$(this).attr('class');
              ac2=$(this).attr('id');
    a=1;
            }
            else{

    var accc="#"+ac2;
    //alert(accc);
     if(ac=='part2')
     {
    $(accc).css({

    "background": "#322f28",
    "color":"#fff",
    });
     }
     if(ac=='part1')
     {

      $(accc).css({

      "background": "#3e3b34",
      "color":"#fff",
    });
     }

     a=0;
    ac=$(this).attr('class');
    ac2=$(this).attr('id');
    $(this).css({
                "background":"#d3b730",
                "color":"#000",
            });

            }

        });

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

How to create an empty file with Ansible?

Something like this (using the stat module first to gather data about it and then filtering using a conditional) should work:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
  when: p.stat.exists is defined and not p.stat.exists

You might alternatively be able to leverage the changed_when functionality.

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

Parse HTML table to Python list?

You should use some HTML parsing library like lxml:

from lxml import etree
s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print dict(zip(headers, values))

prints

{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}

How to change the text of a button in jQuery?

document.getElementById('btnAddProfile').value='Save';

Java: using switch statement with enum under subclass

Wrong:

case AnotherClass.MyEnum.VALUE_A

Right:

case VALUE_A:

Create dataframe from a matrix

You can use stack from the base package. But, you need first to coerce your matrix to a data.frame and to reorder the columns once the data is stacked.

mat <- as.data.frame(mat)
res <- data.frame(time= mat$time,stack(mat,select=-time))
res[,c(3,1,2)]

  ind time values
1 C_0  0.0    0.1
2 C_0  0.5    0.2
3 C_0  1.0    0.3
4 C_1  0.0    0.3
5 C_1  0.5    0.4
6 C_1  1.0    0.5

Note that stack is generally more efficient than the reshape2 package.

Convert an array into an ArrayList

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

How do you get the current time of day?

DateTime.Now.TimeOfDay gives it to you as a TimeSpan (from midnight).

DateTime.Now.ToString("h:mm:ss tt") gives it to you as a string.

DateTime reference: https://msdn.microsoft.com/en-us/library/system.datetime

Set "Homepage" in Asp.Net MVC

Attribute Routing in MVC 5

Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...) in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index). However if you modify the default route as shown below,

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController and an action method inside of it called DoSomething, then the expected default url ExampleController/DoSomething will no longer work because the default route was changed.

A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
    name: "Example",
    url: "hey/now",
    defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);

Now the DoSomething action of the ExampleController class will be mapped to the url hey/now. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,

public class HomeController : Controller
{
    // url is now 'index/' instead of 'home/index'
    [Route("index")]
    public ActionResult Index()
    {
        return View();
    }
    // url is now 'create/new' instead of 'home/create'
    [Route("create/new")]
    public ActionResult Create()
    {
        return View();
    }
}

ComboBox.SelectedText doesn't give me the SelectedText

I think you want to use

String status = "The status of my combobox is " + comboBoxTest.Text

SelectedText property from MSDN

Gets or sets the text that is selected in the editable portion of a ComboBox.

while Text property from MSDN

Gets or sets the text associated with this control.

Stop on first error

Maybe you want set -e:

www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:

This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.

Using :before CSS pseudo element to add image to modal

http://caniuse.com/#search=::after

::after and ::before with content are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.

Is this what you're looking for?

.Modal::after{
  content:url('blackCarrot.png'); /* with class ModalCarrot ??*/
  position:relative; /*or absolute*/
  z-index:100000; /*a number that's more than the modal box*/
  left:-50px;
  top:10px;
}

.ModalCarrot{
   position:absolute;
   left:50%;
   margin-left:-8px;
   top:-16px;
}

If not, can you explain a little better?

or you could use jQuery, like Joshua said:

$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");

Execute raw SQL using Doctrine 2

I got it to work by doing this, assuming you are using PDO.

//Place query here, let's say you want all the users that have blue as their favorite color
$sql = "SELECT name FROM user WHERE favorite_color = :color";

//set parameters 
//you may set as many parameters as you have on your query
$params['color'] = blue;


//create the prepared statement, by getting the doctrine connection
$stmt = $this->entityManager->getConnection()->prepare($sql);
$stmt->execute($params);
//I used FETCH_COLUMN because I only needed one Column.
return $stmt->fetchAll(PDO::FETCH_COLUMN);

You can change the FETCH_TYPE to suit your needs.

Concatenating two one-dimensional NumPy arrays

Here are more approaches for doing this by using numpy.ravel(), numpy.array(), utilizing the fact that 1D arrays can be unpacked into plain elements:

# we'll utilize the concept of unpacking
In [15]: (*a, *b)
Out[15]: (1, 2, 3, 5, 6)

# using `numpy.ravel()`
In [14]: np.ravel((*a, *b))
Out[14]: array([1, 2, 3, 5, 6])

# wrap the unpacked elements in `numpy.array()`
In [16]: np.array((*a, *b))
Out[16]: array([1, 2, 3, 5, 6])

MySQL selecting yesterday's date

SELECT SUBDATE(NOW(),1);

where now() function returs current date and time of system in Timestamp...

you can use:

SELECT SUBDATE(CURDATE(),1)

Limit number of characters allowed in form input text field

<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);"  placeholder="MobileNumber">

<script>
function checkNumber(key) {
  console.log(key);
  var inputNumber = document.querySelector("#MobileNumber").value;
  if(key.key >= 0 && key.key <= 9) {
    inputNumber += key.key;
  }
  else {
    key.preventDefault();
  }
}
</script>

javascript pushing element at the beginning of an array

Use .unshift() to add to the beginning of an array.

TheArray.unshift(TheNewObject);

See MDN for doc on unshift() and here for doc on other array methods.

FYI, just like there's .push() and .pop() for the end of the array, there's .shift() and .unshift() for the beginning of the array.

Why doesn't importing java.util.* include Arrays and Lists?

I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.

Have you tried compiling from the command line?

I have the exact same version:

here it is

Probably you're thinking the warning is an error.

UPDATE

It looks like you have a Arrays.class file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class

How do I wrap text in a pre tag?

Use white-space: pre-wrap and some prefixes for automatic line breaking inside pres.

Do not use word-wrap: break-word because this just, of course, breaks a word in half which is probably something you do not want.

Taking pictures with camera on Android programmatically

You can use Magical Take Photo library.

1. try with compile in gradle

compile 'com.frosquivel:magicaltakephoto:1.0'

2. You need this permission in your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>

3. instance the class like this

// "this" is the current activity param

MagicalTakePhoto magicalTakePhoto =  new MagicalTakePhoto(this,ANY_INTEGER_0_TO_4000_FOR_QUALITY);

4. if you need to take picture use the method

magicalTakePhoto.takePhoto("my_photo_name");

5. if you need to select picture in device, try with the method:

magicalTakePhoto.selectedPicture("my_header_name");

6. You need to override the method onActivityResult of the activity or fragment like this:

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

     // example to get photo
     // imageView.setImageBitmap(magicalTakePhoto.getMyPhoto());
}

Note: Only with this Library you can take and select picture in the device, this use a min API 15.

Reload parent window from child window

parent.location.reload();

This should work.

Using .text() to retrieve only text not nested in child tags

jQuery.fn.ownText = function () {
    return $(this).contents().filter(function () {
        return this.nodeType === Node.TEXT_NODE;
    }).text();
};

How to filter a RecyclerView with a SearchView

This is my take on expanding @klimat answer to not losing filtering animation.

public void filter(String query){
    int completeListIndex = 0;
    int filteredListIndex = 0;
    while (completeListIndex < completeList.size()){
        Movie item = completeList.get(completeListIndex);
        if(item.getName().toLowerCase().contains(query)){
            if(filteredListIndex < filteredList.size()) {
                Movie filter = filteredList.get(filteredListIndex);
                if (!item.getName().equals(filter.getName())) {
                    filteredList.add(filteredListIndex, item);
                    notifyItemInserted(filteredListIndex);
                }
            }else{
                filteredList.add(filteredListIndex, item);
                notifyItemInserted(filteredListIndex);
            }
            filteredListIndex++;
        }
        else if(filteredListIndex < filteredList.size()){
            Movie filter = filteredList.get(filteredListIndex);
            if (item.getName().equals(filter.getName())) {
                filteredList.remove(filteredListIndex);
                notifyItemRemoved(filteredListIndex);
            }
        }
        completeListIndex++;
    }
}

Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.

git stash -> merge stashed change with current changes

What I want is a way to merge my stashed changes with the current changes

Here is another option to do it:

git stash show -p|git apply
git stash drop

git stash show -p will show the patch of last saved stash. git apply will apply it. After the merge is done, merged stash can be dropped with git stash drop.

Is there a way to suppress JSHint warning for one given line?

As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

/*jshint evil:true */

function helloEval(str) {
    /*jshint evil:true */
    eval(str);
}

Create a GUID in Java

This answer contains 2 generators for random-based and name-based UUIDs, compliant with RFC-4122. Feel free to use and share.

RANDOM-BASED (v4)

This utility class that generates random-based UUIDs:

package your.package.name;

import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;

/**
 * Utility class that creates random-based UUIDs.
 * 
 */
public abstract class RandomUuidCreator {

    private static final int RANDOM_VERSION = 4;

    /**
     * Returns a random-based UUID.
     * 
     * It uses a thread local {@link SecureRandom}.
     * 
     * @return a random-based UUID
     */
    public static UUID getRandomUuid() {
        return getRandomUuid(SecureRandomLazyHolder.THREAD_LOCAL_RANDOM.get());
    }

    /**
     * Returns a random-based UUID.
     * 
     * It uses any instance of {@link Random}.
     * 
     * @return a random-based UUID
     */
    public static UUID getRandomUuid(Random random) {

        long msb = 0;
        long lsb = 0;

        // (3) set all bit randomly
        if (random instanceof SecureRandom) {
            // Faster for instances of SecureRandom
            final byte[] bytes = new byte[16];
            random.nextBytes(bytes);
            msb = toNumber(bytes, 0, 8); // first 8 bytes for MSB
            lsb = toNumber(bytes, 8, 16); // last 8 bytes for LSB
        } else {
            msb = random.nextLong(); // first 8 bytes for MSB
            lsb = random.nextLong(); // last 8 bytes for LSB
        }

        // Apply version and variant bits (required for RFC-4122 compliance)
        msb = (msb & 0xffffffffffff0fffL) | (RANDOM_VERSION & 0x0f) << 12; // apply version bits
        lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits

        // Return the UUID
        return new UUID(msb, lsb);
    }

    private static long toNumber(final byte[] bytes, final int start, final int length) {
        long result = 0;
        for (int i = start; i < length; i++) {
            result = (result << 8) | (bytes[i] & 0xff);
        }
        return result;
    }

    // Holds thread local secure random
    private static class SecureRandomLazyHolder {
        static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = ThreadLocal.withInitial(SecureRandom::new);
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        System.out.println("// Using thread local `java.security.SecureRandom` (DEFAULT)");
        System.out.println("RandomUuidCreator.getRandomUuid()");
        System.out.println();
        for (int i = 0; i < 5; i++) {
            System.out.println(RandomUuidCreator.getRandomUuid());
        }

        System.out.println();
        System.out.println("// Using `java.util.Random` (FASTER)");
        System.out.println("RandomUuidCreator.getRandomUuid(new Random())");
        System.out.println();
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            System.out.println(RandomUuidCreator.getRandomUuid(random));
        }
    }
}

This is the output:

// Using thread local `java.security.SecureRandom` (DEFAULT)
RandomUuidCreator.getRandomUuid()

'ef4f5ad2-8147-46cb-8389-c2b8c3ef6b10'
'adc0305a-df29-4f08-9d73-800fde2048f0'
'4b794b59-bff8-4013-b656-5d34c33f4ce3'
'22517093-ee24-4120-96a5-ecee943992d1'
'899fb1fb-3e3d-4026-85a8-8a2d274a10cb'

// Using `java.util.Random` (FASTER)
RandomUuidCreator.getRandomUuid(new Random())

'4dabbbc2-fcb2-4074-a91c-5e2977a5bbf8'
'078ec231-88bc-4d74-9774-96c0b820ceda'
'726638fa-69a6-4a18-b09f-5fd2a708059b'
'15616ebe-1dfd-4f5c-b2ed-cea0ac1ad823'
'affa31ad-5e55-4cde-8232-cddd4931923a'

NAME-BASED (v3 and v5)

This utility class that generates name-based UUIDs (MD5 and SHA1):

package your.package.name;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * Utility class that creates UUIDv3 (MD5) and UUIDv5 (SHA1).
 *
 */
public class HashUuidCreator {

    // Domain Name System
    public static final UUID NAMESPACE_DNS = new UUID(0x6ba7b8109dad11d1L, 0x80b400c04fd430c8L);
    // Uniform Resource Locator
    public static final UUID NAMESPACE_URL = new UUID(0x6ba7b8119dad11d1L, 0x80b400c04fd430c8L);
    // ISO Object ID
    public static final UUID NAMESPACE_ISO_OID = new UUID(0x6ba7b8129dad11d1L, 0x80b400c04fd430c8L);
    // X.500 Distinguished Name
    public static final UUID NAMESPACE_X500_DN = new UUID(0x6ba7b8149dad11d1L, 0x80b400c04fd430c8L);

    private static final int VERSION_3 = 3; // UUIDv3 MD5
    private static final int VERSION_5 = 5; // UUIDv5 SHA1

    private static final String MESSAGE_DIGEST_MD5 = "MD5"; // UUIDv3
    private static final String MESSAGE_DIGEST_SHA1 = "SHA-1"; // UUIDv5

    private static UUID getHashUuid(UUID namespace, String name, String algorithm, int version) {

        final byte[] hash;
        final MessageDigest hasher;

        try {
            // Instantiate a message digest for the chosen algorithm
            hasher = MessageDigest.getInstance(algorithm);

            // Insert name space if NOT NULL
            if (namespace != null) {
                hasher.update(toBytes(namespace.getMostSignificantBits()));
                hasher.update(toBytes(namespace.getLeastSignificantBits()));
            }

            // Generate the hash
            hash = hasher.digest(name.getBytes(StandardCharsets.UTF_8));

            // Split the hash into two parts: MSB and LSB
            long msb = toNumber(hash, 0, 8); // first 8 bytes for MSB
            long lsb = toNumber(hash, 8, 16); // last 8 bytes for LSB

            // Apply version and variant bits (required for RFC-4122 compliance)
            msb = (msb & 0xffffffffffff0fffL) | (version & 0x0f) << 12; // apply version bits
            lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits

            // Return the UUID
            return new UUID(msb, lsb);

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Message digest algorithm not supported.");
        }
    }

    public static UUID getMd5Uuid(String string) {
        return getHashUuid(null, string, MESSAGE_DIGEST_MD5, VERSION_3);
    }

    public static UUID getSha1Uuid(String string) {
        return getHashUuid(null, string, MESSAGE_DIGEST_SHA1, VERSION_5);
    }

    public static UUID getMd5Uuid(UUID namespace, String string) {
        return getHashUuid(namespace, string, MESSAGE_DIGEST_MD5, VERSION_3);
    }

    public static UUID getSha1Uuid(UUID namespace, String string) {
        return getHashUuid(namespace, string, MESSAGE_DIGEST_SHA1, VERSION_5);
    }

    private static byte[] toBytes(final long number) {
        return new byte[] { (byte) (number >>> 56), (byte) (number >>> 48), (byte) (number >>> 40),
                (byte) (number >>> 32), (byte) (number >>> 24), (byte) (number >>> 16), (byte) (number >>> 8),
                (byte) (number) };
    }

    private static long toNumber(final byte[] bytes, final int start, final int length) {
        long result = 0;
        for (int i = start; i < length; i++) {
            result = (result << 8) | (bytes[i] & 0xff);
        }
        return result;
    }

    /**
     * For tests!
     */
    public static void main(String[] args) {

        String string = "JUST_A_TEST_STRING";
        UUID namespace = UUID.randomUUID(); // A custom name space

        System.out.println("Java's generator");
        System.out.println("UUID.nameUUIDFromBytes():      '" + UUID.nameUUIDFromBytes(string.getBytes()) + "'");
        System.out.println();
        System.out.println("This generator");
        System.out.println("HashUuidCreator.getMd5Uuid():  '" + HashUuidCreator.getMd5Uuid(string) + "'");
        System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(string) + "'");
        System.out.println();
        System.out.println("This generator WITH name space");
        System.out.println("HashUuidCreator.getMd5Uuid():  '" + HashUuidCreator.getMd5Uuid(namespace, string) + "'");
        System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(namespace, string) + "'");
    }
}

This is the output:

// Java's generator
UUID.nameUUIDFromBytes():      '9e120341-627f-32be-8393-58b5d655b751'

// This generator
HashUuidCreator.getMd5Uuid():  '9e120341-627f-32be-8393-58b5d655b751'
HashUuidCreator.getSha1Uuid(): 'e4586bed-032a-5ae6-9883-331cd94c4ffa'

// This generator WITH name space
HashUuidCreator.getMd5Uuid():  '2b098683-03c9-3ed8-9426-cf5c81ab1f9f'
HashUuidCreator.getSha1Uuid(): '1ef568c7-726b-58cc-a72a-7df173463bbb'

ALTERNATE GENERATOR

You can also use the uuid-creator library. See these examples:

// Create a random-based UUID
UUID uuid = UuidCreator.getRandomBased();
// Create a name based UUID (SHA1)
String name = "JUST_A_TEST_STRING";
UUID uuid = UuidCreator.getNameBasedSha1(name);

Project page: https://github.com/f4b6a3/uuid-creator

Javascript Date: next month

If you use moment.js, they have an add function. Here's the link - https://momentjs.com/docs/#/manipulating/add/

moment().add(7, 'months');

I also wrote a recursive function based on paxdiablo's answer to add a variable number of months. By default this function would add a month to the current date.

function addMonths(after = 1, now = new Date()) {
        var current;
        if (now.getMonth() == 11) {
            current = new Date(now.getFullYear() + 1, 0, 1);
        } else {
            current = new Date(now.getFullYear(), now.getMonth() + 1, 1);            
        }
        return (after == 1) ? current : addMonths(after - 1, new Date(now.getFullYear(), now.getMonth() + 1, 1))
    }

Example

console.log('Add 3 months to November', addMonths(3, new Date(2017, 10, 27)))

Output -

Add 3 months to November Thu Feb 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)

How do I get the total Json record count using JQuery?

What you're looking for is

j.d.length

The d is the key. At least it is in my case, I'm using a .NET webservice.

 $.ajax({
            type: "POST",
            url: "CantTellU.asmx",
            data: "{'userID' : " + parseInt($.query.get('ID')) + " }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg, status) {
                ApplyTemplate(msg);
                alert(msg.d.length);
            }
        });

Adding an image to a PDF using iTextSharp and scale it properly

I solved it using the following:

foreach (var image in images)
{
    iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);

    if (pic.Height > pic.Width)
    {
        //Maximum height is 800 pixels.
        float percentage = 0.0f;
        percentage = 700 / pic.Height;
        pic.ScalePercent(percentage * 100);
    }
    else
    {
        //Maximum width is 600 pixels.
        float percentage = 0.0f;
        percentage = 540 / pic.Width;
        pic.ScalePercent(percentage * 100);
    }

    pic.Border = iTextSharp.text.Rectangle.BOX;
    pic.BorderColor = iTextSharp.text.BaseColor.BLACK;
    pic.BorderWidth = 3f;
    document.Add(pic);
    document.NewPage();
}

How to declare a inline object with inline variables without a parent class

yes, there is:

object[] x = new object[2];

x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };

you were practically there, just the declaration of the anonymous types was a little off.

How can I get selector from jQuery object

Taking in account some answers read here I'd like to propose this:

function getSelectorFromElement($el) {
  if (!$el || !$el.length) {
    return ;
  }

  function _getChildSelector(index) {
    if (typeof index === 'undefined') {
      return '';
    }

    index = index + 1;
    return ':nth-child(' + index + ')';
  }

  function _getIdAndClassNames($el) {
    var selector = '';

    // attach id if exists
    var elId = $el.attr('id');
    if(elId){
      selector += '#' + elId;
    }

    // attach class names if exists
    var classNames = $el.attr('class');
    if(classNames){
      selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
    }

    return selector;
  }

  // get all parents siblings index and element's tag name,
  // except html and body elements
  var selector = $el.parents(':not(html,body)')
    .map(function() {
      var parentIndex = $(this).index();

      return this.tagName + _getChildSelector(parentIndex);
    })
    .get()
    .reverse()
    .join(' ');

  if (selector) {
    // get node name from the element itself
    selector += ' ' + $el[0].nodeName +
      // get child selector from element ifself
      _getChildSelector($el.index());
  }

  selector += _getIdAndClassNames($el);

  return selector;
}

Maybe useful to create a jQuery plugin?

regex with space and letters only?

Try this demo please: http://jsfiddle.net/sgpw2/

Thanks Jan for spaces \s rest there is some good detail in this link:

http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI

Hope it fits your need :)

code

 $(function() {

    $("#field").bind("keyup", function(event) {
        var regex = /^[a-zA-Z\s]+$/;
        if (regex.test($("#field").val())) {
            $('.validation').html('valid');
        } else {
            $('.validation').html("FAIL regex");
        }
    });
});?

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

Toad for Oracle..How to execute multiple statements?

begin

insert into fiscal_year values(2001,'01-jan-2001','31-dec-2001');
insert into fiscal_year values(2002,'01-jan-2002','31-dec-2002');
insert into fiscal_year values(2003,'01-jan-2003','31-dec-2003');
insert into fiscal_year values(2004,'01-jan-2004','31-dec-2004');

end;

Use like this and then commit.

Calculate text width with JavaScript

The width and heigth of a text can be obtained with clientWidth and clientHeight

var element = document.getElementById ("mytext");

var width = element.clientWidth;
var height = element.clientHeight;

make sure that style position property is set to absolute

element.style.position = "absolute";

not required to be inside a div, can be inside a p or a span

How to simulate a button click using code?

you can do it this way

private Button btn;
btn = (Button)findViewById(R.id.button2);
btn.performClick();