Programs & Examples On #Error detection

jQuery UI autocomplete with item and id

From the Overview tab of jQuery autocomplete plugin:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

So your "two-dimensional" array could look like:

var $local_source = [{
    value: 1,
    label: "c++"
}, {
    value: 2,
    label: "java"
}, {
    value: 3,
    label: "php"
}, {
    value: 4,
    label: "coldfusion"
}, {
    value: 5,
    label: "javascript"
}, {
    value: 6,
    label: "asp"
}, {
    value: 7,
    label: "ruby"
}];

You can access the label and value properties inside focus and select event through the ui argument using ui.item.label and ui.item.value.

Edit

Seems like you have to "cancel" the focus and select events so that it does not place the id numbers inside the text boxes. While doing so you can copy the value in a hidden variable instead. Here is an example.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

it's not exact output that you wanted but maybe something like this will do. Parent cmp:

<table>
  <item *ngFor="#i of items" [data]="i"></item>
</table>

Child cmp

import {Component} from 'angular2/core';

@Component({
  selector: `item`,
  inputs: ['data'],
  template: `
    <tr><td>{{data.name}}</td></tr>
    <tr *ngFor="#i of data.items">
      <td><h1>{{i}}</h1></td>
    </tr>
  `
})
export default class Item {


}

Changing an AIX password via script?

You can try:

echo "USERNAME:NEWPASSWORD" | chpasswd

Margin on child element moves parent element

Neat CSS-only solution

Use the following code to prepend a contentless first-child to the unintentionally moving div:

.parent:before
{content: '';position: relative;height: 0px;width: 0px;overflow: hidden;white-space: pre;}

The advantage of this method is that you do not need to change the CSS of any existing element, and therefore has minimal impact on design. Next to this, the element that is added is a pseudo-element, which is not in the DOM-tree.

Support for pseudo-elements is wide-spread: Firefox 3+, Safari 3+, Chrome 3+, Opera 10+, and IE 8+. This will work in any modern browser (be careful with the newer ::before, which is not supported in IE8).

Context

If the first child of an element has a margin-top, the parent will adjust its position as a way of collapsing redundant margins. Why? It's just like that.

Given the following problem:

<style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}
</style>

<div class="parent"><!--This div moves 40px too-->
    <div class="child">Hello world!</div>
</div>

You can fix it by adding a child with content, such as a simple space. But we all hate to add spaces for what is a design-only issue. Therefore, use the white-space property to fake content.

<style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}
.fix {position: relative;white-space: pre;height: 0px;width: 0px;overflow: hidden;}
</style>

<div class="parent"><!--This div won't move anymore-->
    <div class="fix"></div>
    <div class="child">Hello world!</div>
</div>

Where position: relative; ensures correct positioning of the fix. And white-space: pre; makes you not having to add any content - like a white space - to the fix. And height: 0px;width: 0px;overflow: hidden; makes sure you'll never see the fix.

You might need to add line-height: 0px; or max-height: 0px; to ensure the height is actually zero in ancient IE browsers (I'm unsure). And optionally you could add <!--dummy--> to it in old IE browsers, if it does not work.

In short, you can do all this with only CSS (which removes the need to add an actual child to the HTML DOM-tree):

<style type="text/css">
div {position: relative;}
.parent {background-color: #ccc;}
.child {margin-top: 40px;}

.parent:before {content: '';position: relative;height: 0px;width: 0px;overflow: hidden;white-space: pre;}
</style>

<div class="parent"><!--This div won't move anymore-->
    <div class="child">Hello world!</div>
</div>

Why is AJAX returning HTTP status code 0?

Because this shows up when you google ajax status 0 I wanted to leave some tip that just took me hours of wasted time... I was using ajax to call a PHP service which happened to be Phil's REST_Controller for Codeigniter (not sure if this has anything to do with it or not) and kept getting status 0, readystate 0 and it was driving me nuts. I was debugging it and noticed when I would echo and return instead of exit the message I'd get a success. Finally I turned debugging off and tried and it worked. Seems the xDebug debugger with PHP was somehow modifying the response. If your using a PHP debugger try turning it off to see if that helps.

How to debug Spring Boot application with Eclipse?

Why don't you just right click on the main() method and choose "Debug As... Java Application"?

Can I target all <H> tags with a single selector?

The jQuery selector for all h tags (h1, h2 etc) is " :header ". For example, if you wanted to make all h tags red in color with jQuery, use:

_x000D_
_x000D_
$(':header').css("color","red")
_x000D_
_x000D_
_x000D_

Has an event handler already been added?

I recently came to a similar situation where I needed to register a handler for an event only once. I found that you can safely unregister first, and then register again, even if the handler is not registered at all:

myClass.MyEvent -= MyHandler;
myClass.MyEvent += MyHandler;

Note that doing this every time you register your handler will ensure that your handler is registered only once. Sounds like a pretty good practice to me :)

How do I format axis number format to thousands with a comma in matplotlib?

You can use matplotlib.ticker.funcformatter

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


def func(x, pos):  # formatter function takes tick label and tick position
    s = '%d' % x
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()

enter image description here

Set max-height on inner div so scroll bars appear, but not on parent div

It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:

function SetHeight(){
    var h = $(window).height();
    $("#inner-right").height(h-200);    
}

$(document).ready(SetHeight);
$(window).resize(SetHeight);

Android Studio drawable folders

If you don't see a drawable folder for the DPI that you need, you can create it yourself. There's nothing magical about it; it's just a folder which needs to have the correct name.

AssertionError: View function mapping is overwriting an existing endpoint function: main

There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised.

See https://github.com/mitsuhiko/flask/issues/796

So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version.

The diff of that change is here: http://github.com/mitsuhiko/flask/commit/661ee54bc2bc1ea0763ac9c226f8e14bb0beb5b1

PHP: HTML: send HTML select option attribute in POST

You will have to use JavaScript. The browser will only send the value of the selected option (so its not PHP's fault).

What your JS should do is hook into the form's submit event and create a hidden field with the value of the selected option's stud_name value. This hidden field will then get sent to the server.

That being said ... you shouldn't relay on the client to provide the correct data. You already know what stud_name should be for a given value on the server (since you are outputting it). So just apply the same logic when you are processing the form.

incompatible character encodings: ASCII-8BIT and UTF-8

I solved it by following these steps:

  • Make sure config.encoding = "utf-8" is in the application.rb file.
  • Make sure you are using the 'mysql2' gem.
  • Put # encoding: utf-8 at the top of file containing UTF-8 characters.
  • Above the <App Name>::Application.initialize! line in the environment.rb file, add following two lines:

    Encoding.default_external = Encoding::UTF_8
    Encoding.default_internal = Encoding::UTF_8
    

http://rorguide.blogspot.com/2011/06/incompatible-character-encodings-ascii.html

PostgreSQL: Show tables in PostgreSQL

  1. In PostgreSQL command-line interface after login, type the following command to connect with the desired database.

        \c [database_name]
    

Then you will see this message You are now connected to database "[database_name]"

  1. Type the following command to list all the tables.

        \dt
    

MySQL stored procedure vs function, which would I use when?

A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.

A procedure is executed using the CALL query.

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

How to add a new column to a CSV file?

For adding a new column to an existing CSV file(with headers), if the column to be added has small enough number of values, here is a convenient function (somewhat similar to @joaquin's solution). The function takes the

  1. Existing CSV filename
  2. Output CSV filename (which will have the updated content) and
  3. List with header name&column values
def add_col_to_csv(csvfile,fileout,new_list):
    with open(csvfile, 'r') as read_f, \
        open(fileout, 'w', newline='') as write_f:
        csv_reader = csv.reader(read_f)
        csv_writer = csv.writer(write_f)
        i = 0
        for row in csv_reader:
            row.append(new_list[i])
            csv_writer.writerow(row)
            i += 1 

Example:

new_list1 = ['test_hdr',4,4,5,5,9,9,9]
add_col_to_csv('exists.csv','new-output.csv',new_list1)

Existing CSV file: enter image description here

Output(updated) CSV file: enter image description here

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

How to Automatically Close Alerts using Twitter Bootstrap

With each of the solutions above I continued to lose re-usability of the alert. My solution was as follows:

On page load

$("#success-alert").hide();

Once the alert needed to be displayed

 $("#success-alert").show();
 window.setTimeout(function () {
     $("#success-alert").slideUp(500, function () {
          $("#success-alert").hide();
      });
 }, 5000);

Note that fadeTo sets the opacity to 0, so the display was none and the opacity was 0 which is why I removed from my solution.

JQuery confirm dialog

Try this one

$('<div></div>').appendTo('body')
  .html('<div><h6>Yes or No?</h6></div>')
  .dialog({
      modal: true, title: 'message', zIndex: 10000, autoOpen: true,
      width: 'auto', resizable: false,
      buttons: {
          Yes: function () {
              doFunctionForYes();
              $(this).dialog("close");
          },
          No: function () {
              doFunctionForNo();
              $(this).dialog("close");
          }
      },
      close: function (event, ui) {
          $(this).remove();
      }
});

Fiddle

Insert line break in wrapped cell via code

Yes there are two way to add a line feed:

  1. Use the existing function from VBA vbCrLf in the string you want to add a line feed, as such:

    Dim text As String

    text = "Hello" & vbCrLf & "World!"

    Worksheets(1).Cells(1, 1) = text

  2. Use the Chr() function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:

    Dim text As String

    text = "Hello" & Chr(13) & Chr(10) & "World!"

    Worksheets(1).Cells(1, 1) = text

In both cases, you will have the same output in cell (1,1) or A1.

Query to list all stored procedures

Try this codeplex link, this utility help to localize all stored procedure from sql database.

https://exportmssqlproc.codeplex.com/

Executing periodic actions in Python

You can execute your task in a different thread. threading.Timer will let you execute a given callback once after some time has elapsed, if you want to execute your task, for example, as long as the callback returns True (this is actually what glib.timeout_add provides, but you might not have it installed in windows) or until you cancel it, you can use this code:

import logging, threading, functools
import time

logging.basicConfig(level=logging.NOTSET,
                    format='%(threadName)s %(message)s')

class PeriodicTimer(object):
    def __init__(self, interval, callback):
        self.interval = interval

        @functools.wraps(callback)
        def wrapper(*args, **kwargs):
            result = callback(*args, **kwargs)
            if result:
                self.thread = threading.Timer(self.interval,
                                              self.callback)
                self.thread.start()

        self.callback = wrapper

    def start(self):
        self.thread = threading.Timer(self.interval, self.callback)
        self.thread.start()

    def cancel(self):
        self.thread.cancel()


def foo():
    logging.info('Doing some work...')
    return True

timer = PeriodicTimer(1, foo)
timer.start()

for i in range(2):
    time.sleep(2)
    logging.info('Doing some other work...')

timer.cancel()

Example output:

Thread-1 Doing some work...
Thread-2 Doing some work...
MainThread Doing some other work...
Thread-3 Doing some work...
Thread-4 Doing some work...
MainThread Doing some other work...

Note: The callback isn't executed every interval execution. Interval is the time the thread waits between the callback finished the last time and the next time is called.

Select top 2 rows in Hive

Here I think it's worth mentioning SORT BY and ORDER BY both clauses and why they different,

SELECT * FROM <table_name> SORT BY <column_name> DESC LIMIT 2

If you are using SORT BY clause it sort data per reducer which means if you have more than one MapReduce task it will result partially ordered data. On the other hand, the ORDER BY clause will result in ordered data for the final Reduce task. To understand more please refer to this link.

SELECT * FROM <table_name> ORDER BY <column_name> DESC LIMIT 2

Note: Finally, Even though the accepted answer contains SORT BY clause, I mostly prefer to use ORDER BY clause for the general use case to avoid any data loss.

Trigger css hover with JS

If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().

What are you trying to accomplish?

Read text file into string array (and write)

Note: ioutil is deprecated as of Go 1.16.

If the file isn't too large, this can be done with the ioutil.ReadFile and strings.Split functions like so:

content, err := ioutil.ReadFile(filename)
if err != nil {
    //Do something
}
lines := strings.Split(string(content), "\n")

You can read the documentation on ioutil and strings packages.

Best programming based games

http://www.pythonchallenge.com/

highly addictive, and a great way to learn python

MySQL - UPDATE multiple rows with different values in one query

I did it this way:

<update id="updateSettings" parameterType="PushSettings">
    <foreach collection="settings" item="setting">
        UPDATE push_setting SET status = #{setting.status}
        WHERE type = #{setting.type} AND user_id = #{userId};
    </foreach>
</update>

where PushSettings is

public class PushSettings {

    private List<PushSetting> settings;
    private String userId;
}

it works fine

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

How do I kill a process using Vb.NET or C#?

You can bypass the security concerns, and create a much politer application by simply checking if the Word process is running, and asking the user to close it, then click a 'Continue' button in your app. This is the approach taken by many installers.

private bool isWordRunning() 
{
    return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0;
}

Of course, you can only do this if your app has a GUI

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

For this particular relationship, you could use np.sign:

>>> df["C"] = np.sign(df.A - df.B)
>>> df
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

WAMP server, localhost is not working

If you have skype installed, close it completely.

If you have sql server installed, go to:

Control panel -> Administrative Tools -> Services

And stop SQL Server Reporting Services

Port 80 must be free now. Click on Wamp icon -> Restart All Services

CSS Transition doesn't work with top, bottom, left, right

I ran into this issue today. Here is my hacky solution.

I needed a fixed position element to transition up by 100 pixels as it loaded.

var delay = (ms) => new Promise(res => setTimeout(res, ms));
async function animateView(startPosition,elm){
  for(var i=0; i<101; i++){
    elm.style.top = `${(startPosition-i)}px`;
    await delay(1);
  }
}

How to sum up elements of a C++ vector?

It is easy. C++11 provides an easy way to sum up elements of a vector.

sum = 0; 
vector<int> vec = {1,2,3,4,5,....}
for(auto i:vec) 
   sum+=i;
cout<<" The sum is :: "<<sum<<endl; 

Reference member variables as class members

Is there a name to describe this idiom?

In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.

I am assuming it is to prevent the possibly large overhead of copying a big complex object?

No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const, then the class can change the state of an object that lives outside of it.

Is this generally good practice? Are there any pitfalls to this approach?

It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.

How to replace substrings in windows batch file

To avoid blank line skipping (give readability in conf file) I combine aflat and jeb answer (here) to something like this:

@echo off
setlocal enabledelayedexpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=

for /f "tokens=1,* delims=¶" %%A in ( '"findstr /n ^^ %INTEXTFILE%"') do (
   SET string=%%A
   for /f "delims=: tokens=1,*" %%a in ("!string!") do set "string=%%b"
   if  "!string!" == "" (
       echo.>>%OUTTEXTFILE%
   ) else (
      SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!
      echo !modified! >> %OUTTEXTFILE%
  )
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Greek would need UTF-8 on N column types: aß? ;)

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Can I do Android Programming in C++, C?

You should use Android NDK to develop performance-critical portions of your apps in native code. See Android NDK.

Anyway i don't think it is the right way to develop an entire application.

Difference between jQuery parent(), parents() and closest() functions

from http://api.jquery.com/closest/

The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle, are significant:

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • The returned jQuery object contains zero or one element

.parents()

  • Begins with the parent element
  • Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero, one, or multiple elements

.parent()

  • Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Note: The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $("html").parent() method returns a set containing document whereas $("html").parents() returns an empty set.

Here are related threads:

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

This errors occurs when we use same method name for Jaxb2Marshaller for exemple:

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.loans");

        return marshaller;
    }

And on other file

    @Bean
    public Jaxb2Marshaller marshallerClient() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        marshaller.setContextPath("library.io.github.walterwhites.client");

        return marshaller;
    }

Even It's different class, you should named them differently

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

Change a HTML5 input's placeholder color with CSS

In the html file:

<input type="text" placeholder="placeholder" class="redPlaceHolder">

In the css file:

.redPlaceHolder{
   color: #ff0000;
}

'profile name is not valid' error when executing the sp_send_dbmail command

Did you enable the profile for SQL Server Agent? This a common step that is missed when creating Email profiles in DatabaseMail.

Steps:

  • Right-click on SQL Server Agent in Object Explorer (SSMS)
  • Click on Properties
  • Click on the Alert System tab in the left-hand navigation
  • Enable the mail profile
  • Set Mail System and Mail Profile
  • Click OK
  • Restart SQL Server Agent

How can you represent inheritance in a database?

I lean towards method #1 (a unified Section table), for the sake of efficiently retrieving entire policies with all their sections (which I assume your system will be doing a lot).

Further, I don't know what version of SQL Server you're using, but in 2008+ Sparse Columns help optimize performance in situations where many of the values in a column will be NULL.

Ultimately, you'll have to decide just how "similar" the policy sections are. Unless they differ substantially, I think a more-normalized solution might be more trouble than it's worth... but only you can make that call. :)

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In my case the problem was what Steve S. mentioned:

