Programs & Examples On #Managed bean

Managed bean is a Java EE specific term for Javabean classes which are designed to act as a controller in some MVC application. They are often referred in context of JSF and CDI.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:

WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133

Then at the injection point I got the error:

Unsatisfied dependencies for type ... with qualifiers @Default

The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into

JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml

NOTE: EAP 6.4.x already have this fixed

Get JSF managed bean by name in any Servlet related class

In a servlet based artifact, such as @WebServlet, @WebFilter and @WebListener, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped by:

Bean bean = (Bean) request.getAttribute("beanName");

and @ManagedBean @SessionScoped by:

Bean bean = (Bean) request.getSession().getAttribute("beanName");

and @ManagedBean @ApplicationScoped by:

Bean bean = (Bean) getServletContext().getAttribute("beanName");

Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null. You'd then need to manually create the bean and use setAttribute("beanName", bean).


If you're able to use CDI @Named instead of the since JSF 2.3 deprecated @ManagedBean, then it's even more easy, particularly because you don't anymore need to manually create the beans:

@Inject
private Bean bean;

Note that this won't work when you're using @Named @ViewScoped because the bean can only be identified by JSF view state and that's only available when the FacesServlet has been invoked. So in a filter which runs before that, accessing an @Injected @ViewScoped will always throw ContextNotActiveException.


Only when you're inside @ManagedBean, then you can use @ManagedProperty:

@ManagedProperty("#{bean}")
private Bean bean;

Note that this doesn't work inside a @Named or @WebServlet or any other artifact. It really works inside @ManagedBean only.


If you're not inside a @ManagedBean, but the FacesContext is readily available (i.e. FacesContext#getCurrentInstance() doesn't return null), you can also use Application#evaluateExpressionGet():

FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);

which can be convenienced as follows:

@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
    FacesContext context = FacesContext.getCurrentInstance();
    return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}

and can be used as follows:

Bean bean = findBean("bean");

See also:

Invoke JSF managed bean action on page load

Another easy way is to use fire the method before the view is rendered. This is better than postConstruct because for sessionScope, postConstruct will fire only once every session. This will fire every time the page is loaded. This is ofcourse only for JSF 2.0 and not for JSF 1.2.

This is how to do it -

<html xmlns:f="http://java.sun.com/jsf/core">
      <f:metadata>
          <f:event type="preRenderView" listener="#{myController.onPageLoad}"/>
      </f:metadata>
</html>

And in the myController.java

 public void onPageLoad(){
    // Do something
 }

EDIT - Though this is not a solution for the question on this page, I add this just for people using higher versions of JSF.

JSF 2.2 has a new feature which performs this task using viewAction.

<f:metadata>
    <f:viewAction action="#{myController.onPageLoad}" />
</f:metadata>

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

For 1. topic (Target Unreachable, identifier 'bean' resolved to null);

I checked valuable answers the @BalusC and the other sharers but I exceed the this problem like this on my scenario. After the creating a new xhtml with different name and creating bean class with different name then I wrote (not copy-paste) the codes step by step to the new bean class and new xhtml file.

Target Unreachable, identifier resolved to null in JSF 2.2

I solved this problem.

My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.

Thanks @PM77-1


How to choose the right bean scope?

Introduction

It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.


@Request/View/Flow/Session/ApplicationScoped

A @RequestScoped bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null/void without any navigation/redirect. A @FlowScoped bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped bean lives as long as the established HTTP session. An @ApplicationScoped bean lives as long as the web application runs. Note that the CDI @Model is basically a stereotype for @Named @RequestScoped, so same rules apply.

Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped for simple and non-ajax forms/presentations. Use @ViewScoped for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.

Abusing an @ApplicationScoped bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped bean for request, session or application scoped data, and abusing a @SessionScoped bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.

Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty in case of JSF managed beans or @Inject in case of CDI managed beans.

See also:


@CustomScoped/NoneScoped/Dependent

It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped and @NoneScoped, which are rarely used in real world. The @CustomScoped must refer a custom Map<K, Bean> implementation in some broader scope which has overridden Map#put() and/or Map#get() in order to have more fine grained control over bean creation and/or destroy.

The JSF @NoneScoped and CDI @Dependent basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped or @Dependent is injected in a @SessionScoped, then it will live as long as the @SessionScoped bean.

See also:


Flash scope

As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.

This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped. The flash scope is only available as a map via ExternalContext#getFlash() in managed beans and #{flash} in EL.

See also:

BeanFactory vs ApplicationContext

In summary:

The ApplicationContext includes all functionality of the BeanFactory. It is generally recommended to use the former.

There are some limited situations such as in a Mobile application, where memory consumption might be critical.

In that scenarios, It can be justifiable to use the more lightweight BeanFactory. However, in the most enterprise applications, the ApplicationContext is what you will want to use.

For more, see my blog post:

Difference between BeanFactory and ApplicationContext in Spring – The java spring blog from the basics

What is the difference between a JavaBean and a POJO?

Java beans are special type of POJOs.

Specialities listed below with reason

enter image description here

Getting list of pixel values from PIL

Not PIL, but scipy.misc.imread might still be interesting:

import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)

gives

(480, 640, 3)

so it is (height, width, channels). So you can iterate over it by

for y in range(im.shape[0]):
    for x in range(im.shape[1]):
        color = tuple(im[y][x])
        r, g, b = color

Splitting a string into separate variables

Foreach-object operation statement:

$a,$b = 'hi.there' | foreach split .
$a,$b

hi
there

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

How to find all occurrences of a substring?

When looking for a large amount of key words in a document, use flashtext

from flashtext import KeywordProcessor
words = ['test', 'exam', 'quiz']
txt = 'this is a test'
kwp = KeywordProcessor()
kwp.add_keywords_from_list(words)
result = kwp.extract_keywords(txt, span_info=True)

Flashtext runs faster than regex on large list of search words.

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

I ran into this exact same error message. I tried Aditi's example, and then I realized what the real issue was. (Because I had another apiEndpoint making a similar call that worked fine.) In this case The object in my list had not had an interface extracted from it yet. So because I apparently missed a step, when it went to do the bind to the

List<OfthisModelType>

It failed to deserialize.

If you see this issue, check to see if that could be the issue.

matplotlib: how to draw a rectangle on image

There is no need for subplots, and pyplot can display PIL images, so this can be simplified further:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image

im = Image.open('stinkbug.png')

# Display the image
plt.imshow(im)

# Get the current reference
ax = plt.gca()

# Create a Rectangle patch
rect = Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)

Or, the short version:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image

# Display the image
plt.imshow(Image.open('stinkbug.png'))

# Add the patch to the Axes
plt.gca().add_patch(Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none'))

Trigger css hover with JS

I don't think what your asking is possible.

See: Hover Item with JQuery

Basically, adding a class is the only way to accomplish this that I am aware of.

How to select all the columns of a table except one column?

You can retrieve the list of column name by simple query and then remove those column by apply where query like this.

SELECT * FROM (
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TableName'
) AS allColumns
WHERE allColumns.COLUMN_NAME NOT IN ('unwantedCol1', 'unwantedCol2')

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

This is what I've used:

::Date Variables - replace characters that are not legal as part of filesystem file names (to produce name like "backup_04.15.08.7z")
SET DT=%date%
SET DT=%DT:/=.%
SET DT=%DT:-=.%

If you want further ideas for automating backups to 7-Zip archives, I have a free/open project you can use or review for ideas: http://wittman.org/ziparcy/

Uninstall mongoDB from ubuntu

use sudo with the command:

sudo apt-get remove --purge mongodb  
apt-get autoremove --purge mongodb  

Testing the type of a DOM element in JavaScript

roenving is correct BUT you need to change the test to:

if(element.nodeType == 1) {
//code
}

because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp

Converting time stamps in excel to dates

This worked for me:

=(col_name]/60/60/24)+(col_name-1)

ASP.NET Web Application Message Box

Or create a method like this in your solution:

public static class MessageBox {
    public static void Show(this Page Page, String Message) {
       Page.ClientScript.RegisterStartupScript(
          Page.GetType(),
          "MessageBox",
          "<script language='javascript'>alert('" + Message + "');</script>"
       );
    }
}

Then you can use it like:

MessageBox.Show("Here is my message");

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

Wait for all promises to resolve

You can use "await" in an "async function".

app.controller('MainCtrl', async function($scope, $q, $timeout) {
  ...
  var all = await $q.all([one.promise, two.promise, three.promise]); 
  ...
}

NOTE: I'm not 100% sure you can call an async function from a non-async function and have the right results.

That said this wouldn't ever be used on a website. But for load-testing/integration test...maybe.

Example code:

_x000D_
_x000D_
async function waitForIt(printMe) {_x000D_
  console.log(printMe);_x000D_
  console.log("..."+await req());_x000D_
  console.log("Legendary!")_x000D_
}_x000D_
_x000D_
function req() {_x000D_
  _x000D_
  var promise = new Promise(resolve => {_x000D_
    setTimeout(() => {_x000D_
      resolve("DARY!");_x000D_
    }, 2000);_x000D_
    _x000D_
  });_x000D_
_x000D_
    return promise;_x000D_
}_x000D_
_x000D_
waitForIt("Legen-Wait For It");
_x000D_
_x000D_
_x000D_

How to create javascript delay function

You do not need to use an anonymous function with setTimeout. You can do something like this:

setTimeout(doSomething, 3000);

function doSomething() {
   //do whatever you want here
}

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

Search a string in a file and delete it from this file by Shell Script

sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source usually doesn't work: sed '/pattern/d' file > file so make a copy before trying out, if you doubt it.

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Split a string into array in Perl

Just use /\s+/ against '' as a splitter. In this case all "extra" blanks were removed. Usually this particular behaviour is required. So, in you case it will be:

my $line = "file1.gz file1.gz file3.gz";
my @abc = split(/\s+/, $line);

How to generate gcc debug symbol outside the build target?

Compile with debug information:

gcc -g -o main main.c

Separate the debug information:

objcopy --only-keep-debug main main.debug

or

cp main main.debug
strip --only-keep-debug main.debug

Strip debug information from origin file:

objcopy --strip-debug main

or

strip --strip-debug --strip-unneeded main

debug by debuglink mode:

objcopy --add-gnu-debuglink main.debug main
gdb main

You can also use exec file and symbol file separatly:

gdb -s main.debug -e main

or

gdb
(gdb) exec-file main
(gdb) symbol-file main.debug

For details:

(gdb) help exec-file
(gdb) help symbol-file

Ref:
https://sourceware.org/gdb/onlinedocs/gdb/Files.html#Files https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html

Android: No Activity found to handle Intent error? How it will resolve

Generally to avoid this kind of exceptions, you will need to surround your code by try and catch like this

try{

// your intent here

} catch (ActivityNotFoundException e) {
// show message to user 
}

How to load local file in sc.textFile, instead of HDFS

You do not have to use sc.textFile(...) to convert local files into dataframes. One of options is, to read a local file line by line and then transform it into Spark Dataset. Here is an example for Windows machine in Java:

StructType schemata = DataTypes.createStructType(
            new StructField[]{
                    createStructField("COL1", StringType, false),
                    createStructField("COL2", StringType, false),
                    ...
            }
    );

String separator = ";";
String filePath = "C:\\work\\myProj\\myFile.csv";
SparkContext sparkContext = new SparkContext(new SparkConf().setAppName("MyApp").setMaster("local"));
JavaSparkContext jsc = new JavaSparkContext (sparkContext );
SQLContext sqlContext = SQLContext.getOrCreate(sparkContext );

List<String[]> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
    String line;
    while ((line = br.readLine()) != null) {
      String[] vals = line.split(separator);
      result.add(vals);
    }
 } catch (Exception ex) {
       System.out.println(ex.getMessage());
       throw new RuntimeException(ex);
  }
  JavaRDD<String[]> jRdd = jsc.parallelize(result);
  JavaRDD<Row> jRowRdd = jRdd .map(RowFactory::create);
  Dataset<Row> data = sqlContext.createDataFrame(jRowRdd, schemata);