The pod is crashing because it starts up then immediately exits, thus Kubernetes restarts and the cycle continues.

Namely I had a Java application whose main threw an exception (and something overrode the default uncaught exception handler so that nothing was logged). The solution was to put the body of main into try { ... } catch and print out the exception. Thus I could find out what was wrong and fix it.

(Another cause could be something in the app calling System.exit; you could use a custom SecurityManager with an overridden checkExit to prevent (or log the caller of) exit; see https://stackoverflow.com/a/5401319/204205.)

How can I dynamically switch web service addresses in .NET without a recompile?

I've struggled with this issue for a few days and finally the light bulb clicked. The KEY to being able to change the URL of a webservice at runtime is overriding the constructor, which I did with a partial class declaration. The above, setting the URL behavior to Dynamic must also be done.

This basically creates a web-service wrapper where if you have to reload web service at some point, via add service reference, you don't loose your work. The Microsoft help for Partial classes specially states that part of the reason for this construct is to create web service wrappers. http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.100).aspx

// Web Service Wrapper to override constructor to use custom ConfigSection 
// app.config values for URL/User/Pass
namespace myprogram.webservice
{
    public partial class MyWebService
    {
        public MyWebService(string szURL)
        {
            this.Url = szURL;
            if ((this.IsLocalFileSystemWebService(this.Url) == true))
            {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else
            {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }
    }
}

Execute Shell Script after post build in Jenkins

You should be able to do that with the Batch Task plugin.

  1. Create a batch task in the project.
  2. Add a "Invoke batch tasks" post-build option selecting the same project.

An alternative can also be Post build task plugin.

Why is a "GRANT USAGE" created the first time I grant a user privileges?

I was trying to find the meaning of GRANT USAGE on *.* TO and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password will be granted when you create the user with the following command (CREATE):

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password'; 

When you grant privilege with GRANT, new privilege s will be added on top of it.

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

How to create an executable .exe file from a .m file

It used to be possible to compile Matlab to C with older versions of Matlab. Check out other tools that Matlab comes with.

Newest Matlab code can be exported as a Java's jar or a .Net Dll, etc. You can then write an executable against that library - it will be obfuscated by the way. The users will have to install a freely available Matlab Runtime.

Like others mentioned, mcc / mcc.exe is what you want to convert matlab code to C code.

How to get instance variables in Python?

Although not directly an answer to the OP question, there is a pretty sweet way of finding out what variables are in scope in a function. take a look at this code:

>>> def f(x, y):
    z = x**2 + y**2
    sqrt_z = z**.5
    return sqrt_z

>>> f.func_code.co_varnames
('x', 'y', 'z', 'sqrt_z')
>>> 

The func_code attribute has all kinds of interesting things in it. It allows you todo some cool stuff. Here is an example of how I have have used this:

def exec_command(self, cmd, msg, sig):

    def message(msg):
        a = self.link.process(self.link.recieved_message(msg))
        self.exec_command(*a)

    def error(msg):
        self.printer.printInfo(msg)

    def set_usrlist(msg):
        self.client.connected_users = msg

    def chatmessage(msg):
        self.printer.printInfo(msg)

    if not locals().has_key(cmd): return
    cmd = locals()[cmd]

    try:
        if 'sig' in cmd.func_code.co_varnames and \
                       'msg' in cmd.func_code.co_varnames: 
            cmd(msg, sig)
        elif 'msg' in cmd.func_code.co_varnames: 
            cmd(msg)
        else:
            cmd()
    except Exception, e:
        print '\n-----------ERROR-----------'
        print 'error: ', e
        print 'Error proccessing: ', cmd.__name__
        print 'Message: ', msg
        print 'Sig: ', sig
        print '-----------ERROR-----------\n'

How to find whether MySQL is installed in Red Hat?

to ckeck the status use the below command, which worked on debian....

/etc/init.d/mysql status

to start my sql server use the below command

/etc/init.d/mysql start

to stop the server use the below command

/etc/init.d/mysql stop

Find element in List<> that contains a value

Either use LINQ:

var value = MyList.First(item => item.name == "foo").value;

(This will just find the first match, of course. There are lots of options around this.)

Or use Find instead of FindIndex:

var value = MyList.Find(item => item.name == "foo").value;

I'd strongly suggest using LINQ though - it's a much more idiomatic approach these days.

(I'd also suggest following the .NET naming conventions.)

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

This answer might be helpful if you see above error but actually you have CUDA 10 installed:

pip install tensorflow-gpu==2.0.0

output:

I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_100.dll

which was the solution for me.

How can I start and check my MySQL log?

Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Static link of shared library function in gcc

In gcc, this isn't supported. In fact, this isn't supported in any existing compiler/linker i'm aware of.

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

I faced this issue once and was able to resolve it by fixing of my /etc/hosts. It just was unable to resolve localhost name... Details are here: http://itvictories.com/node/6

In fact, there is 99% that error related to /etc/hosts file

X server just unable to resolve localhost and all consequent actions just fails.

Please be sure that you have a record like

127.0.0.1 localhost

in your /etc/hosts file.

What is the id( ) function used for?

id() does return the address of the object being referenced (in CPython), but your confusion comes from the fact that python lists are very different from C arrays. In a python list, every element is a reference. So what you are doing is much more similar to this C code:

int *arr[3];
arr[0] = malloc(sizeof(int));
*arr[0] = 1;
arr[1] = malloc(sizeof(int));
*arr[1] = 2;
arr[2] = malloc(sizeof(int));
*arr[2] = 3;
printf("%p %p %p", arr[0], arr[1], arr[2]);

In other words, you are printing the address from the reference and not an address relative to where your list is stored.

In my case, I have found the id() function handy for creating opaque handles to return to C code when calling python from C. Doing that, you can easily use a dictionary to look up the object from its handle and it's guaranteed to be unique.

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

"Insert if not exists" statement in SQLite

insert into bookmarks (users_id, lessoninfo_id)

select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;

This is the fastest way.

For some other SQL engines, you can use a Dummy table containing 1 record. e.g:

select 1, 167 from ONE_RECORD_DUMMY_TABLE

What is the difference between Cygwin and MinGW?

Cygwin is is a Unix-like environment and command-line interface for Microsoft Windows.

Mingw is a native software port of the GNU Compiler Collection (GCC) to Microsoft Windows, along with a set of freely distributable import libraries and header files for the Windows API. MinGW allows developers to create native Microsoft Windows applications.

You can run binaries generated with mingw without the cygwin environment, provided that all necessary libraries (DLLs) are present.

Partly cherry-picking a commit with Git

If you want to specify a list of files on the command line, and get the whole thing done in a single atomic command, try:

git apply --3way <(git show -- list-of-files)

--3way: If a patch does not apply cleanly, Git will create a merge conflict so you can run git mergetool. Omitting --3way will make Git give up on patches which don't apply cleanly.

What does '<?=' mean in PHP?

<?=$a; ?>

is a shortcut for:

<?php echo $a; ?>

Git commit -a "untracked files"?

For others having the same problem, try running

git add . which will add all files of the current directory to track (including untracked) and then use

git commit -a to commit all tracked files.

As suggested by @Pacerier, one liner that does the same thing is

git add -A

What's the difference between Thread start() and Runnable run()

The difference is that Thread.start() starts a thread that calls the run() method, while Runnable.run() just calls the run() method on the current thread.

How to preventDefault on anchor tags?

Although Renaud gave a great solution

<a href="#" ng-click="do(); $event.preventDefault()">Click</a> 

I personally found you also need $event.stopPropagation() in some cases to avoid some of the side effects

<a href="#" ng-click="do(); $event.preventDefault(); $event.stopPropagation();">
    Click</a>

will be my solution

How do you pass view parameters when navigating from an action in JSF2?

The unintuitive thing about passing parameters in JSF is that you do not decide what to send (in the action), but rather what you wish to receive (in the target page).

When you do an action that ends with a redirect, the target page metadata is loaded and all required parameters are read and appended to the url as params.

Note that this is exactly the same mechanism as with any other JSF binding: you cannot read inputText's value from one place and have it write somewhere else. The value expression defined in viewParam is used both for reading (before the redirect) and for writing (after the redirect).

With your bean you just do:

@ManagedBean
@RequestScoped
public class MyBean {

private int id;

public String submit() {
    //Does stuff
    id = setID();
    return "success?faces-redirect=true&includeViewParams=true";
}

// setter and getter for id

If the receiving side has:

    <f:metadata>
        <f:viewParam name="id" value="#{myBean.id}" />
    </f:metadata>

It will do exactly what you want.

Python Checking a string's first and last character

When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1

How to convert an ArrayList containing Integers to primitive int array?

This code segment is working for me, try this:

Integer[] arr = x.toArray(new Integer[x.size()]);

Worth to mention ArrayList should be declared like this:

ArrayList<Integer> list = new ArrayList<>();

Remove specific commit

From other answers here, I was kind of confused with how git rebase -i could be used to remove a commit, so I hope it's OK to jot down my test case here (very similar to the OP).

Here is a bash script that you can paste in to create a test repository in the /tmp folder:

set -x

rm -rf /tmp/myrepo*
cd /tmp

mkdir myrepo_git
cd myrepo_git
git init
git config user.name me
git config user.email [email protected]

mkdir folder
echo aaaa >> folder/file.txt
git add folder/file.txt
git commit -m "1st git commit"

echo bbbb >> folder/file.txt
git add folder/file.txt
git commit -m "2nd git commit"

echo cccc >> folder/file.txt
git add folder/file.txt
git commit -m "3rd git commit"

echo dddd >> folder/file.txt
git add folder/file.txt
git commit -m "4th git commit"

echo eeee >> folder/file.txt
git add folder/file.txt
git commit -m "5th git commit"

At this point, we have a file.txt with these contents:

aaaa
bbbb
cccc
dddd
eeee

At this point, HEAD is at the 5th commit, HEAD~1 would be the 4th - and HEAD~4 would be the 1st commit (so HEAD~5 wouldn't exist). Let's say we want to remove the 3rd commit - we can issue this command in the myrepo_git directory:

git rebase -i HEAD~4

(Note that git rebase -i HEAD~5 results with "fatal: Needed a single revision; invalid upstream HEAD~5".) A text editor (see screenshot in @Dennis' answer) will open with these contents:

pick 5978582 2nd git commit
pick 448c212 3rd git commit
pick b50213c 4th git commit
pick a9c8fa1 5th git commit

# Rebase b916e7f..a9c8fa1 onto b916e7f
# ...

So we get all commits since (but not including) our requested HEAD~4. Delete the line pick 448c212 3rd git commit and save the file; you'll get this response from git rebase:

error: could not apply b50213c... 4th git commit

When you have resolved this problem run "git rebase --continue".
If you would prefer to skip this patch, instead run "git rebase --skip".
To check out the original branch and stop rebasing run "git rebase --abort".
Could not apply b50213c... 4th git commit

At this point open myrepo_git/folder/file.txt in a text editor; you'll see it has been modified:

aaaa
bbbb
<<<<<<< HEAD
=======
cccc
dddd
>>>>>>> b50213c... 4th git commit

Basically, git sees that when HEAD got to 2nd commit, there was content of aaaa + bbbb; and then it has a patch of added cccc+dddd which it doesn't know how to append to the existing content.

So here git cannot decide for you - it is you who has to make a decision: by removing the 3rd commit, you either keep the changes introduced by it (here, the line cccc) -- or you don't. If you don't, simply remove the extra lines - including the cccc - in folder/file.txt using a text editor, so it looks like this:

aaaa
bbbb
dddd

... and then save folder/file.txt. Now you can issue the following commands in myrepo_git directory:

$ nano folder/file.txt  # text editor - edit, save
$ git rebase --continue
folder/file.txt: needs merge
You must edit all merge conflicts and then
mark them as resolved using git add

Ah - so in order to mark that we've solved the conflict, we must git add the folder/file.txt, before doing git rebase --continue:

$ git add folder/file.txt
$ git rebase --continue

Here a text editor opens again, showing the line 4th git commit - here we have a chance to change the commit message (which in this case could be meaningfully changed to 4th (and removed 3rd) commit or similar). Let's say you don't want to - so just exit the text editor without saving; once you do that, you'll get:

$ git rebase --continue
[detached HEAD b8275fc] 4th git commit
 1 file changed, 1 insertion(+)
Successfully rebased and updated refs/heads/master.

At this point, now you have a history like this (which you could also inspect with say gitk . or other tools) of the contents of folder/file.txt (with, apparently, unchanged timestamps of the original commits):

1st git commit  |  +aaaa
----------------------------------------------
2nd git commit  |   aaaa
                |  +bbbb
----------------------------------------------
4th git commit  |   aaaa
                |   bbbb
                |  +dddd
----------------------------------------------
5th git commit  |   aaaa
                |   bbbb
                |   dddd
                |  +eeee

And if previously, we decided to keep the line cccc (the contents of the 3rd git commit that we removed), we would have had:

1st git commit  |  +aaaa
----------------------------------------------
2nd git commit  |   aaaa
                |  +bbbb
----------------------------------------------
4th git commit  |   aaaa
                |   bbbb
                |  +cccc
                |  +dddd
----------------------------------------------
5th git commit  |   aaaa
                |   bbbb
                |   cccc
                |   dddd
                |  +eeee

Well, this was the kind of reading I hoped I'd have found, to start grokking how git rebase works in terms of deleting commits/revisions; so hope it might help others too...

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

I believe I found the answer. Per the Xcode 12 beta 6 release notes:

"The Build Settings editor no longer includes the Valid Architectures build setting (VALID_ARCHS), and its use is discouraged. Instead, there is a new Excluded Architectures build setting (EXCLUDED_ARCHS). If a project includes VALID_ARCHS, the setting is displayed in the User-Defined section of the Build Settings editor. (15145028)"

I was able to resolve this issue by manually editing the project file (I could not figure out how to remove the item from the project file using Xcode) and removing all lines referring to VALID_ARCHS. After that, I am able to build for the simulator fine.

Control the dashed border stroke length and distance between strokes

This will make an orange and gray border using the class="myclass" on the div.

.myclass {
    outline:dashed darkorange  12px;
    border:solid slategray  14px;
    outline-offset:-14px;
}

How to parse XML using shellscript?

A rather new project is the xml-coreutils package featuring xml-cat, xml-cp, xml-cut, xml-grep, ...

http://xml-coreutils.sourceforge.net/contents.html

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

How is the default max Java heap size determined?

This is changed in Java 6 update 18.

Assuming that we have more than 1 GB of physical memory (quite common these days), it's always 1/4th of your physical memory for the server vm.

How can you use php in a javascript function

You can't run PHP code with Javascript. When the user recieves the page, the server will have evaluated and run all PHP code, and taken it out. So for example, this will work:

alert( <?php echo "\"Hello\""; ?> );

Because server will have evaluated it to this:

alert("Hello");

However, you can't perform any operations in PHP with it.

This:

function Inc()
{
<?php
$num = 2;
echo $num;
?>
}

Will simply have been evaluated to this:

function Inc()
{
    2
}

If you wan't to call a PHP script, you'll have to call a different page which returns a value from a set of parameters.

This, for example, will work:

script.php

$num = $_POST["num"];
echo $num * 2;

Javascript(jQuery) (on another page):

$.post('script.php', { num: 5 }, function(result) { 
   alert(result); 
});

This should alert 10.

Good luck!

Edit: Just incrementing a number on the page can be done easily in jQuery like this: http://jsfiddle.net/puVPc/

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

How to set a CMake option() at command line

Delete the CMakeCache.txt file and try this:

cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..

You have to enter all your command-line definitions before including the path.

How to use target in location.href

try this one, which simulates a click on an anchor.

var a = document.createElement('a');
a.href='http://www.google.com';
a.target = '_blank';
document.body.appendChild(a);
a.click();

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

sql server #region

No, #region does not exist in the T-SQL language.

You can get code-folding using begin-end blocks:

-- my region
begin
    -- code goes here
end

I'm not sure I'd recommend using them for this unless the code cannot be acceptably refactored by other means though!

Python argparse: default value or specified value

Actually, you only need to use the default argument to add_argument as in this test.py script:

import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--example', default=1)
    args = parser.parse_args()
    print(args.example)

test.py --example
% 1
test.py --example 2
% 2

Details are here.

Can jQuery read/write cookies to a browser?

To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.

It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.

You may want to consider posting your second question in another topic.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

I use this simple function, which returns true or false, to test for localStorage availablity:

isLocalStorageNameSupported = function() {
    var testKey = 'test', storage = window.sessionStorage;
    try {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

Now you can test for localStorage.setItem() availability before using it. Example:

if ( isLocalStorageNameSupported() ) {
    // can use localStorage.setItem('item','value')
} else {
    // can't use localStorage.setItem('item','value')
}

How to center align the ActionBar title in Android?

Code here working for me.

    // Activity 
 public void setTitle(String title){
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(this);
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(textView);
} 

// Fragment
public void setTitle(String title){
    ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(getActivity());
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}

psql: FATAL: role "postgres" does not exist

First you need create a user:

sudo -u postgres createuser --superuser $USER

After you create a database:

sudo -u postgres createdb $USER

Change $USER to your system username.

You can see the the complete solution here.

Random string generation with upper case letters and digits

import uuid
lowercase_str = uuid.uuid4().hex  

lowercase_str is a random value like 'cea8b32e00934aaea8c005a35d85a5c0'

uppercase_str = lowercase_str.upper()

uppercase_str is 'CEA8B32E00934AAEA8C005A35D85A5C0'

Display HTML form values in same page after submit using Ajax

<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>

<!--Insert more code here-->


<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">

Next time you ask a question here, include more detail and what you have tried.

How can I auto hide alert box after it showing it?

tldr; jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
 var el = document.createElement("div");
 el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
 el.innerHTML = msg;
 setTimeout(function(){
  el.parentNode.removeChild(el);
 },duration);
 document.body.appendChild(el);
}

Use this like this:

tempAlert("close",5000);

Add target="_blank" in CSS

This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:

var i_will_target_self = document.querySelectorAll("ul.menu li a#example")

this example uses css to target links in a menu with id = "example"

that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):

for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}

That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."

read more here: http://xahlee.info/js/js_get_elements.html

Getting an odd error, SQL Server query using `WITH` clause

In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:

SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1

And not:

SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

How to get the list of all installed color schemes in Vim?

Type

:colorscheme then Space followed by TAB.

or as Peter said,

:colorscheme then Space followed by CTRLd

The short version of the command is :colo so you can use it in the two previous commands, instead of using the "long form".

If you want to find and preview more themes, there are various websites like Vim colors

View not attached to window manager crash

Issue could be that the Activity have been finished or in progress of finishing.

Add a check isFinishing , and dismiss dialog only when this is false

if (!YourActivity.this.isFinishing() && pDialog != null) {
    pDialog.dismiss();
}

isFinishing : Check to see whether this activity is in the process of finishing,either because you called finish on it or someone else has requested that it finished.

How to insert data using wpdb

Just use wpdb->insert(tablename, coloumn, format) and wp will prepare that's query

<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
   "name" => $name,
   "email" => $email,
   "phone" => $phone,
   "country" => $country,
   "course" => $course,
   "message" => $message,
   "datesent" => $now ,
));
?>

Apply function to pandas groupby

Try:

g = pd.DataFrame(['A','B','A','C','D','D','E'])

# Group by the contents of column 0 
gg = g.groupby(0)  

# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())

# Add a new column that is the count / total number of elements    
histo[1] = histo.astype(np.float)/len(g) 

print histo

Output:

   0         1
0             
A  2  0.285714
B  1  0.142857
C  1  0.142857
D  2  0.285714
E  1  0.142857

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

in laravel used decimal column type for migration

$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);

for more information see available column type

Seaborn Barplot - Displaying Values

Let's stick to the solution from the linked question (Changing color scale in seaborn bar plot). You want to use argsort to determine the order of the colors to use for colorizing the bars. In the linked question argsort is applied to a Series object, which works fine, while here you have a DataFrame. So you need to select one column of that DataFrame to apply argsort on.

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

df = sns.load_dataset("tips")
groupedvalues=df.groupby('day').sum().reset_index()

pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["total_bill"].argsort().argsort() 
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette=np.array(pal[::-1])[rank])

for index, row in groupedvalues.iterrows():
    g.text(row.name,row.tip, round(row.total_bill,2), color='black', ha="center")

plt.show()

enter image description here


The second attempt works fine as well, the only issue is that the rank as returned by rank() starts at 1 instead of zero. So one has to subtract 1 from the array. Also for indexing we need integer values, so we need to cast it to int.

rank = groupedvalues['total_bill'].rank(ascending=True).values
rank = (rank-1).astype(np.int)

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Including JavaScript class definition from another file in Node.js

Instead of myFile.js write your files like myFile.mjs. This extension comes with all the goodies of es6, but I mean I recommend you to you webpack and Babel

Java, "Variable name" cannot be resolved to a variable

public void setHoursWorked(){
    hoursWorked = hours;
}

You haven't defined hours inside that method. hours is not passed in as a parameter, it's not declared as a variable, and it's not being used as a class member, so you get that error.

Why doesn't Mockito mock static methods?

As an addition to the Gerold Broser's answer, here an example of mocking a static method with arguments:

class Buddy {
  static String addHello(String name) {
    return "Hello " + name;
  }
}

...

@Test
void testMockStaticMethods() {
  assertThat(Buddy.addHello("John")).isEqualTo("Hello John");

  try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
    theMock.when(() -> Buddy.addHello("John")).thenReturn("Guten Tag John");
    assertThat(Buddy.addHello("John")).isEqualTo("Guten Tag John");
  }

  assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
}

Get file path of image on Android

In order to take a picture you have to determine a path where you would like the image saved and pass that as an extra in the intent, for example:

private void capture(){
    String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
    String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
    File directory = new File(directoryPath);
    if (!directory.exists()) {
        directory.mkdirs();
    }
    this.capturePath = filePath; // you will process the image from this path if the capture goes well
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
    startActivityForResult(intent, REQUEST_CAPTURE);                

}

I just copied the above portion from another answer I gave.

However to warn you there are a lot of inconsitencies with image capture behavior between devices that you should look out for.

Here is an issue I ran into on some HTC devices, where it would save in the location I passed and in it's default location resulting in duplicate images on the device: Deleting a gallery image after camera intent photo taken

Openssl is not recognized as an internal or external command

it's late answer but it will help to lazy people like me.. add this code to your Application class, there is no need to download openssl and no need to set the path.. only need is just copy this code.. and keyHash will generated in log.

import com.facebook.FacebookSdk;
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
        printKeyHash();
    }

    private void printKeyHash() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.i("KeyHash:",
                        Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("jk", "Exception(NameNotFoundException) : " + e);
        } catch (NoSuchAlgorithmException e) {
            Log.e("mkm", "Exception(NoSuchAlgorithmException) : " + e);
        }
    }
}