Now you can use dataframe data in your code.

How do I set response headers in Flask?

Use make_response of Flask something like

@app.route("/")
def home():
    resp = make_response("hello") #here you could use make_response(render_template(...)) too
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

From flask docs,

flask.make_response(*args)

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

Iterating over each line of ls -l output

It depends what you want to do with each line. awk is a useful utility for this type of processing. Example:

 ls -l | awk '{print $9, $5}'

.. on my system prints the name and size of each item in the directory.

How to change a text with jQuery

Something like this should do the trick:

$(document).ready(function() {
    $('#toptitle').text(function(i, oldText) {
        return oldText === 'Profil' ? 'New word' : oldText;
    });
});

This only replaces the content when it is Profil. See text in the jQuery API.

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I had the same issue and put double quotes around the username and password and it worked: create public database link "opps" identified by "opps" using 'TEST';

When are static variables initialized?

The static variable can be intialize in the following three ways as follow choose any one you like

  1. you can intialize it at the time of declaration
  2. or you can do by making static block eg:

    static {
            // whatever code is needed for initialization goes here
        }
    
  3. There is an alternative to static blocks — you can write a private static method

    class name {
        public static varType myVar = initializeVar();
    
        private static varType initializeVar() {
            // initialization code goes here
        }
    }
    

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

.Cells(.Rows.Count,"A").End(xlUp).row

I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:

.Cells(Rows.Count,"A").End(xlUp).row

Before the Cells, you can write your worksheet name, for example:

Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row

The worksheet name is not necessary when you operate on the same worksheet.

How to make an app's background image repeat

There is a property in the drawable xml to do it. android:tileMode="repeat"

See this site: http://androidforbeginners.blogspot.com/2010/06/how-to-tile-background-image-in-android.html

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

The error message says your DbContext(LogManagerContext ) needs a constructor which accepts a DbContextOptions. But i couldn't find such a constructor in your DbContext. So adding below constructor probably solves your problem.

    public LogManagerContext(DbContextOptions options) : base(options)
    {
    }

Edit for comment

If you don't register IHttpContextAccessor explicitly, use below code:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

Toggle show/hide on click with jQuery

$(document).ready( function(){
  $("button").click(function(){
    $("p").toggle(1000,'linear');
  });
});

Live Demo

Do I use <img>, <object>, or <embed> for SVG files?

If you need your SVGs to be fully styleable with CSS they have to be inline in the DOM. This can be achieved through SVG injection, which uses Javascript to replace a HTML element (usually an <img> element) with the contents of an SVG file after the page has loaded.

Here is a minimal example using SVGInject:

<html>
<head>
  <script src="svg-inject.min.js"></script>
</head>
<body>
  <img src="image.svg" onload="SVGInject(this)" />
</body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the file provided in the src attribute. This works with all browsers that support SVG.

Disclaimer: I am the co-author of SVGInject

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

I found this implementation very easy to use. Also has a generous BSD-style license:

jsSHA: https://github.com/Caligatio/jsSHA

I needed a quick way to get the hex-string representation of a SHA-256 hash. It only took 3 lines:

var sha256 = new jsSHA('SHA-256', 'TEXT');
sha256.update(some_string_variable_to_hash);
var hash = sha256.getHash("HEX");

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

I made the steps 1, 2, 3 and the 7. and I put the folder with the class files in the project build path (right click, properties, java build path, libraries, add class folder, create new folder, advanced>>, link to folder in the file system, browse,...) then restart eclipse.

Drop multiple tables in one shot in MySQL

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below

    • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
    • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  2. Copy and paste the table names from the result set and paste it after the DROP command.

CSS Flex Box Layout: full-width row and columns

This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container has display: flex; and flex-direction: column;, while the columns have flex: 3; and flex: 2; (where "One value, unitless number" determines the flex-grow property) per MDN flex docs.

_x000D_
_x000D_
#Container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
  flex: 3;_x000D_
  background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div class="Content">_x000D_
    <div id="Detail"></div>_x000D_
    <div id="ThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

json_encode sparse PHP array as JSON array, not JSON object

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

$indexedOnly = array();

foreach ($associative as $row) {
    $indexedOnly[] = array_values($row);
}

json_encode($indexedOnly);

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

Are string.Equals() and == operator really same?

There are plenty of descriptive answers here so I'm not going to repeat what has already been said. What I would like to add is the following code demonstrating all the permutations I can think of. The code is quite long due to the number of combinations. Feel free to drop it into MSTest and see the output for yourself (the output is included at the bottom).

This evidence supports Jon Skeet's answer.

Code:

[TestMethod]
public void StringEqualsMethodVsOperator()
{
    string s1 = new StringBuilder("string").ToString();
    string s2 = new StringBuilder("string").ToString();

    Debug.WriteLine("string a = \"string\";");
    Debug.WriteLine("string b = \"string\";");

    TryAllStringComparisons(s1, s2);

    s1 = null;
    s2 = null;

    Debug.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", 20)));
    Debug.WriteLine(string.Empty);
    Debug.WriteLine("string a = null;");
    Debug.WriteLine("string b = null;");

    TryAllStringComparisons(s1, s2);
}
private void TryAllStringComparisons(string s1, string s2)
{
    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- string.Equals --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => string.Equals(a, b), s1, s2);
    Try((a, b) => string.Equals((object)a, b), s1, s2);
    Try((a, b) => string.Equals(a, (object)b), s1, s2);
    Try((a, b) => string.Equals((object)a, (object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- object.Equals --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => object.Equals(a, b), s1, s2);
    Try((a, b) => object.Equals((object)a, b), s1, s2);
    Try((a, b) => object.Equals(a, (object)b), s1, s2);
    Try((a, b) => object.Equals((object)a, (object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- a.Equals(b) --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => a.Equals(b), s1, s2);
    Try((a, b) => a.Equals((object)b), s1, s2);
    Try((a, b) => ((object)a).Equals(b), s1, s2);
    Try((a, b) => ((object)a).Equals((object)b), s1, s2);

    Debug.WriteLine(string.Empty);
    Debug.WriteLine("-- a == b --");
    Debug.WriteLine(string.Empty);
    Try((a, b) => a == b, s1, s2);
#pragma warning disable 252
    Try((a, b) => (object)a == b, s1, s2);
#pragma warning restore 252
#pragma warning disable 253
    Try((a, b) => a == (object)b, s1, s2);
#pragma warning restore 253
    Try((a, b) => (object)a == (object)b, s1, s2);
}
public void Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, T1 in1, T2 in2)
{
    T3 out1;

    Try(tryFunc, e => { }, in1, in2, out out1);
}
public bool Try<T1, T2, T3>(Expression<Func<T1, T2, T3>> tryFunc, Action<Exception> catchFunc, T1 in1, T2 in2, out T3 out1)
{
    bool success = true;
    out1 = default(T3);

    try
    {
        out1 = tryFunc.Compile()(in1, in2);
        Debug.WriteLine("{0}: {1}", tryFunc.Body.ToString(), out1);
    }
    catch (Exception ex)
    {
        Debug.WriteLine("{0}: {1} - {2}", tryFunc.Body.ToString(), ex.GetType().ToString(), ex.Message);
        success = false;
        catchFunc(ex);
    }

    return success;
}

Output:

string a = "string";
string b = "string";

-- string.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- object.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- a.Equals(b) --

a.Equals(b): True
a.Equals(Convert(b)): True
Convert(a).Equals(b): True
Convert(a).Equals(Convert(b)): True

-- a == b --

(a == b): True
(Convert(a) == b): False
(a == Convert(b)): False
(Convert(a) == Convert(b)): False
--------------------

string a = null;
string b = null;

-- string.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- object.Equals --

Equals(a, b): True
Equals(Convert(a), b): True
Equals(a, Convert(b)): True
Equals(Convert(a), Convert(b)): True

-- a.Equals(b) --

a.Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
a.Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(b): System.NullReferenceException - Object reference not set to an instance of an object.
Convert(a).Equals(Convert(b)): System.NullReferenceException - Object reference not set to an instance of an object.

-- a == b --

(a == b): True
(Convert(a) == b): True
(a == Convert(b)): True
(Convert(a) == Convert(b)): True

How to check if a float value is a whole number

You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:

r = int(12000**(1/3.0))
print r*r*r # 10648

How do I increase memory on Tomcat 7 when running as a Windows Service?

The answer to my own question is, I think, to use tomcat7.exe:

cd $CATALINA_HOME
.\bin\service.bat install tomcat
.\bin\tomcat7.exe //US//tomcat7 --JvmMs=512 --JvmMx=1024 --JvmSs=1024

Also, you can launch the UI tool mentioned by BalusC without the system tray or using the installer with tomcat7w.exe

.\bin\tomcat7w.exe //ES//tomcat

An additional note to this:

Setting the --JvmXX parameters (through the UI tool or the command line) may not be enough. You may also need to specify the JVM memory values explicitly. From the command line it may look like this:

bin\tomcat7w.exe //US//tomcat7 --JavaOptions=-Xmx=1024;-Xms=512;..

Be careful not to override the other JavaOption values. You can try updating bin\service.bat or use the UI tool and append the java options (separate each value with a new line).

Please initialize the log4j system properly. While running web service

If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.

static Logger log = Logger.getLogger(MyClass.class);

Thanks,

Put search icon near textbox using bootstrap

You can do it in pure CSS using the :after pseudo-element and getting creative with the margins.

Here's an example, using Font Awesome for the search icon:

_x000D_
_x000D_
.search-box-container input {_x000D_
  padding: 5px 20px 5px 5px;_x000D_
}_x000D_
_x000D_
.search-box-container:after {_x000D_
    content: "\f002";_x000D_
    font-family: FontAwesome;_x000D_
    margin-left: -25px;_x000D_
    margin-right: 25px;_x000D_
}
_x000D_
<!-- font awesome -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="search-box-container">_x000D_
  <input type="text" placeholder="Search..."  />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Homebrew: Could not symlink, /usr/local/bin is not writable

For those who are looking for /usr/local/sbin is not writable error:

UPDATE: It could be /usr/local/someOtherFolderName e.g /usr/local/include. You just need to create that folder with:

  • sudo mkdir someOtherFolderName

First create the sbin folder, note that this requires sudo privileges

  • cd /usr/local

  • sudo mkdir sbin

  • sudo chown -R $(whoami) $(brew --prefix)/*

  • brew link yourPackageName

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

This error is caused by a line of code in /usr/share/phpmyadmin/libraries/sql.lib.php.

It seems when I installed phpMyAdmin using apt, the version in the repository (phpMyAdmin v4.6.6) is not fully compatible with PHP 7.2. There is a newer version available on the official website (v4.8 as of writing), which fixes these compatibility issues with PHP 7.2.

You can download the latest version and install it manually or wait for the repositories to update with the newer version.

Alternatively, you can make a small change to sql.lib.php to fix the error.

Firstly, backup sql.lib.php before editing.

1-interminal:

sudo cp /usr/share/phpmyadmin/libraries/sql.lib.php /usr/share/phpmyadmin/libraries/sql.lib.php.bak

2-Edit sql.lib.php. Using vi:

sudo vi /usr/share/phpmyadmin/libraries/sql.lib.php

OR Using nano:

sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php

Press CTRL + W (for nano) or ? (for vi/vim) and search for (count($analyzed_sql_results['select_expr'] == 1)

Replace it with ((count($analyzed_sql_results['select_expr']) == 1)

Save file and exit. (Press CTRL + X, press Y and then press ENTER for nano users / (for vi/vim) hit ESC then type :wq and press ENTER)

XmlSerializer giving FileNotFoundException at constructor

I had the same problem until I used a 3rd Party tool to generate the Class from the XSD and it worked! I discovered that the tool was adding some extra code at the top of my class. When I added this same code to the top of my original class it worked. Here's what I added...

#pragma warning disable
namespace MyNamespace
{
  using System;
  using System.Diagnostics;
  using System.Xml.Serialization;
  using System.Collections;
  using System.Xml.Schema;
  using System.ComponentModel;
  using System.Xml;
  using System.Collections.Generic;

  [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1064.2")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
  [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
  public partial class MyClassName
  {
  ...

What is the proper way to URL encode Unicode characters?

The general rule seems to be that browsers encode form responses according to the content-type of the page the form was served from. This is a guess that if the server sends us "text/xml; charset=iso-8859-1", then they expect responses back in the same format.

If you're just entering a URL in the URL bar, then the browser doesn't have a base page to work on and therefore just has to guess. So in this case it seems to be doing utf-8 all the time (since both your inputs produced three-octet form values).

The sad truth is that AFAIK there's no standard for what character set the values in a query string, or indeed any characters in the URL, should be interpreted as. At least in the case of values in the query string, there's no reason to suppose that they necessarily do correspond to characters.

It's a known problem that you have to tell your server framework which character set you expect the query string to be encoded as--- for instance, in Tomcat, you have to call request.setEncoding() (or some similar method) before you call any of the request.getParameter() methods. The dearth of documentation on this subject probably reflects the lack of awareness of the problem amongst many developers. (I regularly ask Java interviewees what the difference between a Reader and an InputStream is, and regularly get blank looks)

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to the remote server but I find that unlikely.

Normally a network error will resolve itself given a bit of time, but it sounds like you’ve already given it a bit of time.

cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your web server.

Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.

Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

How do I pass JavaScript values to Scriptlet in JSP?

This is for other people landing here. First of all you need a servlet. I used a @POST request. Now in your jsp file you have two ways to do this:

  1. The complicated way with AJAX, in case you are new to jsp: You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:

    $(document).ready(function() {
        var sendVar = "hello";
        $('#domId').click(function (e)
        {                               
            $.ajax({
                type: "post",
                url: "/", //or whatever your url is
                data: "var=" + sendVar ,
                success: function(){      
                        console.log("success: " + sendVar );                            
                      <% 
                          String received= request.getParameter("var");
    
                          if(received == null || received.isEmpty()){
                              received = "some default value";
                          }
                          MyJavaClass.processJSvar(received); 
                      %>;                            
    
                }
            });
        });
    
    });
    
  2. The easy way just with JSP:

    <form id="myform" method="post" action="http://localhost:port/index.jsp">
         <input type="hidden" name="inputName" value=""/>
                   <% 
                          String pg = request.getParameter("inputName");
    
                          if(pg == null || pg.isEmpty()){
                              pg = "some default value";
                          }
                          DatasyncMain.changeToPage(pg); 
                      %>;     
    </form>
    

Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).

What is the Regular Expression For "Not Whitespace and Not a hyphen"

It can be done much easier:

\S which equals [^ \t\r\n\v\f]

Regular Expressions: Is there an AND operator?

You could pipe your output to another regex. Using grep, you could do this:

grep A | grep B

Why Anaconda does not recognize conda command?

For Windows

Go to Control Panel\System and Security\System\Advanced System Settings then look for Environment Variables.

Your user variables should contain Path=Path\to\Anaconda3\Scripts.

You need to figure where your Anaconda3 folder is (i.e. the path to this folder) . Mine was in C:\Users.

For Linux

You need to add conda to PATH. To do so, type:

export PATH=/path/to/anaconda3/bin:$PATH.

Same thing, you need to figure the path to anaconda3 folder (Usually, the path is stored in $HOME)

If you don't want to do this everytime you start a session, you can also add conda to PATH in your .bashrc file:

echo 'export PATH=/path/to/anaconda3/bin:$PATH' >> ~/.bashrc

How to add a ListView to a Column in Flutter?

I've got this problem too. My solution is use Expanded widget to expand remain space.

new Column(
  children: <Widget>[
    new Expanded(
      child: horizontalList,
    )
  ],
);

How to reload or re-render the entire page using AngularJS

Well maybe you forgot to add "$route" when declaring the dependencies of your Controller:

app.controller('NameCtrl', ['$scope','$route', function($scope,$route) {   
   // $route.reload(); Then this should work fine.
}]);

Delete the 'first' record from a table in SQL Server, without a WHERE condition

No, AFAIK, it's not possible to do it portably.

There's no defined "first" record anyway - on different SQL engines it's perfectly possible that "SELECT * FROM table" might return the results in a different order each time.

How to get a list of images on docker registry v2

I had to do the same here and the above works except I had to provide login details as it was a local docker repository.

It is as per the above but with supplying the username/password in the URL.

curl -k -X GET https://yourusername:yourpassword@theregistryURL/v2/_catalog

It comes back as unformatted JSON.

I piped it through the python formatter for ease of human reading, in case you would like to have it in this format.

curl -k -X GET https://yourusername:yourpassword@theregistryURL/v2/_catalog | python -m json.tool

Docker-Compose can't connect to Docker Daemon

I got this error when there were files in the Dockerfile directory that were not accessible by the current user. docker could thus not upload the full context to the daemon and brought the "Couldn't connect to Docker daemon at http+docker://localunixsocket" message.

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Number of occurrences of a character in a string

Because LINQ can do everything...:

string test = "key1=value1&key2=value2&key3=value3";
var count = test.Where(x => x == '&').Count();

Or if you like, you can use the Count overload that takes a predicate :

var count = test.Count(x => x == '&');

Get GPS location from the web browser

Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script>

How to var_dump variables in twig templates?

Dump all custom variables:

<h1>Variables passed to the view:</h1>
{% for key, value in _context %}
    {% if key starts with '_' %}
    {% else %}
        <pre style="background: #eee">{{ key }}</pre>
        {{ dump(value) }}
    {% endif %}
{% endfor %}

You can use my plugin which will do that for you (an will nicely format the output):

Twig Dump Bar

Returning a value even if no result

You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

SQL Server IF EXISTS THEN 1 ELSE 2

If you want to do it this way then this is the syntax you're after;

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.

REST API - Bulk Create or Update in single request

I think that you could use a POST or PATCH method to handle this since they typically design for this.

  • Using a POST method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).

    In the case, it's not necessary to define your format to describe the update.

  • Using a PATCH method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):

    Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    In the case, you have to define your format to describe the partial update.

I think that in this case, POST and PATCH are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.

The case of PUT is a bit less clear. In fact, when using a method PUT, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.

You can have two options regarding the resource paths.

  • Using the resource path for doc list

In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.

Here is a sample route for this /docs.

The content of such approach could be for method POST:

[
    { "doc_number": 1, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 2, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 3, "binder": 5, (other fields in the case of creation) },
    (...)
]
  • Using sub resource path of binder element

In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.

Here is a sample route for this /binder/{binderId}/docs. In this case, sending a list of docs with a method POST or PATCH will attach docs to the binder with identifier binderId after having created the doc if it doesn't exist.

The content of such approach could be for method POST:

[
    { "doc_number": 1, (other fields in the case of creation) },
    { "doc_number": 2, (other fields in the case of creation) },
    { "doc_number": 3, (other fields in the case of creation) },
    (...)
]

Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.

  • Atomic

In this case, you can leverage the HTTP status. If everything goes well, you get a status 200. If not, another status like 400 if the provided data aren't correct (for example binder id not valid) or something else.

  • Non atomic

In this case, a status 200 will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.

  • Asynchronous

You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202. The client needs to pull an additional resource to see what happens.

Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)

The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.

Hope it helps you, Thierry

Converting BitmapImage to Bitmap and vice versa

Here's an extension method for converting a Bitmap to BitmapImage.

    public static BitmapImage ToBitmapImage(this Bitmap bitmap)
    {
        using (var memory = new MemoryStream())
        {
            bitmap.Save(memory, ImageFormat.Png);
            memory.Position = 0;

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memory;
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.EndInit();
            bitmapImage.Freeze();

            return bitmapImage;
        }
    }

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

NuGet auto package restore does not work with MSBuild

Sometimes this occurs when you have the folder of the package you are trying to restore inside the "packages" folder (i.e. "Packages/EntityFramework.6.0.0/") but the "DLLs" are not inside it (most of the version control systems automatically ignore ".dll" files). This occurs because before NuGet tries to restore each package it checks if the folders already exist, so if it exists, NuGet assumes that the "dll" is inside it. So if this is the problem for you just delete the folder that NuGet will restore it correctly.

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

MySql Error: 1364 Field 'display_name' doesn't have default value

I also had this issue using Lumen, but fixed by setting DB_STRICT_MODE=false in .env file.

How do I implement JQuery.noConflict() ?

By default, jquery uses the variable jQuery and the $ is used for your convenience. If you want to avoid conflicts, a good way is to encapsulate jQuery like so:

(function($){

    $(function(){

        alert('$ is safe!');

    });

})(jQuery)

Remove tracking branches no longer on remote

This will delete all the merged local branched except local master reference and the one currently being used:

git branch --merged | grep -v "*" | grep -v "master" | xargs git branch -d

And this will delete all the branches having already been removed from the remote repository referenced by "origin", but are still locally available in "remotes/origin".

git remote prune origin

Changing SqlConnection timeout

You can set the timeout value in the connection string, but after you've connected it's read-only. You can read more at http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectiontimeout.aspx

As Anil implies, ConnectionTimeout may not be what you need; it controls how long the ADO driver will wait when establishing a new connection. Your usage seems to indicate a need to wait longer than normal for a particular SQL query to execute, and in that case Anil is exactly right; use CommandTimeout (which is R/W) to change the expected completion time for an individual SqlCommand.

Best practice for Django project working directory structure

You can use https://github.com/Mischback/django-project-skeleton repository.

Run below command:

$ django-admin startproject --template=https://github.com/Mischback/django-project-skeleton/archive/development.zip [projectname]

The structure is something like this:

[projectname]/                  <- project root
+-- [projectname]/              <- Django root
¦   +-- __init__.py
¦   +-- settings/
¦   ¦   +-- common.py
¦   ¦   +-- development.py
¦   ¦   +-- i18n.py
¦   ¦   +-- __init__.py
¦   ¦   +-- production.py
¦   +-- urls.py
¦   +-- wsgi.py
+-- apps/
¦   +-- __init__.py
+-- configs/
¦   +-- apache2_vhost.sample
¦   +-- README
+-- doc/
¦   +-- Makefile
¦   +-- source/
¦       +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦   +-- media/
¦   ¦   +-- README
¦   +-- README
¦   +-- static/
¦       +-- README
+-- static/
¦   +-- README
+-- templates/
    +-- base.html
    +-- core
    ¦   +-- login.html
    +-- README

Docker - Cannot remove dead container

Actually things changed slightly these days in order to get rid of those dead containers you may try to unmount those blocked filesystems to release them

So if you get message like this

Error response from daemon: Cannot destroy container elated_wozniak: Driver devicemapper failed to remove root filesystem 656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3: Device is Busy

just run this

umount /var/lib/docker/devicemapper/mnt/656cfd09aee399c8ae8c8d3e735fe48d70be6672773616e15579c8de18e2a3b3

and you can normally remove container after that

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

Semantic Difference

According to HTML 5.2:

When specified on an element, [the hidden attribute] indicates that the element is not yet, or is no longer, directly relevant to the page’s current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user.

Examples include a tab list where some panels are not exposed, or a log-in screen that goes away after a user logs in. I like to call these things “temporally relevant” i.e. they are relevant based on timing.

On the other hand, ARIA 1.1 says:

[The aria-hidden state] indicates whether an element is exposed to the accessibility API.

In other words, elements with aria-hidden="true" are removed from the accessibility tree, which most assistive technology honors, and elements with aria-hidden="false" will definitely be exposed to the tree. Elements without the aria-hidden attribute are in the "undefined (default)" state, which means user agents should expose it to the tree based on its rendering. E.g. a user agent may decide to remove it if its text color matches its background color.

Now let’s compare semantics. It’s appropriate to use hidden, but not aria-hidden, for an element that is not yet “temporally relevant”, but that might become relevant in the future (in which case you would use dynamic scripts to remove the hidden attribute). Conversely, it’s appropriate to use aria-hidden, but not hidden, on an element that is always relevant, but with which you don’t want to clutter the accessibility API; such elements might include “visual flair”, like icons and/or imagery that are not essential for the user to consume.

Effective Difference

The semantics have predictable effects in browsers/user agents. The reason I make a distinction is that user agent behavior is recommended, but not required by the specifications.

The hidden attribute should hide an element from all presentations, including printers and screen readers (assuming these devices honor the HTML specs). If you want to remove an element from the accessibility tree as well as visual media, hidden would do the trick. However, do not use hidden just because you want this effect. Ask yourself if hidden is semantically correct first (see above). If hidden is not semantically correct, but you still want to visually hide the element, you can use other techniques such as CSS.

Elements with aria-hidden="true" are not exposed to the accessibility tree, so for example, screen readers won’t announce them. This technique should be used carefully, as it will provide different experiences to different users: accessible user agents won’t announce/render them, but they are still rendered on visual agents. This can be a good thing when done correctly, but it has the potential to be abused.

Syntactic Difference

Lastly, there is a difference in syntax between the two attributes.

hidden is a boolean attribute, meaning if the attribute is present it is true—regardless of whatever value it might have—and if the attribute is absent it is false. For the true case, the best practice is to either use no value at all (<div hidden>...</div>), or the empty string value (<div hidden="">...</div>). I would not recommend hidden="true" because someone reading/updating your code might infer that hidden="false" would have the opposite effect, which is simply incorrect.

aria-hidden, by contrast, is an enumerated attribute, allowing one of a finite list of values. If the aria-hidden attribute is present, its value must be either "true" or "false". If you want the "undefined (default)" state, remove the attribute altogether.


Further reading: https://github.com/chharvey/chharvey.github.io/wiki/Hidden-Content

More Pythonic Way to Run a Process X Times

There is not a really pythonic way of repeating something. However, it is a better way:

map(lambda index:do_something(), xrange(10))

If you need to pass the index then:

map(lambda index:do_something(index), xrange(10))

Consider that it returns the results as a collection. So, if you need to collect the results it can help.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

java.util.Stack inherits the synchronization overhead of java.util.Vector, which is usually not justified.

It inherits a lot more than that, though. The fact that java.util.Stack extends java.util.Vector is a mistake in object-oriented design. Purists will note that it also offers a lot of methods beyond the operations traditionally associated with a stack (namely: push, pop, peek, size). It's also possible to do search, elementAt, setElementAt, remove, and many other random-access operations. It's basically up to the user to refrain from using the non-stack operations of Stack.

For these performance and OOP design reasons, the JavaDoc for java.util.Stack recommends ArrayDeque as the natural replacement. (A deque is more than a stack, but at least it's restricted to manipulating the two ends, rather than offering random access to everything.)

Is it possible to disable scrolling on a ViewPager

Here's an answer in Kotlin and androidX

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager

class DeactivatedViewPager @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ViewPager(context, attrs) {

    var isPagingEnabled = true

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        return isPagingEnabled && super.onTouchEvent(ev)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return isPagingEnabled && super.onInterceptTouchEvent(ev)
    }
}

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

I came across this thread because I also had the error Could not create SSL/TLS secure channel. In my case, I was attempting to access a Siebel configuration REST API from PowerShell using Invoke-RestMethod, and none of the suggestions above helped.

Eventually I stumbled across the cause of my problem: the server I was contacting required client certificate authentication.

To make the calls work, I had to provide the client certificate (including the private key) with the -Certificate parameter:

$Pwd = 'certificatepassword'
$Pfx = New-Object -TypeName 'System.Security.Cryptography.X509Certificates.X509Certificate2'
$Pfx.Import('clientcert.p12', $Pwd, 'Exportable,PersistKeySet')
Invoke-RestMethod -Uri 'https://your.rest.host/api/' -Certificate $Pfx -OtherParam ...

Hopefully my experience might help someone else who has my particular flavour of this problem.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

Docker has a default entrypoint which is /bin/sh -c but does not have a default command.

When you run docker like this: docker run -i -t ubuntu bash the entrypoint is the default /bin/sh -c, the image is ubuntu and the command is bash.

The command is run via the entrypoint. i.e., the actual thing that gets executed is /bin/sh -c bash. This allowed Docker to implement RUN quickly by relying on the shell's parser.

Later on, people asked to be able to customize this, so ENTRYPOINT and --entrypoint were introduced.

Everything after ubuntu in the example above is the command and is passed to the entrypoint. When using the CMD instruction, it is exactly as if you were doing docker run -i -t ubuntu <cmd>. <cmd> will be the parameter of the entrypoint.

You will also get the same result if you instead type this command docker run -i -t ubuntu. You will still start a bash shell in the container because of the ubuntu Dockerfile specified a default CMD: CMD ["bash"]

As everything is passed to the entrypoint, you can have a very nice behavior from your images. @Jiri example is good, it shows how to use an image as a "binary". When using ["/bin/cat"] as entrypoint and then doing docker run img /etc/passwd, you get it, /etc/passwd is the command and is passed to the entrypoint so the end result execution is simply /bin/cat /etc/passwd.

Another example would be to have any cli as entrypoint. For instance, if you have a redis image, instead of running docker run redisimg redis -H something -u toto get key, you can simply have ENTRYPOINT ["redis", "-H", "something", "-u", "toto"] and then run like this for the same result: docker run redisimg get key.

How to embed a Google Drive folder in a website

At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:

<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>

In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.

To get the API key:

1.) Go to https://console.developers.google.com/ Create a new project.

2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.

3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.

4.) Copy the newly generated API key.

To get the folder ID:

1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.

2.) Copy the part after 'folders/', this is your folder ID.

Now put both the API key and folder id in the above code and embed.

Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.

I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.

The file preview looks like this The content of the iframe looks like this

How to display a pdf in a modal window?

You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.

Can not get a simple bootstrap modal to work

I had an issue with Modals as well. I should have declare jquery.min.js before bootstrap.min.js (in my layout page). From official site : "all plugins depend on jQuery (this means jQuery must be included before the plugin files)"

Android - running a method periodically using postDelayed() call

You can simplify the code like this.

In Java:

new Handler().postDelayed (() -> {
    //your code here
}, 1000);

In Kotlin:

Handler().postDelayed({
   //your code here
}, 1000)

OpenSSL Command to check if a server is presenting a certificate

I was getting the below as well trying to get out to github.com as our proxy re-writes the HTTPS connection with their self-signed cert:

no peer certificate available No client certificate CA names sent

In my output there was also:

Protocol : TLSv1.3

I added -tls1_2 and it worked fine and now I can see which CA it is using on the outgoing request. e.g.:
openssl s_client -connect github.com:443 -tls1_2

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

add "throws IOException" to your method like this:

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

        FileReader reader=new FileReader("db.properties");

        Properties p=new Properties();
        p.load(reader);


    }

Update Multiple Rows in Entity Framework from a list of ids

I have created a library to batch delete or update records with a round trip on EF Core 5.

Sample code as follows:

await ctx.DeleteRangeAsync(b => b.Price > n || b.AuthorName == "zack yang");

await ctx.BatchUpdate()
.Set(b => b.Price, b => b.Price + 3)
.Set(b=>b.AuthorName,b=>b.Title.Substring(3,2)+b.AuthorName.ToUpper())
.Set(b => b.PubTime, b => DateTime.Now)
.Where(b => b.Id > n || b.AuthorName.StartsWith("Zack"))
.ExecuteAsync();

Github repository: https://github.com/yangzhongke/Zack.EFCore.Batch Report: https://www.reddit.com/r/dotnetcore/comments/k1esra/how_to_batch_delete_or_update_in_entity_framework/

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

Flutter.io Android License Status Unknown

For someone who is still facing the issue:
As answered below by Tommie C, Aba and few other people, but may not be clear enough as I found it.
Try installing java 1.8 manually as described here on windows/linux: [https://www3.ntu.edu.sg/home/ehchua/programming/howto/JDK_Howto.html]
and setting $JAVA_HOME variable(jdk path).
On windows set jdk path($JAVA_HOME) : [How to set java_home on Windows 7?.
On linux: [https://askubuntu.com/questions/175514/how-to-set-java-home-for-java].
Then run flutter doctor --android-licenses and accept all the licenses. Hope it helps.

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

sqldeveloper error message: Network adapter could not establish the connection error

Problem - I was not able to connect to DB through sql developer.

Solution - First thing to note is that SQL Developer is only UI to access to your database. I need to connect remote database not the localhost so I need not to install the oracle 8i/9i. Only I need is oracle client to install. After installation it got the path in environment variable like C:\oracle\product\10.2.0\client_1\bin. Still I was not able to connect the db.

Things to be checked.

  1. Listner/port should be up for the server IP where you want to connect.
  2. you will be able to ping the server. go to cmd prompt. type ping server Ip then enter.
  3. telnet the server IP and port. should be succesful.

If all points are ok for you then check from where you are running sql developer .exe file. I pasted sql developer folder to C:\oracle folder and run the .exe file from here and I am able to connect the database. and my problem of 'IO Error: The Network Adapter could not establish the connection' got resolved. Hurrey... :) :)

Copy rows from one table to another, ignoring duplicates

I hope this query will help you

INSERT INTO `dTable` (`field1`, `field2`)
SELECT field1, field2 FROM `sTable` 
WHERE `sTable`.`field1` NOT IN (SELECT `field1` FROM `dTable`)

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I am working on TestNG Maven project, This worked for me by adding <resources> tag in pom.xml, this happens to be the path of my custom configuration file log4j2.xml.

<url>http://maven.apache.org</url>
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
  <resources>
    <resource>
      <directory>src/main/java/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>
<dependencies>
  <dependency>

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

PostgreSQL Forging Key DELETE, UPDATE CASCADE

CREATE TABLE apps_user(
  user_id SERIAL PRIMARY KEY,
  username character varying(30),
  userpass character varying(50),
  created_on DATE
);

CREATE TABLE apps_profile(
    pro_id SERIAL PRIMARY KEY,
    user_id INT4 REFERENCES apps_user(user_id) ON DELETE CASCADE ON UPDATE CASCADE,
    firstname VARCHAR(30),
    lastname VARCHAR(50),
    email VARCHAR UNIQUE,
    dob DATE
);

What is the difference between Sessions and Cookies in PHP?

Session

Session is used for maintaining a dialogue between server and user. It is more secure because it is stored on the server, we cannot easily access it. It embeds cookies on the user computer. It stores unlimited data.

Cookies

Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session. It stores limited amount of data, and is maintained for a limited time.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

Easiest ways to get file name:

val fileName = File(uri.path).name
// or
val fileName = uri.pathSegments.last()

If they don't give you the right name you should use:

fun Uri.getName(context: Context): String {
    val returnCursor = context.contentResolver.query(this, null, null, null, null)
    val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    returnCursor.moveToFirst()
    val fileName = returnCursor.getString(nameIndex)
    returnCursor.close()
    return fileName
}

How can I initialize base class member variables in derived class constructor?

# include<stdio.h>
# include<iostream>
# include<conio.h>

using namespace std;

class Base{
    public:
        Base(int i, float f, double d): i(i), f(f), d(d)
        {
        }
    virtual void Show()=0;
    protected:
        int i;
        float f;
        double d;
};


class Derived: public Base{
    public:
        Derived(int i, float f, double d): Base( i, f, d)
        {
        }
        void Show()
        {
            cout<< "int i = "<<i<<endl<<"float f = "<<f<<endl <<"double d = "<<d<<endl;
        }
};

int main(){
    Base * b = new Derived(10, 1.2, 3.89);
    b->Show();
    return 0;
}

It's a working example in case you want to initialize the Base class data members present in the Derived class object, whereas you want to push these values interfacing via Derived class constructor call.

Insert default value when parameter is null

Christophe,

The default value on a column is only applied if you don't specify the column in the INSERT statement.

Since you're explicitiy listing the column in your insert statement, and explicity setting it to NULL, that's overriding the default value for that column

What you need to do is "if a null is passed into your sproc then don't attempt to insert for that column".

This is a quick and nasty example of how to do that with some dynamic sql.

Create a table with some columns with default values...

CREATE TABLE myTable (
    always VARCHAR(50),
    value1 VARCHAR(50) DEFAULT ('defaultcol1'),
    value2 VARCHAR(50) DEFAULT ('defaultcol2'),
    value3 VARCHAR(50) DEFAULT ('defaultcol3')
)

Create a SPROC that dynamically builds and executes your insert statement based on input params

ALTER PROCEDURE t_insert (
    @always VARCHAR(50),
    @value1 VARCHAR(50) = NULL,
    @value2 VARCHAR(50) = NULL,
    @value3 VARCAHR(50) = NULL
)
AS 
BEGIN
DECLARE @insertpart VARCHAR(500)
DECLARE @valuepart VARCHAR(500)

SET @insertpart = 'INSERT INTO myTable ('
SET @valuepart = 'VALUES ('

    IF @value1 IS NOT NULL
    BEGIN
        SET @insertpart = @insertpart + 'value1,'
        SET @valuepart = @valuepart + '''' + @value1 + ''', '
    END

    IF @value2 IS NOT NULL
    BEGIN
        SET @insertpart = @insertpart + 'value2,'
        SET @valuepart = @valuepart + '''' + @value2 + ''', '
    END

    IF @value3 IS NOT NULL
    BEGIN
        SET @insertpart = @insertpart + 'value3,'
        SET @valuepart = @valuepart + '''' + @value3 + ''', '
    END

    SET @insertpart = @insertpart + 'always) '
    SET @valuepart = @valuepart + + '''' + @always + ''')'

--print @insertpart + @valuepart
EXEC (@insertpart + @valuepart)
END

The following 2 commands should give you an example of what you want as your outputs...

EXEC t_insert 'alwaysvalue'
SELECT * FROM  myTable

EXEC t_insert 'alwaysvalue', 'val1'
SELECT * FROM  myTable

EXEC t_insert 'alwaysvalue', 'val1', 'val2', 'val3'
SELECT * FROM  myTable

I know this is a very convoluted way of doing what you need to do. You could probably equally select the default value from the InformationSchema for the relevant columns but to be honest, I might consider just adding the default value to param at the top of the procedure

Proxy with express.js

I found a shorter solution that does exactly what I want https://github.com/http-party/node-http-proxy

After installing http-proxy

npm install http-proxy --save

Use it like below in your server/index/app.js

var proxyServer = require('http-route-proxy');
app.use('/api/BLABLA/', proxyServer.connect({
  to: 'other_domain.com:3000/BLABLA',
  https: true,
  route: ['/']
}));

I really have spent days looking everywhere to avoid this issue, tried plenty of solutions and none of them worked but this one.

Hope it is going to help someone else too :)

Using async/await for multiple tasks

I just want to add to all great answers above, that if you write a library it's a good practice to use ConfigureAwait(false) and get better performance, as said here.

So this snippet seems to be better:

 public static async Task DoWork() 
 {
     int[] ids = new[] { 1, 2, 3, 4, 5 };
     await Task.WhenAll(ids.Select(i => DoSomething(1, i))).ConfigureAwait(false);
 }

A full fiddle link here.

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

grep --ignore-case --only

This is a known bug on the initial 2.5.1, and has been fixed in early 2007 (Redhat 2.5.1-5) according to the bug reports. Unfortunately Apple is still using 2.5.1 even on Mac OS X 10.7.2.

You could get a newer version via Homebrew (3.0) or MacPorts (2.26) or fink (3.0-1).


Edit: Apparently it has been fixed on OS X 10.11 (or maybe earlier), even though the grep version reported is still 2.5.1.

How can I make space between two buttons in same div?

I used the Bootstrap 4 buttons plugin (https://getbootstrap.com/docs/4.0/components/buttons/#button-plugin) and added the class rounded to the labels and the class mx-1 to the middle button to achieve the desired look and feel of separate radio buttons. Using the class btn-toolbar made the radio button circles appear for me which is not what I wanted. Hope this helps someone.

        <div class="btn-group btn-group-toggle" data-toggle="buttons">
            <label class="btn btn-secondary active rounded">
                <input type="radio" name="options" id="option1" autocomplete="off" checked> Active
            </label>
            <label class="btn btn-secondary rounded mx-1">
                <input type="radio" name="options" id="option2" autocomplete="off"> Radio
            </label>
            <label class="btn btn-secondary rounded">
                <input type="radio" name="options" id="option3" autocomplete="off"> Radio
            </label>
        </div>

Python JSON serialize a Decimal object

How about subclassing json.JSONEncoder?

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            # wanted a simple yield str(o) in the next line,
            # but that would mean a yield on the line with super(...),
            # which wouldn't work (see my comment below), so...
            return (str(o) for o in [o])
        return super(DecimalEncoder, self).default(o)

Then use it like so:

json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)

Ranges of floating point datatype in C?

As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.

However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.

  • float has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.

  • double has 53 significant binary digits, which is approximately 15 decimal digits.

Another answer of mine has further explanation if you're interested.

Getting a slice of keys from a map

I made a sketchy benchmark on the three methods described in other responses.

Obviously pre-allocating the slice before pulling the keys is faster than appending, but surprisingly, the reflect.ValueOf(m).MapKeys() method is significantly slower than the latter:

? go run scratch.go
populating
filling 100000000 slots
done in 56.630774791s
running prealloc
took: 9.989049786s
running append
took: 18.948676741s
running reflect
took: 25.50070649s

Here's the code: https://play.golang.org/p/Z8O6a2jyfTH (running it in the playground aborts claiming that it takes too long, so, well, run it locally.)

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

Comparing Class Types in Java

As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).

In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.

public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
  // TODO handle nulls maybe?
  return c1.getCanonicalName().equals(c2.getCanonicalName());
}

Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.

Replace all occurrences of a String using StringBuilder?

Yes. It is very simple to use String.replaceAll() method:

package com.test;

public class Replace {

    public static void main(String[] args) {
        String input = "Hello World";
        input = input.replaceAll("o", "0");
        System.out.println(input);
    }
}

Output:

Hell0 W0rld

If you really want to use StringBuilder.replace(int start, int end, String str) instead then here you go:

public static void main(String args[]) {
    StringBuilder sb = new StringBuilder("This is a new StringBuilder");

    System.out.println("Before: " + sb);

    String from = "new";
    String to = "replaced";
    sb = sb.replace(sb.indexOf(from), sb.indexOf(from) + from.length(), to);

    System.out.println("After: " + sb);
}

Output:

Before: This is a new StringBuilder
After: This is a replaced StringBuilder

Open Facebook page from Android app?

To do this we need the "Facebook page id", you can get it :

  • from the page go to "About".
  • go to "More Info" section.

introducir la descripción de la imagen aquí

To opening facebook app on specified profile page,

you can do this:

 String facebookId = "fb://page/<Facebook Page ID>";
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookId)));

Or you can validate when the facebook app is not installed, then open the facebook web page.

String facebookId = "fb://page/<Facebook Page ID>";
String urlPage = "http://www.facebook.com/mypage";

     try {
          startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(facebookId )));
        } catch (Exception e) {
         Log.e(TAG, "Application not intalled.");
         //Open url web page.
         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urlPage)));
        }

Maven plugin not using Eclipse's proxy settings

Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings. If the file doesn't exist, create it and put on something like this:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>192.168.1.100</host>
      <port>6666</port>
      <username></username>
      <password></password>
      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
    </proxy>
  </proxies>
  <profiles/>
  <activeProfiles/>
</settings>

After editing the file, it's just a matter of clicking on Update Settings button and it's done. I've just done it and it worked :)

How to run travis-ci locally

You could try Trevor, which uses Docker to run your Travis build.

From its description:

I often need to run tests for multiple versions of Node.js. But I don't want to switch versions manually using n/nvm or push the code to Travis CI just to run the tests.

That's why I created Trevor. It reads .travis.yml and runs tests in all versions you requested, just like Travis CI. Now, you can test before push and keep your git history clean.

Why and when to use angular.copy? (Deep Copy)

In that case, you don't need to use angular.copy()

Explanation :

  • = represents a reference whereas angular.copy() creates a new object as a deep copy.

  • Using = would mean that changing a property of response.data would change the corresponding property of $scope.example or vice versa.

  • Using angular.copy() the two objects would remain seperate and changes would not reflect on each other.

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

OSX - How to auto Close Terminal window after the "exit" command executed.

I've been using

quit -n terminal

at the end of my scripts. You have to have the terminal set to never prompt in preferences

So Terminal > Preferences > Settings > Shell When the shell exits Close the window Prompt before closing Never

Encapsulation vs Abstraction?

Encapsulation protects to collapse the internal behaviour of object/instance from external entity. So, a control should be provided to confirm that the data which is being supplied is not going to harm the internal system of instance/object to survive its existance.

Good example, Divider is a class which has two instance variable dividend and divisor and a method getDividedValue.

Can you please think, if the divisor is set to 0 then internal system/behaviour (getDivided ) will break.

So, the object internal behaviour could be protected by throwing exception through a method.

getting the table row values with jquery

All Elements

$('#tabla > tbody  > tr').each(function() {
    $(this).find("td:gt(0)").each(function(){
       alert($(this).html());
       });
});

Sort a two dimensional array based on one column

  1. install java8 jdk+jre

  2. use lamda expression to sort 2D array.

code:

import java.util.Arrays;
import java.util.Comparator;

class SortString {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "2009.07.25 20:24", "Message A" },
                new String[] { "2009.07.25 20:17", "Message G" },
                new String[] { "2009.07.25 20:25", "Message B" },
                new String[] { "2009.07.25 20:30", "Message D" },
                new String[] { "2009.07.25 20:01", "Message F" },
                new String[] { "2009.07.25 21:08", "Message E" },
                new String[] { "2009.07.25 19:54", "Message R" } 
        };
        // this is applicable only in java 8 version.
        Arrays.sort(data, (String[] s1, String[] s2) -> s1[0].compareTo(s2[0]));

        // we can also use Comparator.comparing and point to Comparable value we want to use        
        // Arrays.sort(data, Comparator.comparing(row->row[0]));

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]);
        }
    }
}

output

2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E

What do the terms "CPU bound" and "I/O bound" mean?

Another way to phrase the same idea:

  • If speeding up the CPU doesn't speed up your program, it may be I/O bound.

  • If speeding up the I/O (e.g. using a faster disk) doesn't help, your program may be CPU bound.

(I used "may be" because you need to take other resources into account. Memory is one example.)

Jenkins - How to access BUILD_NUMBER environment variable

To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.

Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.

EDIT:

Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.

Why don't you use $BUILD_URL then? Isn't it available in the extended email plugin?

Python Turtle, draw text with on screen with larger font

Use the optional font argument to turtle.write(), from the docs:

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))
 Parameters:

  • arg – object to be written to the TurtleScreen
  • move – True/False
  • align – one of the strings “left”, “center” or right”
  • font – a triple (fontname, fontsize, fonttype)

So you could do something like turtle.write("messi fan", font=("Arial", 16, "normal")) to change the font size to 16 (default is 8).

Do a "git export" (like "svn export")?

If you need submodules as well, this should do the trick: https://github.com/meitar/git-archive-all.sh/wiki

'names' attribute must be the same length as the vector

For me, this error was because I had some of my data titles were two names, I merged them in one name and all went well.

Why can't I display a pound (£) symbol in HTML?

You need to save your PHP script file in UTF-8 encoding, and leave the <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> in the HTML.

For text editor, I recommend Notepad++, because it can detect and display the actual encoding of the file (in the lower right corner of the editor), and you can convert it as well.

Counting array elements in Perl

print scalar grep { defined $_ } @a;

How to allow only integers in a textbox?

step by step

given you have a textbox as following,

<asp:TextBox ID="TextBox13" runat="server" 
  onkeypress="return functionx(event)" >
</asp:TextBox>

you create a JavaScript function like this:

     <script type = "text/javascript">
         function functionx(evt) 
         {
            if (evt.charCode > 31 && (evt.charCode < 48 || evt.charCode > 57))
                  {
                    alert("Allow Only Numbers");
                    return false;
                  }
          }
     </script>

the first part of the if-statement excludes the ASCII control chars, the or statements exclued anything, that is not a number

How to write PNG image to string with the PIL?

sth's solution didn't work for me
because in ...

Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension

It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case

You can bypass the format detection by setting the format yourself in a parameter

import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Android - Best and safe way to stop thread

The thing is you need to check whether the thread is running or not !?

Field:

private boolean runningThread = false;

In the thread:

new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep((long) Math.floor(speed));
                        if (!runningThread) {
                            return;
                        }
                        yourWork();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

If you want to stop the thread you should make the below field

private boolean runningThread = false;

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Java: splitting a comma-separated string but ignoring commas in quotes

You're in that annoying boundary area where regexps almost won't do (as has been pointed out by Bart, escaping the quotes would make life hard) , and yet a full-blown parser seems like overkill.

If you are likely to need greater complexity any time soon I would go looking for a parser library. For example this one

How to right-align form input boxes?

Try this:

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

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

How to check if an element is visible with WebDriver

Here is how I would do it (please ignore worry Logger class calls):

public boolean isElementExist(By by) {
    int count = driver.findElements(by).size();
    if (count>=1) {
        Logger.LogMessage("isElementExist: " + by + " | Count: " + count, Priority.Medium);
        return true;
    }
    else {
        Logger.LogMessage("isElementExist: " + by + " | Could not find element", Priority.High);
        return false;
    }   
}

public boolean isElementNotExist(By by) {
    int count = driver.findElements(by).size();
    if (count==0) {
        Logger.LogMessage("ElementDoesNotExist: " + by, Priority.Medium);
        return true;
    }
    else {
        Logger.LogMessage("ElementDoesExist: " + by, Priority.High);
        return false;
    }   
}

public boolean isElementVisible(By by) {
    try {
        if (driver.findElement(by).isDisplayed()) {
            Logger.LogMessage("Element is Displayed: " + by, Priority.Medium);
            return true;
        }
    }
    catch(Exception e) {       
        Logger.LogMessage("Element is Not Displayed: " + by, Priority.High);
        return false;
    }       

    return false;
}

Pointer arithmetic for void pointer in C

Void pointers can point to any memory chunk. Hence the compiler does not know how many bytes to increment/decrement when we attempt pointer arithmetic on a void pointer. Therefore void pointers must be first typecast to a known type before they can be involved in any pointer arithmetic.

void *p = malloc(sizeof(char)*10);
p++; //compiler does how many where to pint the pointer after this increment operation

char * c = (char *)p;
c++;  // compiler will increment the c by 1, since size of char is 1 byte.

How to convert SQL Query result to PANDAS Data Structure?

Long time from last post but maybe it helps someone...

Shorted way than Paul H:

my_dic = session.query(query.all())
my_df = pandas.DataFrame.from_dict(my_dic)

Iterating through a list to render multiple widgets in Flutter?

Basically when you hit 'return' on a function the function will stop and will not continue your iteration, so what you need to do is put it all on a list and then add it as a children of a widget

you can do something like this:

  Widget getTextWidgets(List<String> strings)
  {
    List<Widget> list = new List<Widget>();
    for(var i = 0; i < strings.length; i++){
        list.add(new Text(strings[i]));
    }
    return new Row(children: list);
  }

or even better, you can use .map() operator and do something like this:

  Widget getTextWidgets(List<String> strings)
  {
    return new Row(children: strings.map((item) => new Text(item)).toList());
  }

jQuery first child of "this"

If you want to apply a selector to the context provided by an existing jQuery set, try the find() function:

element.find(">:first-child").toggleClass("redClass");

Jørn Schou-Rode noted that you probably only want to find the first direct descendant of the context element, hence the child selector (>). He also points out that you could just as well use the children() function, which is very similar to find() but only searches one level deep in the hierarchy (which is all you need...):

element.children(":first").toggleClass("redClass");

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

You can do this :

mysql -u USERNAME --password=PASSWORD --database=DATABASE --execute='SELECT `FIELD`, `FIELD` FROM `TABLE` LIMIT 0, 10000 ' -X > file.xml

How to set the text color of TextView in code?

I was doing this for a TextView in a ViewHolder for a RecyclerView. I'm not so sure why, but it didn't work for me in the ViewHolder initialization.

public ViewHolder(View itemView) {
    super(itemView);
    textView = (TextView) itemView.findViewById(R.id.text_view);
    textView.setTextColor(context.getResources().getColor(R.color.myColor));
    // Other stuff
}

But when I moved it to the onBindViewHolder, it worked fine.

public void onBindViewHolder(ViewHolder holder, int position){
    // Other stuff
    holder.textView.setTextColor(context.getResources().getColor(R.color.myColor));
}

Hope this helps someone.

Replacing from match to end-of-line

This should do what you want:

sed 's/two.*/BLAH/'

$ echo "   one  two  three  five
>    four two  five five six
>    six  one  two seven four" | sed 's/two.*/BLAH/'
   one  BLAH
   four BLAH
   six  one  BLAH

The $ is unnecessary because the .* will finish at the end of the line anyways, and the g at the end is unnecessary because your first match will be the first two to the end of the line.

onSaveInstanceState () and onRestoreInstanceState ()

onRestoreInstanceState() is called only when recreating activity after it was killed by the OS. Such situation happen when:

  • orientation of the device changes (your activity is destroyed and recreated).
  • there is another activity in front of yours and at some point the OS kills your activity in order to free memory (for example). Next time when you start your activity onRestoreInstanceState() will be called.

In contrast: if you are in your activity and you hit Back button on the device, your activity is finish()ed (i.e. think of it as exiting desktop application) and next time you start your app it is started "fresh", i.e. without saved state because you intentionally exited it when you hit Back.

Other source of confusion is that when an app loses focus to another app onSaveInstanceState() is called but when you navigate back to your app onRestoreInstanceState() may not be called. This is the case described in the original question, i.e. if your activity was NOT killed during the period when other activity was in front onRestoreInstanceState() will NOT be called because your activity is pretty much "alive".

All in all, as stated in the documentation for onRestoreInstanceState():

Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

As I read it: There is no reason to override onRestoreInstanceState() unless you are subclassing Activity and it is expected that someone will subclass your subclass.

Create directory if it does not exist

When you specify the -Force flag, PowerShell will not complain if the folder already exists.

One-liner:

Get-ChildItem D:\TopDirec\SubDirec\Project* | `
  %{ Get-ChildItem $_.FullName -Filter Revision* } | `
  %{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }

BTW, for scheduling the task please check out this link: Scheduling Background Jobs.

What characters are valid for JavaScript variable names?

Actually, ECMAScript says on page 15: That an identifier may start with a $, an underscore or a UnicodeLetter, and then it goes on (just below that) to specify that a UnicodeLetter can be any character from the unicode catagories, Lo, Ll, Lu, Lt, Lm and Nl. And when you look up those catagories you will see that this opens up a lot more possibilities than just latin letters. Just search for "unicode catagories" in google and you can find them.

How does strtok() split the string into tokens in C?

For those who are still having hard time understanding this strtok() function, take a look at this pythontutor example, it is a great tool to visualize your C (or C++, Python ...) code.

In case the link got broken, paste in:

#include <stdio.h>
#include <string.h>

int main()
{
    char s[] = "Hello, my name is? Matthew! Hey.";
    char* p;
    for (char *p = strtok(s," ,?!."); p != NULL; p = strtok(NULL, " ,?!.")) {
      puts(p);
    }
    return 0;
}

Credits go to Anders K.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

If you're just playing around in local mode, you can drop metastore DB and reinstate it:

rm -rf metastore_db/
$HIVE_HOME/bin/schematool -initSchema -dbType derby

Cannot read property 'length' of null (javascript)

This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)

if (capital && capital.length < 1) {do your stuff}

How to configure postgresql for the first time?

In MacOS, I followed the below steps to make it work.

For the first time, after installation, get the username of the system.

$ cd ~
$ pwd
/Users/someuser
$ psql -d postgres -U someuser

Now that you have logged into the system, and you can create the DB.

postgres=# create database mydb;
CREATE DATABASE
postgres=# create user myuser with encrypted password 'pass123';
CREATE ROLE
postgres=# grant all privileges on database mydb to myuser;
GRANT

UITableViewCell Selected Background Color on Multiple Selection

Swift 4

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{
    let selectedCell = tableView.cellForRow(at: indexPath)! as! LeftMenuCell
    selectedCell.contentView.backgroundColor = UIColor.blue
}

If you want to unselect the previous cell, also you can use the different logic for this

var tempcheck = 9999
var lastrow = IndexPath()
var lastcolor = UIColor()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if tempcheck == 9999
    {
        tempcheck = 0
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
    else
    {
        let selectedCelllasttime = tableView.cellForRow(at: lastrow)! as! HealthTipsCell
        selectedCelllasttime.contentView.backgroundColor = lastcolor
        let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
        lastcolor = selectedCell.contentView.backgroundColor!
        selectedCell.contentView.backgroundColor = UIColor.blue
        lastrow = indexPath
    }
}

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

What is WebKit and how is it related to CSS?

Addition to what @KennyTM said:

  • IE
  • Edge
  • Firefox
    • Engine: Gecko
    • CSS-prefix: -moz
  • Opera
    • Engine: Presto ? Blink1
    • CSS-prefix: -o (Presto) and -webkit (Blink)
  • Safari
    • Engine: WebKit
    • CSS-prefix: -webkit
  • Chrome

1) On February 12 2013 Opera (version 15+) announces they moving away from their own engine Presto to WebKit named Blink.

2) On April 3 2013 Google (Chrome version 28+) announces they are going to use the WebKit-based Blink engine.

3) On December 6 2018 Microsoft (Microsoft Edge 79+ stable) announces they are going to use the WebKit-based Blink engine.

Replace one character with another in Bash

In bash, you can do pattern replacement in a string with the ${VARIABLE//PATTERN/REPLACEMENT} construct. Use just / and not // to replace only the first occurrence. The pattern is a wildcard pattern, like file globs.

string='foo bar qux'
one="${string/ /.}"     # sets one to 'foo.bar qux'
all="${string// /.}"    # sets all to 'foo.bar.qux'

How to install ADB driver for any android device?

You don't really need to install or use any third party tools.

The drivers located in ...\Android\Sdk\extras\google\usb_driver work just fine.

Step 1: In Device Manager, Right click on the malfunctioning Android ADB Interface driver

Step 2: Select Update Driver Software

Step 3: Select Browse my computer for driver software

Step 4: Select Let me pick from a list of device drivers on my computer

Step 5: Select Have Disk

This window pops up:

enter image description here

Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver) or browse to it.

Step 7: Click Ok

This window pops up:

enter image description here

Step 8: Select Android ADB Interface and click Next

The window below pops up with a warning:

enter image description here

That's it. You driver installation will start and in a few seconds, you should be able to see your device