and do not forget add MyApplication class in manifest:

<application
        android:name=".MyApplication"
</application>

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

I had a similar issue and my solution was this code snippet (tested in IE8/9, Chrome and Firefox)

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

iframe.src = 'javascript:void((function(){var script = document.createElement(\'script\');' +
  'script.innerHTML = "(function() {' +
  'document.open();document.domain=\'' + document.domain +
  '\';document.close();})();";' +
  'document.write("<head>" + script.outerHTML + "</head><body></body>");})())';

iframe.contentWindow.document.write('<div>foo</div>');

I've tried several methods but this one appeared to be the best. You can find some explanations in my blog post here.

Reading in a JSON File Using Swift

Simplifying the example provided by Peter Kreinz. Works with Swift 4.2.

The extension function:

extension Decodable {
  static func parse(jsonFile: String) -> Self? {
    guard let url = Bundle.main.url(forResource: jsonFile, withExtension: "json"),
          let data = try? Data(contentsOf: url),
          let output = try? JSONDecoder().decode(self, from: data)
        else {
      return nil
    }

    return output
  }
}

The example model:

struct Service: Decodable {
  let name: String
}

The example usage:

/// service.json
/// { "name": "Home & Garden" }

guard let output = Service.parse(jsonFile: "service") else {
// do something if parsing failed
 return
}