How to get a Char from an ASCII Character Code in c#

It is important to notice that in C# the char type is stored as Unicode UTF-16.

From ASCII equivalent integer to char

char c = (char)88;

or

char c = Convert.ToChar(88)

From char to ASCII equivalent integer

int asciiCode = (int)'A';

The literal must be ASCII equivalent. For example:

string str = "X?????????";
Console.WriteLine((int)str[0]);
Console.WriteLine((int)str[1]);

will print

X
3626

Extended ASCII ranges from 0 to 255.

From default UTF-16 literal to char

Using the Symbol

char c = 'X';

Using the Unicode code

char c = '\u0058';

Using the Hexadecimal

char c = '\x0058';

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

The static keyword and its various uses in C++

Variables:

static variables exist for the "lifetime" of the translation unit that it's defined in, and:

  • If it's in a namespace scope (i.e. outside of functions and classes), then it can't be accessed from any other translation unit. This is known as "internal linkage" or "static storage duration". (Don't do this in headers except for constexpr. Anything else, and you end up with a separate variable in each translation unit, which is crazy confusing)
  • If it's a variable in a function, it can't be accessed from outside of the function, just like any other local variable. (this is the local they mentioned)
  • class members have no restricted scope due to static, but can be addressed from the class as well as an instance (like std::string::npos). [Note: you can declare static members in a class, but they should usually still be defined in a translation unit (cpp file), and as such, there's only one per class]

locations as code:

static std::string namespaceScope = "Hello";
void foo() {
    static std::string functionScope= "World";
}
struct A {
   static std::string classScope = "!";
};

Before any function in a translation unit is executed (possibly after main began execution), the variables with static storage duration (namespace scope) in that translation unit will be "constant initialized" (to constexpr where possible, or zero otherwise), and then non-locals are "dynamically initialized" properly in the order they are defined in the translation unit (for things like std::string="HI"; that aren't constexpr). Finally, function-local statics will be initialized the first time execution "reaches" the line where they are declared. All static variables all destroyed in the reverse order of initialization.

The easiest way to get all this right is to make all static variables that are not constexpr initialized into function static locals, which makes sure all of your statics/globals are initialized properly when you try to use them no matter what, thus preventing the static initialization order fiasco.

T& get_global() {
    static T global = initial_value();
    return global;
}

Be careful, because when the spec says namespace-scope variables have "static storage duration" by default, they mean the "lifetime of the translation unit" bit, but that does not mean it can't be accessed outside of the file.

Functions

Significantly more straightforward, static is often used as a class member function, and only very rarely used for a free-standing function.

A static member function differs from a regular member function in that it can be called without an instance of a class, and since it has no instance, it cannot access non-static members of the class. Static variables are useful when you want to have a function for a class that definitely absolutely does not refer to any instance members, or for managing static member variables.

struct A {
    A() {++A_count;}
    A(const A&) {++A_count;}
    A(A&&) {++A_count;}
    ~A() {--A_count;}

    static int get_count() {return A_count;}
private:
    static int A_count;
}

int main() {
    A var;

    int c0 = var.get_count(); //some compilers give a warning, but it's ok.
    int c1 = A::get_count(); //normal way
}

A static free-function means that the function will not be referred to by any other translation unit, and thus the linker can ignore it entirely. This has a small number of purposes:

  • Can be used in a cpp file to guarantee that the function is never used from any other file.
  • Can be put in a header and every file will have it's own copy of the function. Not useful, since inline does pretty much the same thing.
  • Speeds up link time by reducing work
  • Can put a function with the same name in each translation unit, and they can all do different things. For instance, you could put a static void log(const char*) {} in each cpp file, and they could each all log in a different way.

Bat file to run a .exe at the command prompt

A bat file has no structure...it is how you would type it on the command line. So just open your favourite editor..copy the line of code you want to run..and save the file as whatever.bat or whatever.cmd

TensorFlow: "Attempting to use uninitialized value" in variable initialization

Run this:

init = tf.global_variables_initializer()
sess.run(init)

Or (depending on the version of TF that you have):

init = tf.initialize_all_variables()
sess.run(init)

Typescript sleep

For some reason the above accepted answer does not work in New versions of Angular (V6).

for that use this..

async delay(ms: number) {
    await new Promise(resolve => setTimeout(()=>resolve(), ms)).then(()=>console.log("fired"));
}

above worked for me.

Usage:

this.delay(3000);

OR more accurate way

this.delay(3000).then(any=>{
     //your task after delay.
});

ImportError: No module named BeautifulSoup

if you got two version of python, maybe my situation could help you

this is my situation

1-> mac osx

2-> i have two version python , (1) system default version 2.7 (2) manually installed version 3.6

3-> i have install the beautifulsoup4 with sudo pip install beautifulsoup4

4-> i run the python file with python3 /XXX/XX/XX.py

so this situation 3 and 4 are the key part, i have install beautifulsoup4 with "pip" but this module was installed for python verison 2.7, and i run the python file with "python3". so you should install beautifulsoup4 for the python 3.6;

with the sudo pip3 install beautifulsoup4 you can install the module for the python 3.6

Programmatically saving image to Django ImageField

Your can use Django REST framework and python Requests library to Programmatically saving image to Django ImageField

Here is a Example:

import requests


def upload_image():
    # PATH TO DJANGO REST API
    url = "http://127.0.0.1:8080/api/gallery/"

    # MODEL FIELDS DATA
    data = {'first_name': "Rajiv", 'last_name': "Sharma"}

    #  UPLOAD FILES THROUGH REST API
    photo = open('/path/to/photo'), 'rb')
    resume = open('/path/to/resume'), 'rb')
    files = {'photo': photo, 'resume': resume}

    request = requests.post(url, data=data, files=files)
    print(request.status_code, request.reason) 

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Text in HTML Field to disappear when clicked?

What you want to do is use the HTML5 attribute placeholder which lets you set a default value for your input box:

<input type="text" name="inputBox" placeholder="enter your text here">

This should achieve what you're looking for. However, be careful because the placeholder attribute is not supported in Internet Explorer 9 and earlier versions.

How can I determine the status of a job?

This will show last run status/time or if running, it shows current run time, step number/info, and SPID (if it has associated SPID). It also shows enabled/disabled and job user where it converts to NT SID format for unresolved user accounts.

CREATE TABLE #list_running_SQL_jobs
(
    job_id UNIQUEIDENTIFIER NOT NULL
  , last_run_date INT NOT NULL
  , last_run_time INT NOT NULL
  , next_run_date INT NOT NULL
  , next_run_time INT NOT NULL
  , next_run_schedule_id INT NOT NULL
  , requested_to_run INT NOT NULL
  , request_source INT NOT NULL
  , request_source_id sysname NULL
  , running INT NOT NULL
  , current_step INT NOT NULL
  , current_retry_attempt INT NOT NULL
  , job_state INT NOT NULL
);

DECLARE @sqluser NVARCHAR(128)
      , @is_sysadmin INT;

SELECT @is_sysadmin = ISNULL(IS_SRVROLEMEMBER(N'sysadmin'), 0);

DECLARE read_sysjobs_for_running CURSOR FOR
    SELECT DISTINCT SUSER_SNAME(owner_sid)FROM msdb.dbo.sysjobs;
OPEN read_sysjobs_for_running;
FETCH NEXT FROM read_sysjobs_for_running
INTO @sqluser;

WHILE @@FETCH_STATUS = 0
BEGIN
    INSERT INTO #list_running_SQL_jobs
    EXECUTE master.dbo.xp_sqlagent_enum_jobs @is_sysadmin, @sqluser;
    FETCH NEXT FROM read_sysjobs_for_running
    INTO @sqluser;
END;

CLOSE read_sysjobs_for_running;
DEALLOCATE read_sysjobs_for_running;

SELECT j.name
     , 'Enbld' = CASE j.enabled
                     WHEN 0
                         THEN 'no'
                     ELSE 'YES'
                 END
     , '#Min' = DATEDIFF(MINUTE, a.start_execution_date, ISNULL(a.stop_execution_date, GETDATE()))
     , 'Status' = CASE
                      WHEN a.start_execution_date IS NOT NULL
                          AND a.stop_execution_date IS NULL
                          THEN 'Executing'
                      WHEN h.run_status = 0
                          THEN 'FAILED'
                      WHEN h.run_status = 2
                          THEN 'Retry'
                      WHEN h.run_status = 3
                          THEN 'Canceled'
                      WHEN h.run_status = 4
                          THEN 'InProg'
                      WHEN h.run_status = 1
                          THEN 'Success'
                      ELSE 'Idle'
                  END
     , r.current_step
     , spid = p.session_id
     , owner = ISNULL(SUSER_SNAME(j.owner_sid), 'S-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1))) - CONVERT(BIGINT, 256) * CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256)) + '-' + CONVERT(NVARCHAR(12), UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 4), 1)) / 256 + CONVERT(BIGINT, NULLIF(UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256, 0)) - CONVERT(BIGINT, UNICODE(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 1)) / 256)) + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 5), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 6), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 6), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 7), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 8), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 8), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 9), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 10), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 10), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 11), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 12), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 12), -1)) * 0), '') + ISNULL('-' + CONVERT(NVARCHAR(12), CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 13), 1))) + CONVERT(BIGINT, UNICODE(RIGHT(LEFT(CONVERT(NVARCHAR(256), j.owner_sid), 14), 1))) * CONVERT(BIGINT, 65536) + CONVERT(BIGINT, NULLIF(SIGN(LEN(CONVERT(NVARCHAR(256), j.owner_sid)) - 14), -1)) * 0), '')) --SHOW as NT SID when unresolved
     , a.start_execution_date
     , a.stop_execution_date
     , t.subsystem
     , t.step_name
FROM msdb.dbo.sysjobs j
    LEFT OUTER JOIN (SELECT DISTINCT * FROM #list_running_SQL_jobs) r
        ON j.job_id = r.job_id
    LEFT OUTER JOIN msdb.dbo.sysjobactivity a
        ON j.job_id = a.job_id
            AND a.start_execution_date IS NOT NULL
            --AND a.stop_execution_date IS NULL
            AND NOT EXISTS
            (
                SELECT *
                FROM msdb.dbo.sysjobactivity at
                WHERE at.job_id = a.job_id
                    AND at.start_execution_date > a.start_execution_date
            )
    LEFT OUTER JOIN sys.dm_exec_sessions p
        ON p.program_name LIKE 'SQLAgent%0x%'
            AND j.job_id = SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 7, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 5, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 3, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 1, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 11, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 9, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 15, 2) + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 13, 2) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 17, 4) + '-' + SUBSTRING(SUBSTRING(p.program_name, CHARINDEX('0x', p.program_name) + 2, 32), 21, 12)
    LEFT OUTER JOIN msdb.dbo.sysjobhistory h
        ON j.job_id = h.job_id
            AND h.instance_id = a.job_history_id
    LEFT OUTER JOIN msdb.dbo.sysjobsteps t
        ON t.job_id = j.job_id
            AND t.step_id = r.current_step
ORDER BY 1;

DROP TABLE #list_running_SQL_jobs;

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

How do you create a Marker with a custom icon for google maps API v3?

Try

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      icon: 'http://imageshack.us/a/img826/9489/x1my.png',
      map: map
    });

from here

https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

Is it possible to put CSS @media rules inline?

Problem

No, Media Queries cannot be used in this way

<span style="@media (...) { ... }"></span>

Solution

But if you want provided a specific behavior usable on the fly AND responsive, you can use the style markup and not the attribute.

e.i.

<style scoped>
.on-the-fly-behavior {
    background-image: url('particular_ad.png'); 
}
@media (max-width: 300px) {
    .on-the-fly-behavior {
        background-image: url('particular_ad_small.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

See the code working in live on CodePen

In my Blog for example, I inject a <style> markup in <head> just after <link> declaration for CSS and it's contain the content of a textarea provided beside of real content textarea for create extra-class on the fly when I wrote an artitle.

Note : the scoped attribute is a part of HTML5 specification. If you do not use it, the validator will blame you but browsers currently not support the real purpose : scoped the content of <style> only on immediatly parent element and that element's child elements. Scoped is not mandatory if the <style> element is in <head> markup.


UPDATE: I advice to always use rules in the mobile first way so previous code should be:

<style scoped>
/* 0 to 299 */
.on-the-fly-behavior {
    background-image: url('particular_ad_small.png'); 
}
/* 300 to X */
@media (min-width: 300px) { /* or 301 if you want really the same as previously.  */
    .on-the-fly-behavior {   
        background-image: url('particular_ad.png');
    }
}
</style>
<span class="on-the-fly-behavior"></span>

How do you rename a Git tag?

You can also rename remote tags without checking them out, by duplicate the old tag/branch to a new name and delete the old one, in a single git push command.

Remote tag rename / Remote branch ? tag conversion: (Notice: :refs/tags/)

git push <remote_name> <old_branch_or_tag>:refs/tags/<new_tag> :<old_branch_or_tag>

Remote branch rename / Remote tag ? branch conversion: (Notice: :refs/heads/)

git push <remote_name> <old_branch_or_tag>:refs/heads/<new_branch> :<old_branch_or_tag>

Output renaming a remote tag:

D:\git.repo>git push gitlab App%2012.1%20v12.1.0.23:refs/tags/App_12.1_v12.1.0.23 :App%2012.1%20v12.1.0.23

Total 0 (delta 0), reused 0 (delta 0)
To https://gitlab.server/project/repository.git
 - [deleted]               App%2012.1%20v12.1.0.23
 * [new tag]               App%2012.1%20v12.1.0.23 -> App_12.1_v12.1.0.23

The type or namespace name could not be found

Other problem that might be causing such behavior are build configurations.

I had two projects with configurations set to be built to specific folders. Like Debug and Any CPU and in second it was Debug and x86.

What I did I went to Solution->Context menu->Properties->Configuration properties->Configuration and I set all my projects to use same configurations Debug and x86 and also checked Build tick mark.

Then projects started to build correctly and were able to see namespaces.

Oracle date difference to get number of years

For Oracle SQL Developer I was able to calculate the difference in years using the below line of SQL. This was to get Years that were within 0 to 10 years difference. You can do a case like shown in some of the other responses to handle your ifs as well. Happy Coding!

TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) > 0 and TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) < 10

expand/collapse table rows with JQuery

I liked the simplest answer provided. However, I didn't like the choppiness of the collapsing. So I combined a solution from this question: How to Use slideDown (or show) function on a table row? to make it a smoother animation when the rows slide up or down. It involves having to wrap the content of each td in a div. This allows it to smoothly animate the collapsing. When the rows are expanded, it will replace the div, with just the content.

So here's the html:

<table>
<tr class="header">
    <td>CARS</td>
</tr>
<tr class="thing">
    <td>car</td>
</tr>
<tr class="thing">
    <td>truck</td>
</tr>
<tr class="header">
    <td>HOUSES</td>
</tr>
<tr class="thing">
    <td>split level</td>
</tr>
<tr class="thing">
    <td>trailer</td>
</tr>

And here's the js

$('.header').click(function(){
if($(this).hasClass("collapsed")){
    $(this).nextUntil('tr.header')
    .find('td')
    .parent()
    .find('td > div')
    .slideDown("fast", function(){
        var $set = $(this);
        $set.replaceWith($set.contents());
    });
    $(this).removeClass("collapsed");
} else {
    $(this).nextUntil('tr.header')
    .find('td')
    .wrapInner('<div style="display: block;" />')
    .parent()
    .find('td > div')
    .slideUp("fast");
    $(this).addClass("collapsed");
}
});

Checkout this fiddle for an example https://jsfiddle.net/p9mtqhm7/52/

Return background color of selected cell

If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:

ActiveCell.DisplayFormat.Interior.Color

This also seems to work just fine on regular cells.

How does a Breadth-First Search work when looking for Shortest Path?

I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS

Want to share the experience.

When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges

#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)

#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path

#3
It does not matter what queue you use
   deque/queue(c++) or
   your own queue implementation (in c language)
   A circular queue is unnecessary

#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.

#5
Wikipedia BFS will work, and is sufficient.
    https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode

I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).