// use output if all good

The example will work with arrays, too:

/// services.json
/// [ { "name": "Home & Garden" } ]

guard let output = [Service].parse(jsonFile: "services") else {
// do something if parsing failed
 return
}

// use output if all good

Notice how we don't provide any unnecessary generics, thus we don't need to cast the result of parse.

Targeting only Firefox with CSS

Here is some browser hacks for targeting only the Firefox browser,

Using selector hacks.

_:-moz-tree-row(hover), .selector {}

JavaScript Hacks

var isFF = !!window.sidebar;

var isFF = 'MozAppearance' in document.documentElement.style;

var isFF = !!navigator.userAgent.match(/firefox/i);

Media Query Hacks

This is gonna work on, Firefox 3.6 and Later

@media screen and (-moz-images-in-menus:0) {}

If you need more information,Please visit browserhacks

How to capture the "virtual keyboard show/hide" event in Android?

Nebojsa Tomcic's answer wasn't helpful for me. I have RelativeLayout with TextView and AutoCompleteTextView inside it. I need to scroll the TextView to the bottom when the keyboard is showed and when it's hidden. To accomplish this I overrode onLayout method and it works fine for me.

public class ExtendedLayout extends RelativeLayout
{
    public ExtendedLayout(Context context, AttributeSet attributeSet)
    {
        super(context, attributeSet);
        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main, this);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        super.onLayout(changed, l, t, r, b);

        if (changed)
        {
            int scrollEnd = (textView.getLineCount() - textView.getHeight() /
                textView.getLineHeight()) * textView.getLineHeight();
            textView.scrollTo(0, scrollEnd);
        }
    }
}

How do you sort a dictionary by value?

Or for fun you could use some LINQ extension goodness:

var dictionary = new Dictionary<string, int> { { "c", 3 }, { "a", 1 }, { "b", 2 } };
dictionary.OrderBy(x => x.Value)
  .ForEach(x => Console.WriteLine("{0}={1}", x.Key,x.Value));

How can I set the PATH variable for javac so I can manually compile my .java works?

Trying this out on Windows 10, none of the command-line instructions worked.

Right clicking on "Computer" then open Properties etc. as the post by Galen Nare above already explains, leads you to a window where you need to click on "new" and then paste the path (as said: without deleting anything else). Afterwards you can check by typing java -version in the command-line window, which should display your current java version, if everything worked out right.

What is the default value for Guid?

You can use Guid.Empty. It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000

you can also use these instead

var g = new Guid();
var g = default(Guid);

beware not to use Guid.NewGuid() because it will generate a new Guid.

use one of the options above which you and your team think it is more readable and stick to it. Do not mix different options across the code. I think the Guid.Empty is the best one since new Guid() might make us think it is generating a new guid and some may not know what is the value of default(Guid).

iOS: present view controller programmatically

Try this code:

[self.navigationController presentViewController:controller animated:YES completion:nil];

Embedding a media player in a website using HTML

<html>

<head>
  <H1>
      Automatically play music files on your website when a page loads
    </H1>
</head>

<body>
  <embed src="YourMusic.mp3" autostart="true" loop="true" width="2" height="0">
  </embed>
</body>

</html>

JQuery Datatables : Cannot read property 'aDataSort' of undefined

In my case I had

$(`#my_table`).empty();

Where it should have been

$(`#my_table tbody`).empty();

Note: in my case I had to empty the table since i had data that I wanted gone before inserting new data.

Just thought of sharing where it "might" help someone in the future!

No Such Element Exception?

I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:

 while (i.hasNext()) {
    // code goes here 
}

I did one iteration at the start, and then checked for condition using:

do {
   // code goes here
} while (i.hasNext());

I hope this will help some people at some stage.

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

"UnboundLocalError: local variable referenced before assignment" after an if statement

Before I start, I'd like to note that I can't actually test this since your script reads data from a file that I don't have.

'T' is defined in a local scope for the declared function. In the first instance 'T' is assigned the value of 'data[2]' because the conditional statement above apparently evaluates to True. Since the second call to the function causes the 'UnboundLocalError' exception to occur, the local variable 'T' is getting set and the conditional assignment is never getting triggered.

Since you appear to want to return the first bit of data in the file that matches your conditonal statement, you might want to modify you function to look like this:

def temp_sky(lreq, breq):
    for line in tfile:
        data = line.split()
        if ( abs(float(data[0]) - lreq) <= 0.1 and abs(float(data[1]) - breq) <= 0.1):            
            return data[2]
    return None

That way the desired value gets returned when it is found, and 'None' is returned when no matching data is found.

Visual Studio Code cannot detect installed git

i have recently start visual studio code and have this issue and just write the exact path of executable git solve the issue .... here is the code ...

"git.path": "C:\Program Files\Git\bin\git.exe",

With CSS, use "..." for overflowed block of multi-lines

Here is the closest solution I could get using just css.

HTML

<div class="ellipsis"> <span>...</span>
Hello this is Mr_Green from Stackoverflow. I love CSS. I live in CSS and I will never leave working on CSS even my work is on other technologies.</div>

CSS

div {
    height: 3em;
    line-height: 1.5em;
    width: 80%;
    border: 1px solid green;
    overflow: hidden;
    position: relative;
}
div:after {
    content:". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  . . . . . . . . . . . . . . . . . . . . . . . . . . . .";
    background-color: white;
    color: white;
    display: inline;
    position: relative;
    box-shadow: 8px 1px 1px white;
    z-index: 1;
}
span {
    position: absolute;
    bottom: 0px;
    right: 0px;
    background-color: white;
}

Working Fiddle (resize the window to check)

Link to my blog for explanation

Updated Fiddle

I hope now some css expert would have got idea on how to make it perfect. :)

How to show empty data message in Datatables

Late to the game, but you can also use a localisation file

DataTable provides a .json localized file, which contains the key sEmptyTable and the corresponding localized message.

For example, just download the localized json file on the above link, then initialize your Datatable like that :

$('#example').dataTable( {
    "language": {
        "url": "path/to/your/json/file.json"
    }
});

IMHO, that's a lot cleaner, because your localized content is located in an external file.

This syntax works for DataTables 1.10.16, I didn't test on previous versions.

How do I restrict a float value to only two places after the decimal point in C?

There isn't a way to round a float to another float because the rounded float may not be representable (a limitation of floating-point numbers). For instance, say you round 37.777779 to 37.78, but the nearest representable number is 37.781.

However, you can "round" a float by using a format string function.

'router-outlet' is not a known element

This issue was with me also. Simple trick for it.

 @NgModule({
  imports: [
   .....       
  ],
 declarations: [
  ......
 ],

 providers: [...],
 bootstrap: [...]
 })

use it as in above order.first imports then declarations.It worked for me.

Reset all the items in a form

Do as below create class and call it like this

Check : Reset all Controls (Textbox, ComboBox, CheckBox, ListBox) in a Windows Form using C#

private void button1_Click(object sender, EventArgs e)
{
   Utilities.ResetAllControls(this);
}

public class Utilities
    {
        public static void ResetAllControls(Control form)
        {
            foreach (Control control in form.Controls)
            {
                if (control is TextBox)
                {
                    TextBox textBox = (TextBox)control;
                    textBox.Text = null;
                }

                if (control is ComboBox)
                {
                    ComboBox comboBox = (ComboBox)control;
                    if (comboBox.Items.Count > 0)
                        comboBox.SelectedIndex = 0;
                }

                if (control is CheckBox)
                {
                    CheckBox checkBox = (CheckBox)control;
                    checkBox.Checked = false;
                }

                if (control is ListBox)
                {
                    ListBox listBox = (ListBox)control;
                    listBox.ClearSelected();
                }
            }
        }      
    }

pass post data with window.location.href

Have you considered simply using Local/Session Storage? -or- Depending on the complexity of what you're building; you could even use indexDB.

note:

Local storage and indexDB are not secure - so you want to avoid storing any sensitive / personal data (i.e names, addresses, emails addresses, DOB etc) in either of these.

Session Storage is a more secure option for anything sensitive, it's only accessible to the origin that set the items and also clears as soon as the browser / tab is closed.

IndexDB is a little more [but not much more] complicated and is a 30MB noSQL database built into every browser (but can be basically unlimited if the user opts in) -> next time you're using Google docs, open you DevTools -> application -> IndexDB and take a peak. [spoiler alert: it's encrypted].

Focusing on Local and Session Storage; these are both dead simple to use:

// To Set 
sessionStorage.setItem( 'key' , 'value' );

// e.g.
sessionStorage.setItem( 'formData' , { name: "Mr Manager", company: "Bluth's Frozen Bananas", ...  } );    

// Get The Data 
const fromData = sessionStorage.getItem( 'key' );     

// e.g. (after navigating to next location)
const fromData = sessionStorage.getItem( 'formData' );

// Remove 
sessionStorage.removeItem( 'key' );

// Remove _all_ saved data sessionStorage
sessionStorage.clear( ); 

If simple is not your thing -or- maybe you want to go off road and try a different approach all together -> you can probably use a shared web worker... y'know, just for kicks.

How to check if text fields are empty on form submit using jQuery?

function isEmpty(val) {
if(val.length ==0 || val.length ==null){
    return 'emptyForm';
}else{
    return 'not emptyForm';
}

}

$(document).ready(function(){enter code here
    $( "form" ).submit(function( event ) {
        $('input').each(function(){
           var getInputVal = $(this).val();
            if(isEmpty(getInputVal) =='emptyForm'){
                alert(isEmpty(getInputVal));
            }else{
                alert(isEmpty(getInputVal));
            }
        });
        event.preventDefault();
    });
});

Set icon for Android application

In AndroidManifest change these :

android:icon="@drawable/icon_name"
android:roundIcon="@drawable/icon_name"

How do I scroll to an element using JavaScript?

try this function

function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}

Pass the div id as parameter it will work I am using it already

Where can I find free WPF controls and control templates?

Codeplex is definitively the right place. Recent "post": SofaWPF.codeplex.com based on AvalonDock.codeplex.com, an IDE like framework.

How to check if a float value is a whole number

Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.

for i in range(20, 30):
    print("Trying {0}".format(i))
    if i ** 3 > 12000:
        print("Maximum integral cube root less than 12000: {0}".format(i - 1))
        break

correct PHP headers for pdf file download

You need to define the size of file...

header('Content-Length: ' . filesize($file));

And this line is wrong:

header("Content-Disposition:inline;filename='$filename");

You messed up quotas.

The OutputPath property is not set for this project

had this problem as output from Azure DevOps after setting to build the .csproj instead of the .sln in the Build Pipeline.

The solution for me: Edit .csproj of the affected project, then copy your whole

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCpu' ">

Node, paste it, and then change the first line as followed:

    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|any cpu' ">

The reason is, that in my case the error said

Please check to make sure that you have specified a valid combination of Configuration and Platform for this project.  Configuration='release'  Platform='any cpu'.  

Why Azure wants to use "any cpu" instead of the default "AnyCpu" is a mystery for me, but this hack works.

Why does Google prepend while(1); to their JSON responses?

As this is a High traffic post i hope to provide here an answer slightly more undetermined to the original question and thus to provide further background on a JSON Hijacking attack and its consequences

JSON Hijacking as the name suggests is an attack similar to Cross-Site Request Forgery where an attacker can access cross-domain sensitive JSON data from applications that return sensitive data as array literals to GET requests. An example of a JSON call returning an array literal is shown below:

[{"id":"1001","ccnum":"4111111111111111","balance":"2345.15"}, 
{"id":"1002","ccnum":"5555555555554444","balance":"10345.00"}, 
{"id":"1003","ccnum":"5105105105105100","balance":"6250.50"}]

This attack can be achieved in 3 major steps:

Step 1: Get an authenticated user to visit a malicious page. Step 2: The malicious page will try and access sensitive data from the application that the user is logged into.This can be done by embedding a script tag in an HTML page since the same-origin policy does not apply to script tags.

<script src="http://<jsonsite>/json_server.php"></script>

The browser will make a GET request to json_server.php and any authentication cookies of the user will be sent along with the request. Step 3: At this point while the malicious site has executed the script it does not have access to any sensitive data. Getting access to the data can be achieved by using an object prototype setter. In the code below an object prototypes property is being bound to the defined function when an attempt is being made to set the "ccnum" property.

Object.prototype.__defineSetter__('ccnum',function(obj){

secrets =secrets.concat(" ", obj);

});

At this point the malicious site has successfully hijacked the sensitive financial data (ccnum) returned byjson_server.php JSON

It should be noted that not all browsers support this method; the proof of concept was done on Firefox 3.x.This method has now been deprecated and replaced by the useObject.defineProperty There is also a variation of this attack that should work on all browsers where full named JavaScript (e.g. pi=3.14159) is returned instead of a JSON array.

There are several ways in which JSON Hijacking can be prevented:

  • Since SCRIPT tags can only generate HTTP GET requests, only return JSON objects to POST requests.

  • Prevent the web browser from interpreting the JSON object as valid JavaScript code.

  • Implement Cross-Site Request Forgery protection by requiring that a predefined random value be required for all JSON requests.

so as you can see While(1) comes under the last option. In the most simple terms, while(1) is an infinite loop which will run till a break statement is issued explicitly. And thus what would be described as a lock for the key to be applied (google break statement). Therefore a JSON hijacking, in which the Hacker has no key will be consistently dismissed.Alas, If you read the JSON block with a parser, the while(1) loop is ignored.

So in conclusion, the while(1) loop can more easily visualised as a simple break statement cipher that google can use to control flow of data.

However the key word in that statement is the word 'simple'. The usage of authenticated infinite loops has been thankfully removed from basic practice in the years since 2010 due to its absolute decimation of CPU usage when isolated (and the fact the internet has moved away from forcing through crude 'quick-fixes'). Today instead the codebase has preventative measures embedded and the system is not crucial nor effective anymore. (part of this is the move away from JSON Hijacking to more fruitful datafarming techniques that i wont go into at present)