More explanation from the comment below:

      A
     /  \
  B       C
 /\       /\
D  E     F  G

Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G

say, start node is A

  1. when you reach A, to, B & C the shortest distance to B & C from A is 1

  2. when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)

similarly, A->E is 2 (A->B->E)

also, A->F & A->G is 2

So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)

yes, bfs may take any path
but we are calculating for all paths

if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z

Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck


How to set timer in android?

void method(boolean u,int max)
{
    uu=u;
    maxi=max;
    if (uu==true)
    { 
        CountDownTimer uy = new CountDownTimer(maxi, 1000) 
  {
            public void onFinish()
            {
                text.setText("Finish"); 
            }

            @Override
            public void onTick(long l) {
                String currentTimeString=DateFormat.getTimeInstance().format(new Date());
                text.setText(currentTimeString);
            }
        }.start();
    }

    else{text.setText("Stop ");
}

WebView link click open default browser

As this is one of the top questions about external redirect in WebView, here is a "modern" solution on Kotlin:

webView.webViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            val url = request?.url ?: return false
            //you can do checks here e.g. url.host equals to target one
            startActivity(Intent(Intent.ACTION_VIEW, url))
            return true
        }
    }

How To Upload Files on GitHub

To upload files to your repo without using the command-line, simply type this after your repository name in the browser:

https://github.com/yourname/yourrepositoryname/upload/master

and then drag and drop your files.(provided you are on github and the repository has been created beforehand)

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

// The answer that I was looking for when searching
public void Answer()
{
    IEnumerable<YourClass> first = this.GetFirstIEnumerableList();
    // Assign to empty list so we can use later
    IEnumerable<YourClass> second = new List<YourClass>();

    if (IwantToUseSecondList)
    {
        second = this.GetSecondIEnumerableList();  
    }
    IEnumerable<SchemapassgruppData> concatedList = first.Concat(second);
}

How to rollback just one step using rake db:migrate

Roll back the most recent migration:

rake db:rollback

Roll back the n most recent migrations:

rake db:rollback STEP=n

You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.


Here's some more:

  • rake db:migrate - Run all migrations that haven't been run already
  • rake db:migrate VERSION=20080906120000 - Run all necessary migrations (up or down) to get to the given version
  • rake db:migrate RAILS_ENV=test - Run migrations in the given environment
  • rake db:migrate:redo - Roll back one migration and run it again
  • rake db:migrate:redo STEP=n - Roll back the last n migrations and run them again
  • rake db:migrate:up VERSION=20080906120000 - Run the up method for the given migration
  • rake db:migrate:down VERSION=20080906120000 - Run the down method for the given migration

And to answer your question about where you get a migration's version number from:

The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run

$ rake db:migrate VERSION=20080906120000

(From Running Migrations in the Rails Guides)

PHP - Getting the index of a element from a array

I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka 's answer, but solving the 2x looping of the array.

What you can do is create an array with all your keys, in the order they exist, and then loop through that.

        $keys=array_keys($items);
        foreach($keys as $index=>$key){
                    echo "position: $index".PHP_EOL."item: ".PHP_EOL;
                    var_dump($items[$key]);
                    ...
        }

PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else

Using Tempdata in ASP.NET MVC - Best practice

Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.

The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx

Create pandas Dataframe by appending one row at a time

NEVER grow a DataFrame!

Yes, people have already explained that you should NEVER grow a DataFrame, and that you should append your data to a list and convert it to a DataFrame once at the end. But do you understand why?

Here are the most important reasons, taken from my post here.

  1. It is always cheaper/faster to append to a list and create a DataFrame in one go.
  2. Lists take up less memory and are a much lighter data structure to work with, append, and remove.
  3. dtypes are automatically inferred for your data. On the flip side, creating an empty frame of NaNs will automatically make them object, which is bad.
  4. An index is automatically created for you, instead of you having to take care to assign the correct index to the row you are appending.

This is The Right Way™ to accumulate your data

data = []
for a, b, c in some_function_that_yields_data():
    data.append([a, b, c])

df = pd.DataFrame(data, columns=['A', 'B', 'C'])

These options are horrible

  1. append or concat inside a loop

    append and concat aren't inherently bad in isolation. The problem starts when you iteratively call them inside a loop - this results in quadratic memory usage.

    # Creates empty DataFrame and appends
    df = pd.DataFrame(columns=['A', 'B', 'C'])
    for a, b, c in some_function_that_yields_data():
        df = df.append({'A': i, 'B': b, 'C': c}, ignore_index=True)  
        # This is equally bad:
        # df = pd.concat(
        #       [df, pd.Series({'A': i, 'B': b, 'C': c})], 
        #       ignore_index=True)
    
  2. Empty DataFrame of NaNs

    Never create a DataFrame of NaNs as the columns are initialized with object (slow, un-vectorizable dtype).

    # Creates DataFrame of NaNs and overwrites values.
    df = pd.DataFrame(columns=['A', 'B', 'C'], index=range(5))
    for a, b, c in some_function_that_yields_data():
        df.loc[len(df)] = [a, b, c]
    

The Proof is in the Pudding

Timing these methods is the fastest way to see just how much they differ in terms of their memory and utility.

enter image description here

Benchmarking code for reference.


It's posts like this that remind me why I'm a part of this community. People understand the importance of teaching folks getting the right answer with the right code, not the right answer with wrong code. Now you might argue that it is not an issue to use loc or append if you're only adding a single row to your DataFrame. However, people often look to this question to add more than just one row - often the requirement is to iteratively add a row inside a loop using data that comes from a function (see related question). In that case it is important to understand that iteratively growing a DataFrame is not a good idea.

Change table header color using bootstrap

//use css
.blue {
    background-color:blue !important;
}
.blue th {
    color:white !important;
}

//html
<table class="table blue">.....</table>

How do I get the MAX row with a GROUP BY in LINQ query?

        using (DataContext dc = new DataContext())
        {
            var q = from t in dc.TableTests
                    group t by t.SerialNumber
                        into g
                        select new
                        {
                            SerialNumber = g.Key,
                            uid = (from t2 in g select t2.uid).Max()
                        };
        }