*

Connecting to TCP Socket from browser using javascript

This will be possible via the navigator interface as shown below:

navigator.tcpPermission.requestPermission({remoteAddress:"127.0.0.1", remotePort:6789}).then(
  () => {
    // Permission was granted
    // Create a new TCP client socket and connect to remote host
    var mySocket = new TCPSocket("127.0.0.1", 6789);

    // Send data to server
    mySocket.writeable.write("Hello World").then(
        () => {

            // Data sent sucessfully, wait for response
            console.log("Data has been sent to server");
            mySocket.readable.getReader().read().then(
                ({ value, done }) => {
                    if (!done) {
                        // Response received, log it:
                        console.log("Data received from server:" + value);
                    }

                    // Close the TCP connection
                    mySocket.close();
                }
            );
        },
        e => console.error("Sending error: ", e)
    );
  }
);

More details are outlined in the w3.org tcp-udp-sockets documentation.

http://raw-sockets.sysapps.org/#interface-tcpsocket

https://www.w3.org/TR/tcp-udp-sockets/

Another alternative is to use Chrome Sockets

Creating connections

chrome.sockets.tcp.create({}, function(createInfo) {
  chrome.sockets.tcp.connect(createInfo.socketId,
    IP, PORT, onConnectedCallback);
});

Sending data

chrome.sockets.tcp.send(socketId, arrayBuffer, onSentCallback);

Receiving data

chrome.sockets.tcp.onReceive.addListener(function(info) {
  if (info.socketId != socketId)
    return;
  // info.data is an arrayBuffer.
});

You can use also attempt to use HTML5 Web Sockets (Although this is not direct TCP communication):

var connection = new WebSocket('ws://IPAddress:Port');

connection.onopen = function () {
  connection.send('Ping'); // Send the message 'Ping' to the server
};

http://www.html5rocks.com/en/tutorials/websockets/basics/

Your server must also be listening with a WebSocket server such as pywebsocket, alternatively you can write your own as outlined at Mozilla

add a string prefix to each value in a string column using Pandas

As an alternative, you can also use an apply combined with format (or better with f-strings) which I find slightly more readable if one e.g. also wants to add a suffix or manipulate the element itself:

df = pd.DataFrame({'col':['a', 0]})

df['col'] = df['col'].apply(lambda x: "{}{}".format('str', x))

which also yields the desired output:

    col
0  stra
1  str0

If you are using Python 3.6+, you can also use f-strings:

df['col'] = df['col'].apply(lambda x: f"str{x}")

yielding the same output.

The f-string version is almost as fast as @RomanPekar's solution (python 3.6.4):

df = pd.DataFrame({'col':['a', 0]*200000})

%timeit df['col'].apply(lambda x: f"str{x}")
117 ms ± 451 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit 'str' + df['col'].astype(str)
112 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Using format, however, is indeed far slower:

%timeit df['col'].apply(lambda x: "{}{}".format('str', x))
185 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Checking for empty result (php, pdo, mysql)

what I'm doing wrong here?

Almost everything.

$today = date('Y-m-d'); // no need for strtotime

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR

$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while

return count($this->id_email); // no need for the everything else

effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.

Test for array of string type in TypeScript

You can have do it easily using Array.prototype.some() as below.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && !test.some((value) => typeof value !== 'string')
}
const myArray = ["A", "B", "C"]
console.log(isStringArray(myArray)) // will be log true if string array

I believe this approach is better that others. That is why I am posting this answer.

Update on Sebastian Vittersø's comment

Here you can use Array.prototype.every() as well.

const isStringArray = (test: any[]): boolean => {
 return Array.isArray(test) && test.every((value) => typeof value === 'string')
}

Ignore Duplicates and Create New List of Unique Values in Excel

To remove duplicates from a column

  1. Sort the values in column A A->Z
  2. Select column B
  3. While column B is still selected, in the formula input box, enter

    =IF(TRIM(A1)=TRIM(A2),"",TRIM(A1))
    
  4. While Column B is still selected, select Edit -> Fill -> Down (in newer versions, simply select cell B1 and pull down the outer box to expand all the way down in the column)

Note: if column B is on another sheet, you may do Sheet1!A1 and Sheet1!A2.

foreach for JSON array , syntax

Sure, you can use JS's foreach.

for (var k in result) {
  something(result[k])
}

How to get the value from the GET parameters?

Here I am posting one example. But it's in jQuery. Hope it will help others:

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

<!-- URL:  www.example.com/correct/?message=done&year=1990-->

<script type="text/javascript">
$(function(){
    $.url.attr('protocol')  // --> Protocol: "http"
    $.url.attr('path')          // --> host: "www.example.com"
    $.url.attr('query')         // --> path: "/correct/"
    $.url.attr('message')   // --> query: "done"
    $.url.attr('year')      // --> query: "1990"
});
</script>

How can I give access to a private GitHub repository?

Two steps:
1. Login and click "Invite someone" in the right column under "People". Enter and select persons github id.
2. It will then give you the option to "Invite Username to some teams" at which point you simply check off which teams you want to add them to then click "Send Invitation"

Alternatively:
1. Get the persons github id (not their email)
2. Navigate to the repository you would like to add the user to
3. Click "Settings" in the right column (not the gearbox settings along the top)
4. Click Collaborators long the left column
5. Select the repository name
6. Where it reads "Invite or add users to team" add the persons github id
7. An invitation will then be e-mailed.

Please let me know how this worked for you!

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

White space at top of page

Try this

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

SQL grouping by all the columns

Short answer: no. GROUP BY clauses intrinsically require order to the way they arrange your results. A different order of field groupings would lead to different results.

Specifying a wildcard would leave the statement open to interpretation and unpredictable behaviour.

HTML img scaling

I think the best solution is resize the images via script or locally and upload them again. Remember, you're forcing your viewers to download larger files than they need

How to add property to object in PHP >= 5.3 strict mode without generating error

Yes, is possible to dynamically add properties to a PHP object.

This is useful when a partial object is received from javascript.

JAVASCRIPT side:

var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
    if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});

PHP side:

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.

Differences between fork and exec

fork() creates a copy of the current process, with execution in the new child starting from just after the fork() call. After the fork(), they're identical, except for the return value of the fork() function. (RTFM for more details.) The two processes can then diverge still further, with one unable to interfere with the other, except possibly through any shared file handles.

exec() replaces the current process with a new one. It has nothing to do with fork(), except that an exec() often follows fork() when what's wanted is to launch a different child process, rather than replace the current one.

How to create a custom string representation for a class object?

Ignacio Vazquez-Abrams' approved answer is quite right. It is, however, from the Python 2 generation. An update for the now-current Python 3 would be:

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(object, metaclass=MC):
    pass

print(C)

If you want code that runs across both Python 2 and Python 3, the six module has you covered:

from __future__ import print_function
from six import with_metaclass

class MC(type):
  def __repr__(self):
    return 'Wahaha!'

class C(with_metaclass(MC)):
    pass

print(C)

Finally, if you have one class that you want to have a custom static repr, the class-based approach above works great. But if you have several, you'd have to generate a metaclass similar to MC for each, and that can get tiresome. In that case, taking your metaprogramming one step further and creating a metaclass factory makes things a bit cleaner:

from __future__ import print_function
from six import with_metaclass

def custom_class_repr(name):
    """
    Factory that returns custom metaclass with a class ``__repr__`` that
    returns ``name``.
    """
    return type('whatever', (type,), {'__repr__': lambda self: name})

class C(with_metaclass(custom_class_repr('Wahaha!'))): pass

class D(with_metaclass(custom_class_repr('Booyah!'))): pass

class E(with_metaclass(custom_class_repr('Gotcha!'))): pass

print(C, D, E)

prints:

Wahaha! Booyah! Gotcha!

Metaprogramming isn't something you generally need everyday—but when you need it, it really hits the spot!

add to array if it isn't there already

Taking Gumbo's idea, making the code work:

$array = array('111111','222222','3333333','4444','5555', 
'AAAAAA', 'BBBBBB', 'CCC', 'DDDDDDD', 'EEEEEEEE', 'FFFFFF', 'GGG',
'AAAAAA', 'BBBBBB', 'CCC', 'DDDDDDD', 'EEEEEEEE', 'FFFFFF', 'GGG',
'222222', 
'666666', '777777', 'HHHH');

print_r($array);

$keys= array();
foreach ($array as $k => $v){
    if (isset($v['value'])) {
        $keys[$v] = $k;
    }
}
$unique = array();
foreach ($keys as $key) {
    $unique[] = $array[$key];
}
print "<br><br>";
print_r($unique);

Gives this:

Array
(
    [0] => 111111
    [1] => 222222
    [2] => 3333333
    [3] => 4444
    [4] => 5555
    [5] => AAAAAA
    [6] => BBBBBB
    [7] => CCC
    [8] => DDDDDDD
    [9] => EEEEEEEE
    [10] => FFFFFF
    [11] => GGG
    [12] => AAAAAA
    [13] => BBBBBB
    [14] => CCC
    [15] => DDDDDDD
    [16] => EEEEEEEE
    [17] => FFFFFF
    [18] => GGG
    [19] => 222222
    [20] => 666666
    [21] => 777777
    [22] => HHHH
)

Array
(
    [0] => 111111
    [1] => 222222
    [2] => 3333333
    [3] => 4444
    [4] => 5555
    [5] => AAAAAA
    [6] => BBBBBB
    [7] => CCC
    [8] => DDDDDDD
    [9] => EEEEEEEE
    [10] => FFFFFF
    [11] => GGG
    [12] => 666666
    [13] => 777777
    [14] => HHHH
)

Change navbar text color Bootstrap

The thread you linked to does answer the question for you. You need to target the a elements themselves. E.g.

.nav.navbar-nav.navbar-right a {
    color: blue;
}

If that doesn't work, it just needs to be more specific. E.g.

.nav.navbar-nav.navbar-right li a {
    color: blue;
}

How do I get this javascript to run every second?

window.setTimeout(func,1000);

This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.

Reference

SQL "IF", "BEGIN", "END", "END IF"?

If this is MS Sql Server then what you have should work fine... In fact, technically, you don;t need the Begin & End at all, snce there's only one statement in the begin-End Block... (I assume @Classes is a table variable ?)

If @Term = 3
   INSERT INTO @Classes
    SELECT                  XXXXXX  
     FROM XXXX blah blah blah
-- -----------------------------

 -- This next should always run, if the first code did not throw an exception... 
 INSERT INTO @Classes    
 SELECT XXXXXXXX        
 FROM XXXXXX (more code)

What is App.config in C#.NET? How to use it?

Just adding one more point

Using app.config some how you can control application access, you want apply particular change to entire application use app config file and you can access the settings like below ConfigurationSettings.AppSettings["Key"]

How to find which columns contain any NaN value in Pandas dataframe

df.columns[df.isnull().any()].tolist()

it will return name of columns that contains null rows

How do I generate sourcemaps when using babel and webpack?

Minimal webpack config for jsx with sourcemaps:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: `./src/index.jsx` ,
  output: {
    path:  path.resolve(__dirname,"build"),
    filename: "bundle.js"
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

Running it:

Jozsefs-MBP:react-webpack-babel joco$ webpack -d
Hash: c75d5fb365018ed3786b
Version: webpack 1.13.2
Time: 3826ms
        Asset     Size  Chunks             Chunk Names
    bundle.js   1.5 MB       0  [emitted]  main
bundle.js.map  1.72 MB       0  [emitted]  main
    + 221 hidden modules
Jozsefs-MBP:react-webpack-babel joco$

Open directory using C

You should really post your code(a), but here goes. Start with something like:

    #include <stdio.h>
    #include <dirent.h>

    int main (int argc, char *argv[]) {
        struct dirent *pDirent;
        DIR *pDir;

        // Ensure correct argument count.

        if (argc != 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }

        // Ensure we can open directory.

        pDir = opendir (argv[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", argv[1]);
            return 1;
        }

        // Process each entry.

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }

        // Close directory and exit.

        closedir (pDir);
        return 0;
    }

You need to check in your case that args[1] is both set and refers to an actual directory. A sample run, with tmp is a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]

Note also that you have to pass a directory in, not a file. When I execute:

testprog tmp/file1.txt

I get:

Cannot open directory 'tmp/file1.txt'

That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1])) if the initial diropen fails).


(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.

Visual Studio window which shows list of methods

I have been using USysWare DPack since forever. It is very small and not intrusive so if all you want is a quick shortcut window showing list of methods of the current file you are using, it provides just that. Good thing is that the author is still active after more than 10 years just to keep providing the same features into latest VS release.

https://marketplace.visualstudio.com/items?itemName=SergeyM.DPack-16348

After installation, just use Alt + M to bring up the method list window. I prefer to show all members instead, but it's up to you.

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

In Tensorflow, get the names of all the Tensors in a graph

tf.all_variables() can get you the information you want.

Also, this commit made today in TensorFlow Learn that provides a function get_variable_names in estimator that you can use to retrieve all variable names easily.

Interview question: Check if one string is a rotation of other string

And now for something completely different.

If you want a really fast answer in some constrained context when strings are not rotation of one another

  • compute some character based checksum (like xoring all characters) on both strings. If signatures differ strings are not rotations of one another.

Agreed, it can fail, but it is very fast to say if strings don't match and if they match you can still use another algorithm like string concatenation to check.

Creating a SOAP call using PHP with an XML body

First off, you have to specify you wish to use Document Literal style:

$client = new SoapClient(NULL, array(
    'location' => 'https://example.com/path/to/service',
    'uri' => 'http://example.com/wsdl',
    'trace' => 1,
    'use' => SOAP_LITERAL)
);

Then, you need to transform your data into a SoapVar; I've written a simple transform function:

function soapify(array $data)
{
        foreach ($data as &$value) {
                if (is_array($value)) {
                        $value = soapify($value);
                }
        }

        return new SoapVar($data, SOAP_ENC_OBJECT);
}

Then, you apply this transform function onto your data:

$data = soapify(array(
    'Acquirer' => array(
        'Id' => 'MyId',
        'UserId' => 'MyUserId',
        'Password' => 'MyPassword',
    ),
));

Finally, you call the service passing the Data parameter:

$method = 'Echo';

$result = $client->$method(new SoapParam($data, 'Data'));

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

SET STATISTICS TIME ON

SELECT * 

FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;

SET STATISTICS TIME OFF;

And see the message tab it will look like this:

SQL Server Execution Times:

   CPU time = 0 ms,  elapsed time = 10 ms.

(778 row(s) affected)

SQL Server parse and compile time: 

   CPU time = 0 ms, elapsed time = 0 ms.

SQL Server : Arithmetic overflow error converting expression to data type int

declare @d real
set @d=1.0;
select @d*40000*(192+2)*20000+150000

Material effect on button with background color

Programmatically applying the colors:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

    ColorStateList colorStateListRipple = new ColorStateList(
            new int[][] {{0}},
            new int[] {Color.WHITE} // ripple color
            );

    RippleDrawable rippleDrawable = (RippleDrawable) myButton.getBackground();
    rippleDrawable.setColor(colorStateListRipple);
    myButton.setBackground(rippleDrawable); // applying the ripple color
}

ColorStateList colorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed}, // when pressed
                new int[]{android.R.attr.state_enabled}, // normal state color
                new int[]{} // normal state color
        },
        new int[]{
                Color.CYAN, // when pressed
                Color.RED, // normal state color
                Color.RED // normal state color
        }
);

ViewCompat.setBackgroundTintList(myButton, colorStateList); // applying the state colors

Excel VBA Loop on columns

Another method to try out. Also select could be replaced when you set the initial column into a Range object. Performance wise it helps.

Dim rng as Range

Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.

'-- here is your loop
i = 1
Do
   '-- do something: e.g. show the address of the column that you are currently in
   Msgbox rng.offset(0,i).Address 
   i = i + 1
Loop Until i > 10

** Two methods to get the column name using column number**

  • Split()

code

colName = Split(Range.Offset(0,i).Address, "$")(1)
  • String manipulation:

code

Function myColName(colNum as Long) as String
    myColName = Left(Range(0, colNum).Address(False, False), _ 
    1 - (colNum > 10)) 
End Function 

How to get post slug from post in WordPress?

Here is most advanced and updated version what cover many cases:

if(!function_exists('the_slug')):
    function the_slug($post_id=false, $echo=true) {
        global $product, $page;

        if(is_numeric($post_id) && $post_id == intval($post_id)) {} else {
            if(!is_object($post_id)){}else if(property_exists($post_id, 'ID')){
                $post_id = $post_id->ID;
            }
            if(empty($post_id) && property_exists($product, 'ID')) $post_id = $product->ID;
            if(empty($post_id)) $post_id =  get_the_ID();

            if(empty($post_id) && property_exists($page, 'ID')) $post_id =  $page->ID;
        }

        if(!empty($post_id))
            $slug = basename(get_permalink($post_id));
        else
            $slug = basename(get_permalink());
        do_action('before_slug', $slug);
        $slug = apply_filters('slug_filter', $slug);
        if( $echo ) echo $slug;
        do_action('after_slug', $slug);
        return $slug;
      }
endif;

This is collections from the best answers and few my updates.

Django gives Bad Request (400) when DEBUG = False

For me, I got this error by not setting USE_X_FORWARDED_HOST to true. From the docs:

This should only be enabled if a proxy which sets this header is in use.

My hosting service wrote explicitly in their documentation that this setting must be used, and I get this 400 error if I forget it.

Detect when browser receives file download

I have updated the below reference code. Add a proper download URL link and try this out.

_x000D_
_x000D_
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <style type="text/css">
            body {
              padding: 0;
              margin: 0;
            }

            svg:not(:root) {
              display: block;
            }

            .playable-code {
              background-color: #f4f7f8;
              border: none;
              border-left: 6px solid #558abb;
              border-width: medium medium medium 6px;
              color: #4d4e53;
              height: 100px;
              width: 90%;
              padding: 10px 10px 0;
            }

            .playable-canvas {
              border: 1px solid #4d4e53;
              border-radius: 2px;
            }

            .playable-buttons {
              text-align: right;
              width: 90%;
              padding: 5px 10px 5px 26px;
            }
        </style>
        
        <style type="text/css">
            .event-log {
    width: 25rem;
    height: 4rem;
    border: 1px solid black;
    margin: .5rem;
    padding: .2rem;
}

input {
    width: 11rem;
    margin: .5rem;
}

        </style>
        
        <title>XMLHttpRequest: progress event - Live_example - code sample</title>
    </head>
    <body>
        
            <div class="controls">
    <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
    <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
    <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
        
        
            <script>
                const xhrButtonSuccess = document.querySelector('.xhr.success');
const xhrButtonError = document.querySelector('.xhr.error');
const xhrButtonAbort = document.querySelector('.xhr.abort');
const log = document.querySelector('.event-log');

function handleEvent(e) {
if (e.type=='progress')
{log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred Received ${event.loaded} of ${event.total}\n`;
    }
else if (e.type=='loadstart')
{
log.textContent = log.textContent + `${e.type}: started\n`;
}
else if  (e.type=='error')
{
log.textContent = log.textContent + `${e.type}: error\n`;
}
else if (e.type=='loadend')
{
log.textContent = log.textContent + `${e.type}: completed\n`;
}

}

function addListeners(xhr) {
    xhr.addEventListener('loadstart', handleEvent);
    xhr.addEventListener('load', handleEvent);
    xhr.addEventListener('loadend', handleEvent);
    xhr.addEventListener('progress', handleEvent);
    xhr.addEventListener('error', handleEvent);
    xhr.addEventListener('abort', handleEvent);
}

function runXHR(url) {
    log.textContent = '';

    const xhr = new XMLHttpRequest();
    
   var request = new XMLHttpRequest();
   addListeners(request);
        request.open('GET', url, true);
        request.responseType = 'blob';
        request.onload = function (e) {
        var data = request.response;
        var blobUrl = window.URL.createObjectURL(data);
        var downloadLink = document.createElement('a');
        downloadLink.href = blobUrl;
        downloadLink.download ='download.zip';
        downloadLink.click();
        };
        request.send();
        return request
}

xhrButtonSuccess.addEventListener('click', () => {
    runXHR('https://abbbbbc.com/download.zip');
});

xhrButtonError.addEventListener('click', () => {
    runXHR('http://i-dont-exist');
});

xhrButtonAbort.addEventListener('click', () => {
    runXHR('https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json').abort();
});
            </script>
        
    </body>
</html>
Return to post
_x000D_
_x000D_
_x000D_

Reference:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/progress_event#live_example

Adding an assets folder in Android Studio

right click on app-->select

New-->Select Folder-->then click on Assets Folder

How to iterate through a DataTable

You can also use linq extensions for DataSets:

var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
    TextBox1.Text = imgPath;
}

Store mysql query output into a shell variable

Another example when the table name or database contains unsupported characters such as a space, or '-'

db='data-base'

db_d=''
db_d+='`'
db_d+=$db
db_d+='`'

myvariable=`mysql --user=$user --password=$password -e "SELECT A, B, C FROM $db_d.table_a;"`

How to set time to midnight for current day?

You can use the Date property of the DateTime object - eg

DateTime midnight = DateTime.Now.Date;

So your code example becomes

private DateTime _Begin = DateTime.Now.Date;
public DateTime Begin { get { return _Begin; } set { _Begin = value; } }

PS. going back to your original code setting the hours to 12 will give you time of noon for the current day, so instead you could have used 0...

var now = DateTime.Now;
new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

Tooltip on image

I am set Tooltips On My Working Project That Is 100% Working

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
.tooltip {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border-bottom: 1px dotted black;_x000D_
}_x000D_
_x000D_
.tooltip .tooltiptext {_x000D_
  visibility: hidden;_x000D_
  width: 120px;_x000D_
  background-color: black;_x000D_
  color: #fff;_x000D_
  text-align: center;_x000D_
  border-radius: 6px;_x000D_
  padding: 5px 0;_x000D_
_x000D_
  /* Position the tooltip */_x000D_
  position: absolute;_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
  visibility: visible;_x000D_
}_x000D_
.size_of_img{_x000D_
width:90px}_x000D_
</style>_x000D_
_x000D_
<body style="text-align:center;">_x000D_
_x000D_
<p>Move the mouse over the text below:</p>_x000D_
_x000D_
<div class="tooltip"><img class="size_of_img" src="https://babeltechreviews.com/wp-content/uploads/2018/07/rendition1.img_.jpg" alt="Image 1" /><span class="tooltiptext">grewon.pdf</span></div>_x000D_
_x000D_
<p>Note that the position of the tooltip text isn't very good. Check More Position <a href="https://www.w3schools.com/css/css_tooltip.asp">GO</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to browse localhost on Android device?

Combining a few of the answers above plus one other additional item solved the problem for me.

  1. As mentioned above, turn your firewall off [add a specific rule allowing the incoming connections to the port once you've successfully connected]
  2. Find you IP address via ipconfig as mentioned above
  3. Verify that your webserver is binding to the ip address found above and not just 127.0.0.1. Test this locally by browsing to the ip address and port. E.g. 192.168.1.113:8888. If it's not, find a solution. E.g. https://groups.google.com/forum/?fromgroups=#!topic/google-appengine-java/z4rtqkKO2hg
  4. Now test it out on your Android device. Note that I also turned off my data connection and exclusively used a wifi connection on my Android.

Getting path relative to the current working directory?

Thanks to the other answers here and after some experimentation I've created some very useful extension methods:

public static string GetRelativePathFrom(this FileSystemInfo to, FileSystemInfo from)
{
    return from.GetRelativePathTo(to);
}

public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to)
{
    Func<FileSystemInfo, string> getPath = fsi =>
    {
        var d = fsi as DirectoryInfo;
        return d == null ? fsi.FullName : d.FullName.TrimEnd('\\') + "\\";
    };

    var fromPath = getPath(from);
    var toPath = getPath(to);

    var fromUri = new Uri(fromPath);
    var toUri = new Uri(toPath);

    var relativeUri = fromUri.MakeRelativeUri(toUri);
    var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

    return relativePath.Replace('/', Path.DirectorySeparatorChar);
}

Important points:

  • Use FileInfo and DirectoryInfo as method parameters so there is no ambiguity as to what is being worked with. Uri.MakeRelativeUri expects directories to end with a trailing slash.
  • DirectoryInfo.FullName doesn't normalize the trailing slash. It outputs whatever path was used in the constructor. This extension method takes care of that for you.

How do check if a PHP session is empty?

The best practice is to check if the array key exists using the built-in array_key_exists function.

Line Break in XML?

In XML a line break is a normal character. You can do this:

<xml>
  <text>some text
with
three lines</text>
</xml>

and the contents of <text> will be

some text
with
three lines

If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n won't work, on the other hand, because XML has no escape sequences*.


* Note that &#xA; is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.

This is where neither &#xA; nor things like \n will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.


Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br> tags to force line breaks on screen.

Here is a JavaScript function that inserts <br> into a multi-line string:

function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }

Alternatively you can force line breaks at new line characters with CSS:

div.lines {
    white-space: pre-line;
}

How can I find my php.ini on wordpress?

Open .htaccess file in a code editor like sublime text and then add..

php_value upload_max_filesize 1000M
php_value post_max_size 2000M
php_value memory_limit 3000M
php_value max_execution_time 1800
php_value max_input_time 180

hope it helps..............it did for me.

Bundle ID Suffix? What is it?

The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.

It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.

An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:

com.awesomeapps.thebestapp

In this case the suffix is thebestapp.

Enum ToString with user friendly strings

I use a generic class to store the enum/description pairs and a nested helper class to get the description.

The enum:

enum Status { Success, Fail, Pending }

The generic class:

Note: Since a generic class cannot be constrained by an enum I am constraining by struct instead and checking for enum in the constructor.

public class EnumX<T> where T : struct
{
    public T Code { get; set; }
    public string Description { get; set; }

    public EnumX(T code, string desc)
    {
        if (!typeof(T).IsEnum) throw new NotImplementedException();

        Code = code;
        Description = desc;
    }

    public class Helper
    {
        private List<EnumX<T>> codes;

        public Helper(List<EnumX<T>> codes)
        {
            this.codes = codes;
        }

        public string GetDescription(T code)
        {
            EnumX<T> e = codes.Where(c => c.Code.Equals(code)).FirstOrDefault();
            return e is null ? "Undefined" : e.Description;
        }
    }
}

Usage:

EnumX<Status>.Helper StatusCodes = new EnumX<Status>.Helper(new List<EnumX<Status>>()
        {
            new EnumX<Status>(Status.Success,"Operation was successful"),
            new EnumX<Status>(Status.Fail,"Operation failed"),
            new EnumX<Status>(Status.Pending,"Operation not complete. Please wait...")
        });

        Console.WriteLine(StatusCodes.GetDescription(Status.Pending));

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

Mapping composite keys using EF code first

For Mapping Composite primary key using Entity framework we can use two approaches.

1) By Overriding the OnModelCreating() Method

For ex: I have the model class named VehicleFeature as shown below.

public class VehicleFeature
{
    public int VehicleId { get; set; }
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

The Code in my DBContext would be like ,

public class VegaDbContext : DbContext
{
    public DbSet<Make> Makes{get;set;}

    public DbSet<Feature> Features{get;set;}
    public VegaDbContext(DbContextOptions<VegaDbContext> options):base(options)        
    {           

    }
    // we override the OnModelCreating method here.
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<VehicleFeature>().HasKey(vf=> new {vf.VehicleId, vf.FeatureId});
    }
}

2) By Data Annotations.

public class VehicleFeature
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
    [Key]
    public int VehicleId { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    [Key]
    public int FeatureId{get;set;}
    public Vehicle Vehicle{get;set;}
    public Feature Feature{get;set;}
}

Please refer the below links for the more information.

1) https://msdn.microsoft.com/en-us/library/jj591617(v=vs.113).aspx

2) How to add a composite unique key using EF 6 Fluent Api?

How do I vertical center text next to an image in html/css?

Since most of the answers to this question are between 2009 and 2014 (except for a comment in 2018), there should be an update to this.

I found a solution to the wrap-text problem brought up by Spongman on Jun 11 '14 at 23:20. He has an example here: jsfiddle.net/vPpD4

If you add the following in the CSS under the div tag in the jsfiddle.net/vPpD4 example, you get the desired wrap-text effect that I think Spongman was asking about. I don't know how far back this is applicable, but this works in all of the current (as of Dec 2020/Jan 2021) browsers available for Windows computers. Note: I have not tested this on the Apple Safari browser. I have also not tested this on any mobile devices.

    div img { 
        float: left;
    }
    .clearfix::after {
        content: ""; 
        clear: both;
        display: table;
    }

I also added a border around the image, just so that the reader will understand where the edge of the image is and why the text wraps as it does. The resulting example looks is here: http://jsfiddle.net/tqg7hLzk/

How to execute a Windows command on a remote PC?

This can be done by using PsExec which can be downloaded here

psexec \\computer_name -u username -p password ipconfig

If this isn't working try doing this :-

  1. Open RegEdit on your remote server.
  2. Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System.

  3. Add a new DWORD value called LocalAccountTokenFilterPolicy

  4. Set its value to 1.
  5. Reboot your remote server.
  6. Try running PSExec again from your local server.

How to check if a windows form is already open, and close it if it is?

Try this, it will work :

//inside main class
Form1 Fm1 = new Form1();<br>

//in button click
if (Fm1.IsDisposed)
{
    Fm1 = new Form();
}
Fm1.Show();
Fm1.BringToFront();
Fm1.Activate();

Trim string in JavaScript?

There are a lot of implementations that can be used. The most obvious seems to be something like this:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

" foo bar ".trim();  // "foo bar"

estimating of testing effort as a percentage of development time

Some years ago, in a safety critical field, I have heard something like one day for unit testing ten lines of code.

I have also observed 50% of effort for development and 50% for testing (not only unit testing).

How to mount a single file in a volume

All above answers are Correct.

but one thing that I found really helpful is that mounted file should exist inside docker host in advance otherwise docker will create a directory instead.

for example:

/a/file/inside/host/hostFile.txt:/a/file/inside/container/containerFile.txt

hostFile.txt should exist in advance. otherwise you will receive this error: containerFile.txt is a directory

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you wrap each template in a script tag, eg:

<script id="about.html" type="text/ng-template">
<div>
    <h3>About</h3>
    This is the About page
    Its cool!
</div>
</script>

Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.

Add the code that this guy wrote to change the angular $templatecache service - its only a small piece of code and it works: Vojta Jina's Gist

Its the $http.get that should be changed to use your bundle file:

allTplPromise = $http.get('templates/templateBundle.min.html').then(

Your routes templateUrl should look like this:

        $routeProvider.when(
            "/about", {
                controller: "",
                templateUrl: "about.html"
            }
        );

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

Unknown version of Tomcat was specified in Eclipse

Having installed tomcat with brew the solution for me was:

sudo chmod -R 777 /usr/local/Cellar/tomcat/<your_version>

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

Proper way to assert type of variable in Python

Doing type('') is effectively equivalent to str and types.StringType

so type('') == str == types.StringType will evaluate to "True"

Note that Unicode strings which only contain ASCII will fail if checking types in this way, so you may want to do something like assert type(s) in (str, unicode) or assert isinstance(obj, basestring), the latter of which was suggested in the comments by 007Brendan and is probably preferred.

isinstance() is useful if you want to ask whether an object is an instance of a class, e.g:

class MyClass: pass

print isinstance(MyClass(), MyClass) # -> True
print isinstance(MyClass, MyClass()) # -> TypeError exception

But for basic types, e.g. str, unicode, int, float, long etc asking type(var) == TYPE will work OK.

Where can I find the TypeScript version installed in Visual Studio?

The TypeScript team sorted this out in Visual Studio 2017 versions 15.3 and later, including the free Community edition.

How to See Which TypeScript Versions are Installed in Visual Studio

All you now need do is to go to project properties of any TypeScript Visual Studio project (right-click the project file in Solution Explorer/Properties), then go to the TypeScript Build tab on the left-hand side. This has a 'Typescript version' dropdown that shows you the version the project is using, and if you open it the dropdown shows you ALL versions of TypeScript currently installed in Visual Studio.

The actual installs are currently at C:\Program Files (x86)\Microsoft SDKs\TypeScript and then subfolders by version number, at least on Win10 on my computer. If you want to see the exact version (e.g. 2.8.3 rather than just 2.8) you can find the appropriate tsc.exe in here and look at its properties (Details tab in right-click/Properties in File Explorer).

How to Install Specific TypeScript Version

If you want to install a specific version of TypeScript for Visual Studio, you can download older versions from the Details->Releases section of the TypeScript SDK for Visual Studio 2017 Downloads page. You can verify that the version has been installed either with the 'Typescript version' dropdown in VS or inspecting the C:\Program Files (x86)\Microsoft SDKs\TypeScript folder.