Programs & Examples On #Encodeuricomponent

encodeURIComponent is a core JavaScript function that escapes special characters in strings so that they can be safely used in URIs as components of query strings or hashes.

How to encode URL parameters?

Using new ES6 Object.entries(), it makes for a fun little nested map/join:

_x000D_
_x000D_
const encodeGetParams = p => _x000D_
  Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");_x000D_
_x000D_
const params = {_x000D_
  user: "María Rodríguez",_x000D_
  awesome: true,_x000D_
  awesomeness: 64,_x000D_
  "ZOMG+&=*(": "*^%*GMOZ"_x000D_
};_x000D_
_x000D_
console.log("https://example.com/endpoint?" + encodeGetParams(params))
_x000D_
_x000D_
_x000D_

When should I use mmap for file access?

Memory mapping has a potential for a huge speed advantage compared to traditional IO. It lets the operating system read the data from the source file as the pages in the memory mapped file are touched. This works by creating faulting pages, which the OS detects and then the OS loads the corresponding data from the file automatically.

This works the same way as the paging mechanism and is usually optimized for high speed I/O by reading data on system page boundaries and sizes (usually 4K) - a size for which most file system caches are optimized to.

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

What are the differences between type() and isinstance()?

According to python documentation here is a statement:

8.15. types — Names for built-in types

Starting in Python 2.2, built-in factory functions such as int() and str() are also names for the corresponding types.

So isinstance() should be preferred over type().

How do I find out what type each object is in a ArrayList<Object>?

You can use the getClass() method, or you can use instanceof. For example

for (Object obj : list) {
  if (obj instanceof String) {
   ...
  }
}

or

for (Object obj : list) {
 if (obj.getClass().equals(String.class)) {
   ...
 }
}

Note that instanceof will match subclasses. For instance, of C is a subclass of A, then the following will be true:

C c = new C();
assert c instanceof A;

However, the following will be false:

C c = new C();
assert !c.getClass().equals(A.class)

Error "initializer element is not constant" when trying to initialize variable with const

I had this error in code that looked like this:

int A = 1;
int B = A;

The fix is to change it to this

int A = 1;
#define B A

The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.

How to display image from URL on Android

InputStream URLcontent = (InputStream) new URL(url).getContent();
Drawable image = Drawable.createFromStream(URLcontent, "your source link");

this has worked for me

Refresh or force redraw the fragment

This worked for me from within Fragment:

Fragment frg = null;
Class fragmentClass;
fragmentClass = MainFragment.class;

try {
    frg = (android.support.v4.app.Fragment)     
    fragmentClass.newInstance();
} catch(Exception ex) {
    ex.printStackTrace();
}

getFragmentManager()
    .beginTransaction()
    .replace(R.id.flContent, frg)
    .commit();

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

Add space between cells (td) using css

cellspacing (distance between cells) parameter of the TABLE tag is precisely what you want. The disadvantage is it's one value, used both for x and y, you can't choose different spacing or padding vertically/horizontally. There is a CSS property too, but it's not widely supported.

How to print variables without spaces between values

Don't use print ..., if you don't want spaces. Use string concatenation or formatting.

Concatenation:

print 'Value is "' + str(value) + '"'

Formatting:

print 'Value is "{}"'.format(value)

The latter is far more flexible, see the str.format() method documentation and the Formatting String Syntax section.

You'll also come across the older % formatting style:

print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)

but this isn't as flexible as the newer str.format() method.

Fastest way to extract frames using ffmpeg?

In my case I need frames at least every second. I used the 'seek to' approach above but wondered if I could parallelize the task. I used the N processes with FIFO approach here: https://unix.stackexchange.com/questions/103920/parallelize-a-bash-for-loop/216475#216475

open_sem(){
  mkfifo /tmp/pipe-$$
  exec 3<>/tmp/pipe-$$
  rm /tmp/pipe-$$
  local i=$1
  for((;i>0;i--)); do
    printf %s 000 >&3
  done
}
run_with_lock(){
    local x
    read -u 3 -n 3 x && ((0==x)) || exit $x
    (
    "$@" 
    printf '%.3d' $? >&3
    )&
}
N=16
open_sem $N
time for i in {0..39} ; do run_with_lock ffmpeg -ss `echo $i` -i /tmp/input/GOPR1456.MP4  -frames:v 1 /tmp/output/period_down_$i.jpg  & done

Essentially I forked the process with & but limited the number of concurrent threads to N.

This improved the 'seek to' approach from 26 seconds to 16 seconds in my case. The only problem is the main thread does not exit cleanly back to the terminal since stdout gets flooded.

How to hide output of subprocess in Python 2.7

Why not use commands.getoutput() instead?

import commands

text = "Mario Balotelli" 
output = 'espeak "%s"' % text
print text
a = commands.getoutput(output)

Cast object to T

Have you tried Convert.ChangeType?

If the method always returns a string, which I find odd, but that's besides the point, then perhaps this changed code would do what you want:

private static T ReadData<T>(XmlReader reader, string value)
{
    reader.MoveToAttribute(value);
    object readData = reader.ReadContentAsObject();
    return (T)Convert.ChangeType(readData, typeof(T));
}

convert string to number node.js

Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

How do I put hint in a asp:textbox

The placeholder attribute

You're looking for the placeholder attribute. Use it like any other attribute inside your ASP.net control:

<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/>

Don't bother about your IDE (i.e. Visual Studio) maybe not knowing the attribute. Attributes which are not registered with ASP.net are passed through and rendered as is. So the above code (basically) renders to:

<input type="text" placeholder="hint"/>

Using placeholder in resources

A fine way of applying the hint to the control is using resources. This way you may have localized hints. Let's say you have an index.aspx file, your App_LocalResources/index.aspx.resx file contains

<data name="WithHint.placeholder">
    <value>hint</value>
</data>

and your control looks like

<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/>

the rendered result will look the same as the one in the chapter above.

Add attribute in code behind

Like any other attribute you can add the placeholder to the AttributeCollection:

txtWithHint.Attributes.Add("placeholder", "hint");

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

This error occurs if some unit test cases are failing.

In my application, certain unit tests were not compatible with Java 8 so they were failing. My error was resolved after changing jdk1.8.0_92 to jdk1.7.0_80.

The build would succeed with mvn clean install -DskipTests but this will skip the unit tests. So just ensure that you run then separately after the build is complete.

UITableViewCell, show delete button on swipe

In iOS 8 and Swift 2.0 please try this,

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
   // let the controller to know that able to edit tableView's row 
   return true
}

override func tableView(tableView: UITableView, commitEdittingStyle editingStyle UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)  {
   // if you want to apply with iOS 8 or earlier version you must add this function too. (just left in blank code)
}

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?  {
   // add the action button you want to show when swiping on tableView's cell , in this case add the delete button.
   let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: { (action , indexPath) -> Void in

   // Your delete code here.....
   .........
   .........
   })

   // You can set its properties like normal button
   deleteAction.backgroundColor = UIColor.redColor()

   return [deleteAction]
}

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

$(document).ready(function(){
     $("#a").mouseover(function(){
         $("#b").css("background-color", "red");
     });
});

Returning a file to View/Download in ASP.NET MVC

public ActionResult Download()
{
    var document = ...
    var cd = new System.Net.Mime.ContentDisposition
    {
        // for example foo.bak
        FileName = document.FileName, 

        // always prompt the user for downloading, set to true if you want 
        // the browser to try to show the file inline
        Inline = false, 
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File(document.Data, document.ContentType);
}

NOTE: This example code above fails to properly account for international characters in the filename. See RFC6266 for the relevant standardization. I believe recent versions of ASP.Net MVC's File() method and the ContentDispositionHeaderValue class properly accounts for this. - Oskar 2016-02-25

Actionbar notification count icon (badge) like Google has

I don't like ActionView based solutions, my idea is:

  1. create a layout with TextView, that TextView will be populated by application
  2. when you need to draw a MenuItem:

    2.1. inflate layout

    2.2. call measure() & layout() (otherwise view will be 0px x 0px, it's too small for most use cases)

    2.3. set the TextView's text

    2.4. make "screenshot" of the view

    2.6. set MenuItem's icon based on bitmap created on 2.4

  3. profit!

so, result should be something like enter image description here

  1. create layout here is a simple example
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/counterPanel"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:background="@drawable/ic_menu_gallery">
    <RelativeLayout
        android:id="@+id/counterValuePanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/counterBackground"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/unread_background" />

        <TextView
            android:id="@+id/count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1"
            android:textSize="8sp"
            android:layout_centerInParent="true"
            android:textColor="#FFFFFF" />
    </RelativeLayout>
</FrameLayout>

@drawable/unread_background is that green TextView's background, @drawable/ic_menu_gallery is not really required here, it's just to preview layout's result in IDE.

  1. add code into onCreateOptionsMenu/onPrepareOptionsMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
    
        MenuItem menuItem = menu.findItem(R.id.testAction);
        menuItem.setIcon(buildCounterDrawable(count, R.drawable.ic_menu_gallery));
    
        return true;
    }
    
  2. Implement build-the-icon method:

    private Drawable buildCounterDrawable(int count, int backgroundImageId) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.counter_menuitem_layout, null);
        view.setBackgroundResource(backgroundImageId);
    
        if (count == 0) {
            View counterTextPanel = view.findViewById(R.id.counterValuePanel);
            counterTextPanel.setVisibility(View.GONE);
        } else {
            TextView textView = (TextView) view.findViewById(R.id.count);
            textView.setText("" + count);
        }
    
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
    
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
    
        return new BitmapDrawable(getResources(), bitmap);
    }
    

The complete code is here: https://github.com/cvoronin/ActionBarMenuItemCounter

How to write to a CSV line by line?

You could just write to the file as you would write any normal file.

with open('csvfile.csv','wb') as file:
    for l in text:
        file.write(l)
        file.write('\n')

If just in case, it is a list of lists, you could directly use built-in csv module

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

How to shutdown a Spring Boot Application in a correct way?

Spring Boot now supports graceful shut down (currently in pre-release versions, 2.3.0.BUILD-SNAPSHOT)

When enabled, shutdown of the application will include a grace period of configurable duration. During this grace period, existing requests will be allowed to complete but no new requests will be permitted

You can enable it with:

server.shutdown.grace-period=30s

https://docs.spring.io/spring-boot/docs/2.3.0.BUILD-SNAPSHOT/reference/html/spring-boot-features.html#boot-features-graceful-shutdown

How to Find App Pool Recycles in Event Log

IIS version 8.5 +

To enable Event Tracing for Windows for your website/application

  1. Go to Logging and ensure either ETW event only or Both log file and ETW event ...is selected.

enter image description here

  1. Enable the desired Recycle logs in the Advanced Settings for the Application Pool:

enter image description here

  1. Go to the default Custom View: WebServer filters IIS logs:

Custom Views > ServerRoles > Web Server

enter image description here

  1. ... or System logs:

Windows Logs > System

Change One Cell's Data in mysql

UPDATE TABLE <tablename> SET <COLUMN=VALUE> WHERE <CONDITION>

Example:

UPDATE TABLE teacher SET teacher_name='NSP' WHERE teacher_id='1'

close fxml window by code, javafx

I implemented this in the following way after receiving a NullPointerException from the accepted answer.

In my FXML:

<Button onMouseClicked="#onMouseClickedCancelBtn" text="Cancel">

In my Controller class:

@FXML public void onMouseClickedCancelBtn(InputEvent e) {
    final Node source = (Node) e.getSource();
    final Stage stage = (Stage) source.getScene().getWindow();
    stage.close();
}

Cannot find the declaration of element 'beans'

I had this issue and the root cause turned out to be white-space (shown as dots below) after the www.springframework.org/schema/beans reference in xsi:schemaLocation, i.e.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans....
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

How does the ARM architecture differ from x86?

Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.

As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.

There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).

ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.

At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).

Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.

ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.

Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.

So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.

use mysql SUM() in a WHERE clause

When using aggregate functions to filter, you must use a HAVING statement.

SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500

jquery get all form elements: input, textarea & select

This is my favorite function and it works like a charm for me!

It returns an object with all for input, select and textarea data.

And it's trying to getting objects name by look for elements name else Id else class.

var All_Data = Get_All_Forms_Data();
console.log(All_Data);

Function:

function Get_All_Forms_Data(Element)
{
    Element = Element || '';
    var All_Page_Data = {};
    var All_Forms_Data_Temp = {};
    if(!Element)
    {
        Element = 'body';
    }

    $(Element).find('input,select,textarea').each(function(i){
        All_Forms_Data_Temp[i] = $(this);
    });

    $.each(All_Forms_Data_Temp,function(){
        var input = $(this);
        var Element_Name;
        var Element_Value;

        if((input.attr('type') == 'submit') || (input.attr('type') == 'button'))
        {
            return true;
        }

        if((input.attr('name') !== undefined) && (input.attr('name') != ''))
        {
            Element_Name = input.attr('name').trim();
        }
        else if((input.attr('id') !== undefined) && (input.attr('id') != ''))
        {
            Element_Name = input.attr('id').trim();
        }
        else if((input.attr('class') !== undefined) && (input.attr('class') != ''))
        {
            Element_Name = input.attr('class').trim();
        }

        if(input.val() !== undefined)
        {
            if(input.attr('type') == 'checkbox')
            {
                Element_Value = input.parent().find('input[name="'+Element_Name+'"]:checked').val();
            }
            else if((input.attr('type') == 'radio'))
            {
                Element_Value = $('input[name="'+Element_Name+'"]:checked',Element).val();
            }
            else
            {
                Element_Value = input.val();
            }
        }
        else if(input.text() != undefined)
        {
            Element_Value = input.text();
        }

        if(Element_Value === undefined)
        {
            Element_Value = '';
        }

        if(Element_Name !== undefined)
        {
            var Element_Array = new Array();
            if(Element_Name.indexOf(' ') !== -1)
            {
                Element_Array = Element_Name.split(/(\s+)/);
            }
            else
            {
                Element_Array.push(Element_Name);
            }

            $.each(Element_Array,function(index, Name)
            {
                Name = Name.trim();
                if(Name != '')
                {
                    All_Page_Data[Name] = Element_Value;
                }
            });
        }
    });
    return All_Page_Data;
}

ping response "Request timed out." vs "Destination Host unreachable"

As khaos said, a destination unreachable could also mean that something is blocking the way from or to your destination. For example an ACL that filters bad IP addresses.

How can I check for "undefined" in JavaScript?

I use it as a function parameter and exclude it on function execution that way I get the "real" undefined. Although it does require you to put your code inside a function. I found this while reading the jQuery source.

undefined = 2;

(function (undefined) {
   console.log(undefined); // prints out undefined
   // and for comparison:
   if (undeclaredvar === undefined) console.log("it works!")
})()

Of course you could just use typeof though. But all my code is usually inside a containing function anyways, so using this method probably saves me a few bytes here and there.

Conditional logic in AngularJS template

You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?

<div class="from" ng-show="message.from">From: {{message.from.name}}</div>

Use of ~ (tilde) in R programming Language

R defines a ~ (tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:

library(datasets)
lm( myFormula, data=iris)

help("~") or help("formula") will teach you more.

@Spacedman has covered the basics. Let's discuss how it works.

First, being an operator, note that it is essentially a shortcut to a function (with two arguments):

> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs

That can be helpful to know for use in e.g. apply family commands.

Second, you can manipulate the formula as text:

oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )

Third, you can manipulate it as a list:

myFormula[[2]]
myFormula[[3]]

Finally, there are some helpful tricks with formulae (see help("formula") for more):

myFormula <- Species ~ . 

For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.

How to export data as CSV format from SQL Server using sqlcmd?

This answer builds on the solution from @iain-elder, which works well except for the large database case (as pointed out in his solution). The entire table needs to fit in your system's memory, and for me this was not an option. I suspect the best solution would use the System.Data.SqlClient.SqlDataReader and a custom CSV serializer (see here for an example) or another language with an MS SQL driver and CSV serialization. In the spirit of the original question which was probably looking for a no dependency solution, the PowerShell code below worked for me. It is very slow and inefficient especially in instantiating the $data array and calling Export-Csv in append mode for every $chunk_size lines.

$chunk_size = 10000
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = "SELECT * FROM <TABLENAME>"
$command.Connection = $connection
$connection.open()
$reader = $command.ExecuteReader()

$read = $TRUE
while($read){
    $counter=0
    $DataTable = New-Object System.Data.DataTable
    $first=$TRUE;
    try {
        while($read = $reader.Read()){

            $count = $reader.FieldCount
            if ($first){
                for($i=0; $i -lt $count; $i++){
                    $col = New-Object System.Data.DataColumn $reader.GetName($i)
                    $DataTable.Columns.Add($col)
                }
                $first=$FALSE;
            }

            # Better way to do this?
            $data=@()
            $emptyObj = New-Object System.Object
            for($i=1; $i -le $count; $i++){
                $data +=  $emptyObj
            }

            $reader.GetValues($data) | out-null
            $DataRow = $DataTable.NewRow()
            $DataRow.ItemArray = $data
            $DataTable.Rows.Add($DataRow)
            $counter += 1
            if ($counter -eq $chunk_size){
                break
            }
        }
        $DataTable | Export-Csv "output.csv" -NoTypeInformation -Append
    }catch{
        $ErrorMessage = $_.Exception.Message
        Write-Output $ErrorMessage
        $read=$FALSE
        $connection.Close()
        exit
    }
}
$connection.close()

SQL Server insert if not exists best practice

Normalizing your operational tables as suggested by Transact Charlie, is a good idea, and will save many headaches and problems over time - but there are such things as interface tables, which support integration with external systems, and reporting tables, which support things like analytical processing; and those types of tables should not necessarily be normalized - in fact, very often it is much, much more convenient and performant for them to not be.

In this case, I think Transact Charlie's proposal for your operational tables is a good one.

But I would add an index (not necessarily unique) to CompetitorName in the Competitors table to support efficient joins on CompetitorName for the purposes of integration (loading of data from external sources), and I would put an interface table into the mix: CompetitionResults.

CompetitionResults should contain whatever data your competition results have in it. The point of an interface table like this one is to make it as quick and easy as possible to truncate and reload it from an Excel sheet or a CSV file, or whatever form you have that data in.

That interface table should not be considered part of the normalized set of operational tables. Then you can join with CompetitionResults as suggested by Richard, to insert records into Competitors that don't already exist, and update the ones that do (for example if you actually have more information about competitors, like their phone number or email address).

One thing I would note - in reality, Competitor Name, it seems to me, is very unlikely to be unique in your data. In 200,000 competitors, you may very well have 2 or more David Smiths, for example. So I would recommend that you collect more information from competitors, such as their phone number or an email address, or something which is more likely to be unique.

Your operational table, Competitors, should just have one column for each data item that contributes to a composite natural key; for example it should have one column for a primary email address. But the interface table should have a slot for old and new values for a primary email address, so that the old value can be use to look up the record in Competitors and update that part of it to the new value.

So CompetitionResults should have some "old" and "new" fields - oldEmail, newEmail, oldPhone, newPhone, etc. That way you can form a composite key, in Competitors, from CompetitorName, Email, and Phone.

Then when you have some competition results, you can truncate and reload your CompetitionResults table from your excel sheet or whatever you have, and run a single, efficient insert to insert all the new competitors into the Competitors table, and single, efficient update to update all the information about the existing competitors from the CompetitionResults. And you can do a single insert to insert new rows into the CompetitionCompetitors table. These things can be done in a ProcessCompetitionResults stored procedure, which could be executed after loading the CompetitionResults table.

That's a sort of rudimentary description of what I've seen done over and over in the real world with Oracle Applications, SAP, PeopleSoft, and a laundry list of other enterprise software suites.

One last comment I'd make is one I've made before on SO: If you create a foreign key that insures that a Competitor exists in the Competitors table before you can add a row with that Competitor in it to CompetitionCompetitors, make sure that foreign key is set to cascade updates and deletes. That way if you need to delete a competitor, you can do it and all the rows associated with that competitor will get automatically deleted. Otherwise, by default, the foreign key will require you to delete all the related rows out of CompetitionCompetitors before it will let you delete a Competitor.

(Some people think non-cascading foreign keys are a good safety precaution, but my experience is that they're just a freaking pain in the butt that are more often than not simply a result of an oversight and they create a bunch of make work for DBA's. Dealing with people accidentally deleting stuff is why you have things like "are you sure" dialogs and various types of regular backups and redundant data sources. It's far, far more common to actually want to delete a competitor, whose data is all messed up for example, than it is to accidentally delete one and then go "Oh no! I didn't mean to do that! And now I don't have their competition results! Aaaahh!" The latter is certainly common enough, so, you do need to be prepared for it, but the former is far more common, so the easiest and best way to prepare for the former, imo, is to just make foreign keys cascade updates and deletes.)

Set active tab style with AngularJS

A way to solve this without having to rely on URLs is to add a custom attribute to every partial during $routeProvider configuration, like this:

$routeProvider.
    when('/dashboard', {
        templateUrl: 'partials/dashboard.html',
        controller: widgetsController,
        activetab: 'dashboard'
    }).
    when('/lab', {
        templateUrl: 'partials/lab.html',
        controller: widgetsController,
        activetab: 'lab'
    });

Expose $route in your controller:

function widgetsController($scope, $route) {
    $scope.$route = $route;
}

Set the active class based on the current active tab:

<li ng-class="{active: $route.current.activetab == 'dashboard'}"></li>
<li ng-class="{active: $route.current.activetab == 'lab'}"></li>

How do I print a double value without scientific notation using Java?

Java/Kotlin compiler converts any value greater than 9999999 (greater than or equal to 10 million) to scientific notation ie. Epsilion notation.

Ex: 12345678 is converted to 1.2345678E7

Use this code to avoid automatic conversion to scientific notation:

fun setTotalSalesValue(String total) {
        var valueWithoutEpsilon = total.toBigDecimal()
        /* Set the converted value to your android text view using setText() function */
        salesTextView.setText( valueWithoutEpsilon.toPlainString() )
    }

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

You will have to be careful binding the UI to your custom collection -- the Default CollectionView class only supports single notification of items.

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow.

_x000D_
_x000D_
table {_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
  max-height: 60px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
  <th>head1</th>_x000D_
  <th>head2</th>_x000D_
  <th>head3</th>_x000D_
  <th>head4</th>_x000D_
  </tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
  <table>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Jackson JSON custom serialization for certain fields

In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);

Override age:

public abstract class PersonMixin {
    @JsonSerialize(using = PersonAgeSerializer.class)
    public String age;
}

Do whatever you need with the age:

public class PersonAgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
    }
}

The object 'DF__*' is dependent on column '*' - Changing int to double

I had this error trying to run a migration to work around it I renamed the column and re-generated the migration using

add-migration migrationname -force

in the package manager console. I was then able to run

update-database

successfully.

Twitter Bootstrap carousel different height images cause bouncing arrows

More recently I am testing this CSS source for the Bootstrap carousel

The height set to 380 should be set equal to the biggest/tallest image being displayed...

Please Vote up/down this answer based on usability testing with the following CSS thanks.

/* CUSTOMIZE THE CAROUSEL
-------------------------------------------------- */

/* Carousel base class */
.carousel {
  max-height: 100%;
  max-height: 380px;
  margin-bottom: 60px;
  height:auto;
}
/* Since positioning the image, we need to help out the caption */
.carousel-caption {
  z-index: 10;
    background: rgba(0, 0, 0, 0.45);
}

/* Declare heights because of positioning of img element */
.carousel .item {
  max-height: 100%;
  max-height: 380px;
  background-color: #777;
}
.carousel-inner > .item > img {
 /*  position: absolute;*/
  top: 0;
  left: 0;
  min-width: 40%;
  max-width: 100%;
  max-height: 380px;
  width: auto;
  margin-right:auto;
  margin-left:auto;
  height:auto;

}

UIScrollView Scrollable Content Size Ambiguity

This error took me a while to track down, initially I tried pinning the ScrollView's size but the error message clearly says "content size". I made sure everything I pinned from the top of the ScrollView was also pinned to the bottom. That way the ScrollView can calculate its content height by finding the height of all the objects & constraints. This solved the ambiguous content height, the width is pretty similar... Initially I had most things X centered in the ScrollView, but I had to also pin the objects to the side of the ScrollView. I don't like this because the iPhone6 might have a wider screen but it will remove the 'ambiguous content width' error.

Comparing date part only without comparing time in JavaScript

Comparing with setHours() will be a solution. Sample:

var d1 = new Date();
var d2 = new Date("2019-2-23");
if(d1.setHours(0,0,0,0) == d2.setHours(0,0,0,0)){
    console.log(true)
}else{
    console.log(false)
}

What, why or when it is better to choose cshtml vs aspx?

While the syntax is certainly different between Razor (.cshtml/.vbhtml) and WebForms (.aspx/.ascx), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).

This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.

Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.

How to make child element higher z-index than parent?

This is impossible as a child's z-index is set to the same stacking index as its parent.

You have already solved the problem by removing the z-index from the parent, keep it like this or make the element a sibling instead of a child.

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

In case anyone else comes by this issue, the default port on MAMP for mysql is 8889, but the port that php expects to use for mysql is 3306. So you need to open MAMP, go to preferences, and change the MAMP mysql port to 3306, then restart the mysql server. Now the connection should be successful with host=localhost, user=root, pass=root.

Testing pointers for validity (C/C++)

In general, it's impossible to do. Here's one particularly nasty case:

struct Point2d {
    int x;
    int y;
};

struct Point3d {
    int x;
    int y;
    int z;
};

void dump(Point3 *p)
{
    printf("[%d %d %d]\n", p->x, p->y, p->z);
}

Point2d points[2] = { {0, 1}, {2, 3} };
Point3d *p3 = reinterpret_cast<Point3d *>(&points[0]);
dump(p3);

On many platforms, this will print out:

[0 1 2]

You're forcing the runtime system to incorrectly interpret bits of memory, but in this case it's not going to crash, because the bits all make sense. This is part of the design of the language (look at C-style polymorphism with struct inaddr, inaddr_in, inaddr_in6), so you can't reliably protect against it on any platform.

How to know which is running in Jupyter notebook?

import sys
print(sys.executable)
print(sys.version)
print(sys.version_info)

Seen below :- output when i run JupyterNotebook outside a CONDA venv

/home/dhankar/anaconda2/bin/python
2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:42:40) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
 

Seen below when i run same JupyterNoteBook within a CONDA Venv created with command --

conda create -n py35 python=3.5 ## Here - py35 , is name of my VENV

in my Jupyter Notebook it prints :-

/home/dhankar/anaconda2/envs/py35/bin/python
3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)

also if you already have various VENV's created with different versions of Python you switch to the desired Kernel by choosing KERNEL >> CHANGE KERNEL from within the JupyterNotebook menu... JupyterNotebookScreencapture

Also to install ipykernel within an existing CONDA Virtual Environment -

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments

Source --- https://github.com/jupyter/notebook/issues/1524

 $ /path/to/python -m  ipykernel install --help
 usage: ipython-kernel-install [-h] [--user] [--name NAME]
                          [--display-name DISPLAY_NAME]
                          [--profile PROFILE] [--prefix PREFIX]
                          [--sys-prefix]

Install the IPython kernel spec.

optional arguments: -h, --help show this help message and exit --user Install for the current user instead of system-wide --name NAME Specify a name for the kernelspec. This is needed to have multiple IPython kernels at the same time. --display-name DISPLAY_NAME Specify the display name for the kernelspec. This is helpful when you have multiple IPython kernels. --profile PROFILE Specify an IPython profile to load. This can be used to create custom versions of the kernel. --prefix PREFIX Specify an install prefix for the kernelspec. This is needed to install into a non-default location, such as a conda/virtual-env. --sys-prefix Install to Python's sys.prefix. Shorthand for --prefix='/Users/bussonniermatthias/anaconda'. For use in conda/virtual-envs.

How to properly and completely close/reset a TcpClient connection?

The correct way to close the socket so you can re-open is:

tcpClient.Client.Disconnect(true);

The Boolean parameter indicates if you want to reuse the socket:

Disconnect method usage

How to update a menu item shown in the ActionBar?

First please follow the two lines of codes to update the action bar items before that you should set a condition in oncreateOptionMenu(). For example:

Boolean mISQuizItemSelected = false;

/**
 * Called to inflate the action bar menus
 *
 * @param menu
 *      the menu
 *
 * @return true, if successful
 */

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu items for use in the action bar

    inflater.inflate(R.menu.menu_demo, menu);

    //condition to hide the menus
    if (mISQuizItemSelected) {
        for (int i = 0; i < menu.size(); i++) {
            menu.getItem(i).setVisible(false);
        }
    }

    return super.onCreateOptionsMenu(menu);
}

/**
 * Called when the item on the action bar being selected.
 *
 * @param item
 *      menuitem being selected
 *
 * @return true if the menuitem id being selected is matched
 * false if none of the menuitems id are matched
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getId() == R.id.action_quiz) {
        //to navigate based on the usertype either learner or leo
        mISQuizItemSelected = true;

        ActionBar actionBar = getActionBar();
        invalidateOptionMenu();
    }
}

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

How to convert OutputStream to InputStream?

An OutputStream is one where you write data to. If some module exposes an OutputStream, the expectation is that there is something reading at the other end.

Something that exposes an InputStream, on the other hand, is indicating that you will need to listen to this stream, and there will be data that you can read.

So it is possible to connect an InputStream to an OutputStream

InputStream----read---> intermediateBytes[n] ----write----> OutputStream

As someone metioned, this is what the copy() method from IOUtils lets you do. It does not make sense to go the other way... hopefully this makes some sense

UPDATE:

Of course the more I think of this, the more I can see how this actually would be a requirement. I know some of the comments mentioned Piped input/ouput streams, but there is another possibility.

If the output stream that is exposed is a ByteArrayOutputStream, then you can always get the full contents by calling the toByteArray() method. Then you can create an input stream wrapper by using the ByteArrayInputStream sub-class. These two are pseudo-streams, they both basically just wrap an array of bytes. Using the streams this way, therefore, is technically possible, but to me it is still very strange...

Server unable to read htaccess file, denying access to be safe

Just my solution. I had extracted a file, had some minor changes, and got the error above. Deleted everything, uploaded and extracted again, and normal business.

What is the difference between & and && in Java?

boolean a, b;

Operation     Meaning                       Note
---------     -------                       ----
   a && b     logical AND                    short-circuiting
   a || b     logical OR                     short-circuiting
   a &  b     boolean logical AND            not short-circuiting
   a |  b     boolean logical OR             not short-circuiting
   a ^  b     boolean logical exclusive OR
  !a          logical NOT

short-circuiting        (x != 0) && (1/x > 1)   SAFE
not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE

Get value of c# dynamic property via string

In .Net core 3.1 you can try like this

d?.value2 , d?.value3

Python Prime number checker

Your problem is that the loop continues to run even thought you've "made up your mind" already. You should add the line break after a=a+1

Back to previous page with header( "Location: " ); in PHP

try:

header('Location: ' . $_SERVER['HTTP_REFERER']);

Note that this may not work with secure pages (HTTPS) and it's a pretty bad idea overall as the header can be hijacked, sending the user to some other destination. The header may not even be sent by the browser.

Ideally, you will want to either:

  • Append the return address to the request as a query variable (eg. ?back=/list)
  • Define a return page in your code (ie. all successful form submissions redirect to the listing page)
  • Provide the user the option of where they want to go next (eg. Save and continue editing or just Save)

How to get element by class name?

you can use

getElementsByClassName

suppose you have some elements and applied a class name 'test', so, you can get elements like as following

var tests = document.getElementsByClassName('test');

its returns an instance NodeList, or its superset: HTMLCollection (FF).

Read more

Create Django model or update if exists

This should be the answer you are looking for

EmployeeInfo.objects.update_or_create(
    #id or any primary key:value to search for
    identifier=your_id, 
    #if found update with the following or save/create if not found
    defaults={'name':'your_name'}
)

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

How to correctly iterate through getElementsByClassName

If you use the new querySelectorAll you can call forEach directly.

document.querySelectorAll('.edit').forEach(function(button) {
    // Now do something with my button
});

Per the comment below. nodeLists do not have a forEach function.

If using this with babel you can add Array.from and it will convert non node lists to a forEach array. Array.from does not work natively in browsers below and including IE 11.

Array.from(document.querySelectorAll('.edit')).forEach(function(button) {
    // Now do something with my button
});

At our meetup last night I discovered another way to handle node lists not having forEach

[...document.querySelectorAll('.edit')].forEach(function(button) {
    // Now do something with my button
});

Browser Support for [...]

Showing as Node List

Showing as Node List

Showing as Array

Showing as Array

How to add a RequiredFieldValidator to DropDownList control?

If you are using a data source, here's another way to do it without code behind.

Note the following key points:

  • The ListItem of Value="0" is on the source page, not added in code
  • The ListItem in the source will be overwritten if you don't include AppendDataBoundItems="true" in the DropDownList
  • InitialValue="0" tells the validator that this is the value that should fire that validator (as pointed out in other answers)

Example:

<asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
                  DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType" 
                            InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="sdsType" runat="server" 
                   ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
                   SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>

What does HTTP/1.1 302 mean exactly?

According to RFC 1945/Hypertext Transfer Protocol - HTTP / 1.0:

   302 Moved Temporarily

   The requested resource resides temporarily under a different URL.
   Since the redirection may be altered on occasion, the client should
   continue to use the Request-URI for future requests.

   The URL must be given by the Location field in the response. Unless
   it was a HEAD request, the Entity-Body of the response should
   contain a short note with a hyperlink to the new URI(s).

   If the 302 status code is received in response to a request using
   the POST method, the user agent must not automatically redirect the
   request unless it can be confirmed by the user, since this might
   change the conditions under which the request was issued.

       Note: When automatically redirecting a POST request after
       receiving a 302 status code, some existing user agents will
       erroneously change it into a GET request.

getting the table row values with jquery

All Elements

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

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

I can see great answers, so there's no need to repeat here, so I'd like to offer some advice:

I would recommend using a Unix Timestamp integer instead of a human-readable date format to handle time internally, then use PHP's date() function to convert the timestamp value into a human-readable date format for user display. Here's a crude example of how it should be done:

// Get unix timestamp in seconds
$current_time = date();

// Or if you need millisecond precision

// Get unix timestamp in milliseconds
$current_time = microtime(true);

Then use $current_time as needed in your app (store, add or subtract, etc), then when you need to display the date value it to your users, you can use date() to specify your desired date format:

// Display a human-readable date format
echo date('d-m-Y', $current_time);

This way you'll avoid much headache dealing with date formats, conversions and timezones, as your dates will be in a standardized format (Unix Timestamp) that is compact, timezone-independent (always in UTC) and widely supported in programming languages and databases.

How to resolve "gpg: command not found" error during RVM installation?

You can also use:

$ sudo gem install rvm

It should give you the following output:

Fetching: rvm-1.11.3.9.gem (100%)
Successfully installed rvm-1.11.3.9
Parsing documentation for rvm-1.11.3.9
Installing ri documentation for rvm-1.11.3.9
1 gem installed

Android WebView not loading an HTTPS URL

Remove the below code it will work

 super.onReceivedSslError(view, handler, error);

Quickly create large file on a Windows system

PowerShell one-liner to create a file in C:\Temp to fill disk C: leaving only 10 MB:

[io.file]::Create("C:\temp\bigblob.txt").SetLength((gwmi Win32_LogicalDisk -Filter "DeviceID='C:'").FreeSpace - 10MB).Close

HTTP POST using JSON in Java

For Java 11 you can use new HTTP client:

 HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost/api"))
        .header("Content-Type", "application/json")
        .POST(ofInputStream(() -> getClass().getResourceAsStream(
            "/some-data.json")))
        .build();

    client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();

You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

Android Google Maps v2 - set zoom level for myLocation

Slightly different solution than HeatfanJohn's, where I change the zoom relatively to the current zoom level:

// Zoom out just a little
map.animateCamera(CameraUpdateFactory.zoomTo(map.getCameraPosition().zoom - 0.5f));

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

In Perl, how to remove ^M from a file?

Slightly unrelated, but to remove ^M from the command line using Perl, do this:

perl -p -i -e "s/\r\n/\n/g" file.name

Find and replace - Add carriage return OR Newline

Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.

So, if you are doing a find, or a replace, consider the "\r".

For a little more detail on "\r" and "\n", see: https://stackoverflow.com/a/3451192/4427457

Updating Python on Mac

On a mac use the following in the terminal to update python if you have anaconda:

conda update python

How to turn off magic quotes on shared hosting?

I know I'm late to answer this, but I read most of the answers and while many were great, only djn actually explained why you were getting this 500 Internal Server Error.

While his explanation was 100% correct, this is a perfect example of why you should always wrap those in an <IfModule>. While this won't fix the actual problem of not being able to set those flags in your .htaccess, it will at least prevent the 500 error.

<IfModule mod_php5.c>
    # put all of your php_flags here, for example:
    php_flag magic_quotes_gpc off
</IfModule>

Or for older versions it would be <IfModule mod_php.c> etc.

I try to make a habit out of always doing this so as to avoid any such 500 errors. After that, just apply what Peter Bailey said.

How to auto generate migrations with Sequelize CLI from Sequelize models?

As of 16/9/2020 most of these answers are not too much consistent any way! Try this new npm package

Sequelize-mig

It completed most known problems in sequelize-auto-migrations and its forks and its maintained and documented!

Its used in a way similar to the known one

Install:

npm install sequelize-mig -g / yarn global add sequelize-mig

then use it like this

sequelize-mig migration:make -n <migration name>

Replace a string in a file with nodejs

Perhaps the "replace" module (www.npmjs.org/package/replace) also would work for you. It would not require you to read and then write the file.

Adapted from the documentation:

// install:

npm install replace 

// require:

var replace = require("replace");

// use:

replace({
    regex: "string to be replaced",
    replacement: "replacement string",
    paths: ['path/to/your/file'],
    recursive: true,
    silent: true,
});

How do I convert an integer to binary in JavaScript?

we can also calculate the binary for positive or negative numbers as below:

_x000D_
_x000D_
function toBinary(n){
    let binary = "";
    if (n < 0) {
      n = n >>> 0;
    }
    while(Math.ceil(n/2) > 0){
        binary = n%2 + binary;
        n = Math.floor(n/2);
    }
    return binary;
}

console.log(toBinary(7));
console.log(toBinary(-7));
_x000D_
_x000D_
_x000D_

How to grep and replace

Usually not with grep, but rather with sed -i 's/string_to_find/another_string/g' or perl -i.bak -pe 's/string_to_find/another_string/g'.

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

SET NAMES utf8 in MySQL?

Thanks @all!

don't use: query("SET NAMES utf8"); this is setup stuff and not a query. put it right afte a connection start with setCharset() (or similar method)

some little thing in parctice:

status:

  • mysql server by default talks latin1
  • your hole app is in utf8
  • connection is made without any extra (so: latin1) (no SET NAMES utf8 ..., no set_charset() method/function)

Store and read data is no problem as long mysql can handle the characters. if you look in the db you will already see there is crap in it (e.g.using phpmyadmin).

until now this is not a problem! (wrong but works often (in europe)) ..

..unless another client/programm or a changed library, which works correct, will read/save data. then you are in big trouble!

Angular bootstrap datepicker date format does not format ng-model value

Finally I got work around to the above problem. angular-strap has exactly the same feature that I am expecting. Just by applying date-format="MM/dd/yyyy" date-type="string" I got my expected behavior of updating ng-model in given format.

<div class="bs-example" style="padding-bottom: 24px;" append-source>
    <form name="datepickerForm" class="form-inline" role="form">
      <!-- Basic example -->
      <div class="form-group" ng-class="{'has-error': datepickerForm.date.$invalid}">
        <label class="control-label"><i class="fa fa-calendar"></i> Date <small>(as date)</small></label>
        <input type="text"  autoclose="true"  class="form-control" ng-model="selectedDate" name="date" date-format="MM/dd/yyyy" date-type="string" bs-datepicker>
      </div>
      <hr>
      {{selectedDate}}
     </form>
</div>

here is working plunk link

how to add css class to html generic control div?

I think the answer of Curt is correct, however, what if you want to add a class to a div that already has a class declared in the ASP.NET code.

Here is my solution for that, it is a generic method so you can call it directly as this:

Asp Net Div declaration:

<div id="divButtonWrapper" runat="server" class="text-center smallbutton fixPad">

Code to add class:

divButtonWrapper.AddClassToHtmlControl("nameOfYourCssClass")

Generic class:

public static class HtmlGenericControlExtensions
{
    public static void AddClassToHtmlControl(this HtmlGenericControl htmlGenericControl, string className)
    {
        if (string.IsNullOrWhiteSpace(className))
            return;

        htmlGenericControl
            .Attributes.Add("class", string.Join(" ", htmlGenericControl
            .Attributes["class"]
            .Split(' ')
            .Except(new[] { "", className })
            .Concat(new[] { className })
            .ToArray()));
    }
}

How to enumerate an enum with String type?

EDIT: Swift Evolution Proposal SE-0194 Derived Collection of Enum Cases proposes a level headed solution to this problem. We see it in Swift 4.2 and newer. The proposal also points out to some workarounds that are similar to some already mentioned here but it might be interesting to see nevertheless.

I will also keep my original post for completeness' sake.


This is yet another approach based on @Peymmankh's answer, adapted to Swift 3.

public protocol EnumCollection: Hashable {}

extension EnumCollection {

public static func allValues() -> [Self] {
    typealias S = Self

    let retVal = AnySequence { () -> AnyIterator<S> in
        var raw = 0
        return AnyIterator {
            let current = withUnsafePointer(to: &raw) {
                 $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee }
            }
            guard current.hashValue == raw else { return nil }
            raw += 1
            return current
        }
    }

    return [S](retVal)
}

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

Fatal error: Call to undefined function sqlsrv_connect()

If you are using Microsoft Drivers 3.1, 3.0, and 2.0. Please check your PHP version already install with IIS.

Use this script to check the php version:

<?php echo phpinfo(); ?>

OR

If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.

Then:
If you are using new PHP version (5.6) please download Drivers from here

For PHP version Lower than 5.6 - please download Drivers from here

  • PHP Driver version 3.1 requires PHP 5.4.32, or PHP 5.5.16, or later.
  • PHP Driver version 3.0 requires PHP 5.3.0 or later. If possible, use PHP 5.3.6, or later.
  • PHP Driver version 2.0 driver works with PHP 5.2.4 or later, but not with PHP 5.4. If possible, use PHP 5.2.13, or later.

Then use the PHP Manager to add that downloaded drivers into php config file.You can do it as shown below (browse the files and press OK). Then Restart the IIS Server

enter image description here

If this method not work please change the php version and try to run your php script. enter image description here

Tip:Change the php version to lower and try to understand what happened.then you can download relevant drivers.

How do I add an existing directory tree to a project in Visual Studio?

Visual Studio 2017 and newer support a new lightweight .csproj format which has come to be known as "SDK format". One of several advantages of this format is that instead of containing a list of files and folders which are included, files are wildcard included by default. Therefore, with this new format, your files and folders - added in Explorer or on the command line - will get picked up automatically!

The SDK format .csproj file currently works with the following project types:

  • Class library projects

  • Console apps

  • ASP.NET Core web apps

  • .NET Core projects of any type

To use the new format, create a new .NET Core or .NET Standard project. Because the templates haven't been updated for the full .NET Framework even in Visual Studio 2019, to create a .NET class library choose the .NET Standard Library template, and then edit the project file to target the framework version of your choice (the new style project format can be edited inside Visual Studio - just right click the project in the Solution Explorer and select "Edit project file"). For example:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net46</TargetFramework>
  </PropertyGroup>
</Project>

Further reading:

To check if string contains particular word

Solution-1: - If you want to search for a combination of characters or an independent word from a sentence.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".*Beneficent.*")) {return true;}
else{return false;}

Solution-2: - There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word. For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true. For this remember to add space in your regular expression.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".* cent .*")) {return true;}
else{return false;}

Now in Solution-2 it wll return false because no independent cent word exist.

Additional: You can add or remove space on either side in 2nd solution according to your requirements.

Loop through JSON object List

had same problem today, Your topic helped me so here goes solution ;)

 alert(result.d[0].EmployeeTitle);

How to delete last character from a string using jQuery?

@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

//-----------------------------------------
// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

How different is Objective-C from C++?

Off the top of my head:

  1. Styles - Obj-C is dynamic, C++ is typically static
  2. Although they are both OOP, I'm certain the solutions would be different.
  3. Different object model (C++ is restricted by its compile-time type system).

To me, the biggest difference is the model system. Obj-C lets you do messaging and introspection, but C++ has the ever-so-powerful templates.

Each have their strengths.

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You can use google map Obtaining User Location here!

After obtaining your location(longitude and latitude), you can use google place api

This code can help you get your location easily but not the best way.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);  

Get the Year/Month/Day from a datetime in php?

Use DateTime with DateTime::format()

$datetime = new DateTime($dateTimeString);
echo $datetime->format('w');

How to create a DB for MongoDB container on start up?

My answer is based on the one provided by @x-yuri; but my scenario it's a little bit different. I wanted an image containing the script, not bind without needing to bind-mount it.

mongo-init.sh -- don't know whether or not is need but but I ran chmod +x mongo-init.sh also:

#!/bin/bash
# https://stackoverflow.com/a/53522699
# https://stackoverflow.com/a/37811764
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
  var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
  var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
  var user = '$MONGO_INITDB_USERNAME';
  var passwd = '$MONGO_INITDB_PASSWORD';

  var admin = db.getSiblingDB('admin');

  admin.auth(rootUser, rootPassword);
  db.createUser({
    user: user,
    pwd: passwd,
    roles: [
      {
        role: "root",
        db: "admin"
      }
    ]
  });
EOF

Dockerfile:

FROM mongo:3.6

COPY mongo-init.sh /docker-entrypoint-initdb.d/mongo-init.sh

CMD [ "/docker-entrypoint-initdb.d/mongo-init.sh" ]

docker-compose.yml:

version: '3'

services:
    mongodb:
        build: .
        container_name: mongodb-test
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=example
            - MONGO_INITDB_USERNAME=myproject
            - MONGO_INITDB_PASSWORD=myproject
            - MONGO_INITDB_DATABASE=myproject

    myproject:
        image: myuser/myimage
        restart: on-failure
        container_name: myproject
        environment:
            - DB_URI=mongodb
            - DB_HOST=mongodb-test
            - DB_NAME=myproject
            - DB_USERNAME=myproject
            - DB_PASSWORD=myproject
            - DB_OPTIONS=
            - DB_PORT=27017            
        ports:
            - "80:80"

After that, I went ahead and publish this Dockefile as an image to use in other projects.

note: without adding the CMD it mongo throws: unbound variable error

Android - styling seek bar

Google have made this easier in SDK 21. Now we have attributes for specifying the thumb tint colors:

android:thumbTint
android:thumbTintMode
android:progressTint

http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTint http://developer.android.com/reference/android/widget/AbsSeekBar.html#attr_android:thumbTintMode

MySQL: Convert INT to DATETIME

select from_unixtime(column,'%Y-%m-%d') from myTable; 

Turning off hibernate logging console output

Important notice: the property (part of hibernate configuration, NOT part of logging framework config!)

hibernate.show_sql

controls the logging directly to STDOUT bypassing any logging framework (which you can recognize by the missing output formatting of the messages). If you use a logging framework like log4j, you should always set that property to false because it gives you no benefit at all.

That circumstance irritated me quite a long time because I never really cared about it until I tried to write some benchmark regarding Hibernate.

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Running the script like this (cron case for example): php5 /pathToScript/info.php produces the same error.

The correct way: php5 -cli /pathToScript/info.php

How to list all the roles existing in Oracle database?

Got the answer :

SELECT * FROM DBA_ROLES;

DataAdapter.Fill(Dataset)

leDbConnection connection = 
new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet1 DS = new DataSet1();
connection.Open();

OleDbDataAdapter DBAdapter = new OleDbDataAdapter(
@"SELECT tbl_Computer.*,  tbl_Besitzer.*
  FROM tbl_Computer 
  INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
  WHERE (((tbl_Besitzer.Vorname)='ma'));", 
connection);

Referring to the null object in Python

In Python, to represent the absence of a value, you can use the None value (types.NoneType.None) for objects and "" (or len() == 0) for strings. Therefore:

if yourObject is None:  # if yourObject == None:
    ...

if yourString == "":  # if yourString.len() == 0:
    ...

Regarding the difference between "==" and "is", testing for object identity using "==" should be sufficient. However, since the operation "is" is defined as the object identity operation, it is probably more correct to use it, rather than "==". Not sure if there is even a speed difference.

Anyway, you can have a look at:

How can I wrap or break long text/word in a fixed width span?

Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.

By defining the the full span as display:inline-block you might have a hard time displaying images.

Therefore I prefer to define a span like so:

span {
  display:block;
  width:150px;
  word-wrap:break-word;      
}
p span, a span,
h1 span, h2 span, h3 span, h4 span, h5 span {
  display:inline-block;
}
img{
  display:block;
}

How does Trello access the user's clipboard?

I actually built a Chrome extension that does exactly this, and for all web pages. The source code is on GitHub.

I find three bugs with Trello's approach, which I know because I've faced them myself :)

The copy doesn't work in these scenarios:

  1. If you already have Ctrl pressed and then hover a link and hit C, the copy doesn't work.
  2. If your cursor is in some other text field in the page, the copy doesn't work.
  3. If your cursor is in the address bar, the copy doesn't work.

I solved #1 by always having a hidden span, rather than creating one when user hits Ctrl/Cmd.

I solved #2 by temporarily clearing the zero-length selection, saving the caret position, doing the copy and restoring the caret position.

I haven't found a fix for #3 yet :) (For information, check the open issue in my GitHub project).

Recommended way to embed PDF in HTML?

just use iFrame for PDF's.

I had specific needs in my React.js app, tried millions of solutions but ended up with an iFrame :) Good luck!

SQLite - UPSERT *not* INSERT or REPLACE

Updates from Bernhardt:

You can indeed do an upsert in SQLite, it just looks a little different than you are used to. It would look something like:

INSERT INTO table_name (id, column1, column2) 
VALUES ("youruuid", "value12", "value2")
ON CONFLICT(id) DO UPDATE 
SET column1 = "value1", column2 = "value2"

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

Trying to mock datetime.date.today(), but not working

For what it's worth, the Mock docs talk about datetime.date.today specifically, and it's possible to do this without having to create a dummy class:

https://docs.python.org/3/library/unittest.mock-examples.html#partial-mocking

>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
...     mock_date.today.return_value = date(2010, 10, 8)
...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
...
...     assert mymodule.date.today() == date(2010, 10, 8)
...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
...

Pan & Zoom Image

Yet another version of the same kind of control. It has similar functionality as the others, but it adds:

  1. Touch support (drag/pinch)
  2. The image can be deleted (normally, the Image control locks the image on disk, so you cannot delete it).
  3. An inner border child, so the panned image doesn't overlap the border. In case of borders with rounded rectangles, look for ClippedBorder classes.

Usage is simple:

<Controls:ImageViewControl ImagePath="{Binding ...}" />

And the code:

public class ImageViewControl : Border
{
    private Point origin;
    private Point start;
    private Image image;

    public ImageViewControl()
    {
        ClipToBounds = true;
        Loaded += OnLoaded;
    }

    #region ImagePath

    /// <summary>
    ///     ImagePath Dependency Property
    /// </summary>
    public static readonly DependencyProperty ImagePathProperty = DependencyProperty.Register("ImagePath", typeof (string), typeof (ImageViewControl), new FrameworkPropertyMetadata(string.Empty, OnImagePathChanged));

    /// <summary>
    ///     Gets or sets the ImagePath property. This dependency property 
    ///     indicates the path to the image file.
    /// </summary>
    public string ImagePath
    {
        get { return (string) GetValue(ImagePathProperty); }
        set { SetValue(ImagePathProperty, value); }
    }

    /// <summary>
    ///     Handles changes to the ImagePath property.
    /// </summary>
    private static void OnImagePathChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var target = (ImageViewControl) d;
        var oldImagePath = (string) e.OldValue;
        var newImagePath = target.ImagePath;
        target.ReloadImage(newImagePath);
        target.OnImagePathChanged(oldImagePath, newImagePath);
    }

    /// <summary>
    ///     Provides derived classes an opportunity to handle changes to the ImagePath property.
    /// </summary>
    protected virtual void OnImagePathChanged(string oldImagePath, string newImagePath)
    {
    }

    #endregion

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        image = new Image {
                              //IsManipulationEnabled = true,
                              RenderTransformOrigin = new Point(0.5, 0.5),
                              RenderTransform = new TransformGroup {
                                                                       Children = new TransformCollection {
                                                                                                              new ScaleTransform(),
                                                                                                              new TranslateTransform()
                                                                                                          }
                                                                   }
                          };
        // NOTE I use a border as the first child, to which I add the image. I do this so the panned image doesn't partly obscure the control's border.
        // In case you are going to use rounder corner's on this control, you may to update your clipping, as in this example:
        // http://wpfspark.wordpress.com/2011/06/08/clipborder-a-wpf-border-that-clips/
        var border = new Border {
                                    IsManipulationEnabled = true,
                                    ClipToBounds = true,
                                    Child = image
                                };
        Child = border;

        image.MouseWheel += (s, e) =>
                                {
                                    var zoom = e.Delta > 0
                                                   ? .2
                                                   : -.2;
                                    var position = e.GetPosition(image);
                                    image.RenderTransformOrigin = new Point(position.X / image.ActualWidth, position.Y / image.ActualHeight);
                                    var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
                                    st.ScaleX += zoom;
                                    st.ScaleY += zoom;
                                    e.Handled = true;
                                };

        image.MouseLeftButtonDown += (s, e) =>
                                         {
                                             if (e.ClickCount == 2)
                                                 ResetPanZoom();
                                             else
                                             {
                                                 image.CaptureMouse();
                                                 var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
                                                 start = e.GetPosition(this);
                                                 origin = new Point(tt.X, tt.Y);
                                             }
                                             e.Handled = true;
                                         };

        image.MouseMove += (s, e) =>
                               {
                                   if (!image.IsMouseCaptured) return;
                                   var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
                                   var v = start - e.GetPosition(this);
                                   tt.X = origin.X - v.X;
                                   tt.Y = origin.Y - v.Y;
                                   e.Handled = true;
                               };

        image.MouseLeftButtonUp += (s, e) => image.ReleaseMouseCapture();

        //NOTE I apply the manipulation to the border, and not to the image itself (which caused stability issues when translating)!
        border.ManipulationDelta += (o, e) =>
                                       {
                                           var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
                                           var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);

                                           st.ScaleX *= e.DeltaManipulation.Scale.X;
                                           st.ScaleY *= e.DeltaManipulation.Scale.X;
                                           tt.X += e.DeltaManipulation.Translation.X;
                                           tt.Y += e.DeltaManipulation.Translation.Y;

                                           e.Handled = true;
                                       };
    }

    private void ResetPanZoom()
    {
        var st = (ScaleTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is ScaleTransform);
        var tt = (TranslateTransform)((TransformGroup)image.RenderTransform).Children.First(tr => tr is TranslateTransform);
        st.ScaleX = st.ScaleY = 1;
        tt.X = tt.Y = 0;
        image.RenderTransformOrigin = new Point(0.5, 0.5);
    }

    /// <summary>
    /// Load the image (and do not keep a hold on it, so we can delete the image without problems)
    /// </summary>
    /// <see cref="http://blogs.vertigo.com/personal/ralph/Blog/Lists/Posts/Post.aspx?ID=18"/>
    /// <param name="path"></param>
    private void ReloadImage(string path)
    {
        try
        {
            ResetPanZoom();
            // load the image, specify CacheOption so the file is not locked
            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.UriSource = new Uri(path, UriKind.RelativeOrAbsolute);
            bitmapImage.EndInit();
            image.Source = bitmapImage;
        }
        catch (SystemException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

How good is Java's UUID.randomUUID?

At a former employer we had a unique column that contained a random uuid. We got a collision the first week after it was deployed. Sure, the odds are low but they aren't zero. That is why Log4j 2 contains UuidUtil.getTimeBasedUuid. It will generate a UUID that is unique for 8,925 years so long as you don't generate more than 10,000 UUIDs/millisecond on a single server.

Issue with background color and Google Chrome

I'm seen this problem with Chrome too, if I remember correctly if you minimize and then maximize your window it fixes it as well?

Haven't really used Chrome too much since it was released but this is definitely something I blame on Google as the code I was checking it on was air tight.

.NET unique object identifier

It is possible to make a unique object identifier in Visual Studio: In the watch window, right-click the object variable and choose Make Object ID from the context menu.

Unfortunately, this is a manual step, and I don't believe the identifier can be accessed via code.

jQuery has deprecated synchronous XMLHTTPRequest

The accepted answer is correct, but I found another cause if you're developing under ASP.NET with Visual Studio 2013 or higher and are sure you didn't make any synchronous ajax requests or define any scripts in the wrong place.

The solution is to disable the "Browser Link" feature by unchecking "Enable Browser Link" in the VS toolbar dropdown indicated by the little refresh icon pointing clockwise. As soon as you do this and reload the page, the warnings should stop!

Disable Browser Link

This should only happen while debugging locally, but it's still nice to know the cause of the warnings.

SQL Row_Number() function in Where Clause

I think you want something like this:

SELECT employee_id 
FROM  (SELECT employee_id, row_number() 
       OVER (order by employee_id) AS 'rownumber' 
       FROM V_EMPLOYEE) TableExpressionsMustHaveAnAliasForDumbReasons
WHERE rownumber > 0

How can I open the interactive matplotlib window in IPython notebook?

I'm using ipython in "jupyter QTConsole" from Anaconda at www.continuum.io/downloads on 5/28/20117.

Here's an example to flip back and forth between a separate window and an inline plot mode using ipython magic.

>>> import matplotlib.pyplot as plt

# data to plot
>>> x1 = [x for x in range(20)]

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Show in separate window
>>> %matplotlib
>>> plt.plot(x1)
>>> plt.close() 

# Show in console window
>>> %matplotlib inline
>>> plt.plot(x1)
>>> plt.close() 

# Note: the %matplotlib magic above causes:
#      plt.plot(...) 
# to implicitly include a:
#      plt.show()
# after the command.
#
# (Not sure how to turn off this behavior
# so that it matches behavior without using %matplotlib magic...)
# but its ok for interactive work...

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

Have you been trying to reference your custom MapFragment class in the layout file?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapFragment"
        android:name="com.nfc.demo.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

EditText, clear focus on touch outside

This is my Version based on zMan's code. It will not hide the keyboard if the next view also is an edit text. It will also not hide the keyboard if the user just scrolls the screen.

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        downX = (int) event.getRawX();
    }

    if (event.getAction() == MotionEvent.ACTION_UP) {
        View v = getCurrentFocus();
        if (v instanceof EditText) {
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();
            //Was it a scroll - If skip all
            if (Math.abs(downX - x) > 5) {
                return super.dispatchTouchEvent(event);
            }
            final int reducePx = 25;
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            //Bounding box is to big, reduce it just a little bit
            outRect.inset(reducePx, reducePx);
            if (!outRect.contains(x, y)) {
                v.clearFocus();
                boolean touchTargetIsEditText = false;
                //Check if another editText has been touched
                for (View vi : v.getRootView().getTouchables()) {
                    if (vi instanceof EditText) {
                        Rect clickedViewRect = new Rect();
                        vi.getGlobalVisibleRect(clickedViewRect);
                        //Bounding box is to big, reduce it just a little bit
                        clickedViewRect.inset(reducePx, reducePx);
                        if (clickedViewRect.contains(x, y)) {
                            touchTargetIsEditText = true;
                            break;
                        }
                    }
                }
                if (!touchTargetIsEditText) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
    }
    return super.dispatchTouchEvent(event);
}

Best way to check if a Data Table has a null value in it

Try comparing the value of the column to the DBNull.Value value to filter and manage null values in whatever way you see fit.

foreach(DataRow row in table.Rows)
{
    object value = row["ColumnName"];
    if (value == DBNull.Value)
        // do something
    else
        // do something else
}

More information about the DBNull class


If you want to check if a null value exists in the table you can use this method:

public static bool HasNull(this DataTable table)
{
    foreach (DataColumn column in table.Columns)
    {
        if (table.Rows.OfType<DataRow>().Any(r => r.IsNull(column)))
            return true;
    }

    return false;
}

which will let you write this:

table.HasNull();

Maven Could not resolve dependencies, artifacts could not be resolved

Turns out that it happened because of the firewall on my computer. Turning it off worked for me.

best way to get folder and file list in Javascript

I don't like adding new package into my project just to handle this simple task.

And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

So I made a function to get all the folder content (and its sub folder).... NON-Recursively

var getDirectoryContent = function(dirPath) {
    /* 
        get list of files and directories from given dirPath and all it's sub directories
        NON RECURSIVE ALGORITHM
        By. Dreamsavior
    */
    var RESULT = {'files':[], 'dirs':[]};

    var fs = fs||require('fs');
    if (Boolean(dirPath) == false) {
        return RESULT;
    }
    if (fs.existsSync(dirPath) == false) {
        console.warn("Path does not exist : ", dirPath);
        return RESULT;
    }

    var directoryList = []
    var DIRECTORY_SEPARATOR = "\\";
    if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;

    directoryList.push(dirPath); // initial

    while (directoryList.length > 0) {
        var thisDir  = directoryList.shift(); 
        if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;

        var thisDirContent = fs.readdirSync(thisDir);
        while (thisDirContent.length > 0) { 
            var thisFile  = thisDirContent.shift(); 
            var objPath = thisDir+thisFile

            if (fs.existsSync(objPath) == false) continue;
            if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                directoryList.push(thisDirPath);
                RESULT['dirs'].push(thisDirPath);

            } else  { // is a file
                RESULT['files'].push(objPath); 

            } 
        } 

    }
    return RESULT;
}

the only drawback of this function is that this is Synchronous function... You have been warned ;)

Google Maps API 3 - Custom marker color for default (dot) marker

Sometimes something really simple, can be answered complex. I am not saying that any of the above answers are incorrect, but I would just apply, that it can be done as simple as this:

I know this question is old, but if anyone just wants to change to pin or marker color, then check out the documentation: https://developers.google.com/maps/documentation/android-sdk/marker

when you add your marker simply set the icon-property:

GoogleMap gMap;
LatLng latLng;
....
// write your code...
....
gMap.addMarker(new MarkerOptions()
    .position(latLng)
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

There are 10 default colors to choose from. If that isn't enough (the simple solution) then I would probably go for the more complex given in the other answers, fulfilling a more complex need.

ps: I've written something similar in another answer and therefore I should refer to that answer, but the last time I did that, I was asked to post the answer since it was so short (as this one)..

Not receiving Google OAuth refresh token

In order to get the refresh token you have to add both approval_prompt=force and access_type="offline" If you are using the java client provided by Google it will look like this:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, getClientSecrets(), scopes)
            .build();

AuthorizationCodeRequestUrl authorizationUrl =
            flow.newAuthorizationUrl().setRedirectUri(callBackUrl)
                    .setApprovalPrompt("force")
                    .setAccessType("offline");

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

I had a similar issue with zsh and nvm on Linux, I fixed it by adding nvm initialization script in ~/.profile and restart login session like this

export NVM_DIR="$HOME/.nvm" 
 [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm 
 [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

TypeScript enum to object array

Here's the simple function with correct typing I use

/**
 * Helper to produce an array of enum values.
 * @param enumeration Enumeration object.
 */
export function enumToArray<T, G extends keyof T = keyof T>(enumeration: T): T[G][] {
  // tslint:disable: comment-format

  // enum Colors {
  //   WHITE = 0,
  //   BLACK = 1,
  // }
  // Object.values(Colors) will produce ['WHITE', 'BLACK', 0, 1]

  // So, simply slice the second half
  const enumValues = Object.values(enumeration);
  return enumValues.slice(enumValues.length / 2, enumValues.length) as T[G][];
}

Usage example:

enum Colors {
  Red = 1,
  Blue = 2,
}
enumToArray(Colors)

Laravel Checking If a Record Exists

The Easiest Way to do

    public function update(Request $request, $id)
{


    $coupon = Coupon::where('name','=',$request->name)->first(); 

    if($coupon->id != $id){
        $validatedData = $request->validate([
            'discount' => 'required',   
            'name' => 'required|unique:coupons|max:255',      
        ]);
    }


    $requestData = $request->all();
    $coupon = Coupon::findOrFail($id);
    $coupon->update($requestData);
    return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}

How to create a fixed-size array of objects

Swift 4

You can somewhat think about it as array of object vs. array of references.

  • [SKSpriteNode] must contain actual objects
  • [SKSpriteNode?] can contain either references to objects, or nil

Examples

  1. Creating an array with 64 default SKSpriteNode:

    var sprites = [SKSpriteNode](repeatElement(SKSpriteNode(texture: nil),
                                               count: 64))
    
  2. Creating an array with 64 empty slots (a.k.a optionals):

    var optionalSprites = [SKSpriteNode?](repeatElement(nil,
                                          count: 64))
    
  3. Converting an array of optionals into an array of objects (collapsing [SKSpriteNode?] into [SKSpriteNode]):

    let flatSprites = optionalSprites.flatMap { $0 }
    

    The count of the resulting flatSprites depends on the count of objects in optionalSprites: empty optionals will be ignored, i.e. skipped.

Unable to Connect to GitHub.com For Cloning

I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:

git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port

Run cURL commands from Windows console

  1. Go to curl Download Wizard
  2. Select curl executable
  3. Select Win32 or Win64
  4. Then select package for it(Eg generic/cygwin) as per your requirement
  5. Then you will have to select version. You can select unspecified.
  6. This will directly take you to download link which on click will give you popup to download the zip file.
  7. Extract the zip to get the executable. Add this folder in your environment variables and you are done. You can then execute curl command from cmd.

Difference between multitasking, multithreading and multiprocessing?

Multitasking - This is basically multiprogramming in the context of a single-user interactive environment, in which the OS switches between several programs in main memory so as to give the illusion that several are running at once. Common scheduling algorithms used for multitasking are: Round-Robin, Priority Scheduling (multiple queues), Shortest-Process-Next.

MULTIPROCESSING is like the OS handling the different jobs in main memory in such a way that it gives its time to each and every job when other is busy for some task such as I/O operation. So as long as at least one job needs to execute, the cpu never sit idle. and here it is automatically handled by the OS,

How to get "GET" request parameters in JavaScript?

Just to put my two cents in, if you wanted an object containing all the requests

function getRequests() {
    var s1 = location.search.substring(1, location.search.length).split('&'),
        r = {}, s2, i;
    for (i = 0; i < s1.length; i += 1) {
        s2 = s1[i].split('=');
        r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
    }
    return r;
};

var QueryString = getRequests();

//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3

Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.

function Request(name){
    return QueryString[name.toLowerCase()];
}

Understanding MongoDB BSON Document size limit

Many in the community would prefer no limit with warnings about performance, see this comment for a well reasoned argument: https://jira.mongodb.org/browse/SERVER-431?focusedCommentId=22283&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-22283

My take, the lead developers are stubborn about this issue because they decided it was an important "feature" early on. They're not going to change it anytime soon because their feelings are hurt that anyone questioned it. Another example of personality and politics detracting from a product in open source communities but this is not really a crippling issue.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Best way to clear a PHP array's values

This is powerful and tested unset($gradearray);//re-set the array

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

tsc is not recognized as internal or external command

The problem is that tsc is not in your PATH if installed locally.

You should modify your .vscode/tasks.json to include full path to tsc.

The line to change is probably equal to "command": "tsc".

You should change it to "command": "node" and add the following to your args: "args": ["${workspaceRoot}\\node_modules\\typescript\\bin\\tsc"] (on Windows).

This will instruct VSCode to:

  1. Run NodeJS (it should be installed globally).
  2. Pass your local Typescript installation as the script to run.

(that's pretty much what tsc executable does)

Are you sure you don't want to install Typescript globally? It should make things easier, especially if you're just starting to use it.

Use underscore inside Angular controllers

When you include Underscore, it attaches itself to the window object, and so is available globally.

So you can use it from Angular code as-is.

You can also wrap it up in a service or a factory, if you'd like it to be injected:

var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
  return $window._; // assumes underscore has already been loaded on the page
}]);

And then you can ask for the _ in your app's module:

// Declare it as a dependency of your module
var app = angular.module('app', ['underscore']);

// And then inject it where you need it
app.controller('Ctrl', function($scope, _) {
  // do stuff
});

How to create localhost database using mysql?

Consider using the MySQL Installer for Windows as it installs and updates the various MySQL products on your system, including MySQL Server, MySQL Workbench, and MySQL Notifier. The Notifier monitors your MySQL instances so you'll know if MySQL is running, and it can also be used to start/stop MySQL.

How can I check if char* variable points to empty string?

An empty string has one single null byte. So test if (s[0] == (char)0)

Youtube autoplay not working on mobile devices with embedded HTML5 player

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512

Html- how to disable <a href>?

<script>
    $(document).ready(function(){
        $('#connectBtn').click(function(e){
            e.preventDefault();
        })
    });
</script>

This will prevent the default action.

Current timestamp as filename in Java

You can use DateTime

import org.joda.time.DateTime

Option 1 : with yyyyMMddHHmmss

DateTime.now().toString("yyyyMMddHHmmss")

Will give 20190205214430

Option 2 : yyyy-dd-M--HH-mm-ss

   DateTime.now().toString("yyyy-dd-M--HH-mm-ss")

will give 2019-05-2--21-43-32

Comparing results with today's date?

Not sure what your asking!

However

SELECT  GETDATE()

Will get you the current date and time

SELECT  DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

Will get you just the date with time set to 00:00:00

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

Remove Object from Array using JavaScript

I guess the answers are very branched and knotted.

You can use the following path to remove an array object that matches the object given in the modern JavaScript jargon.


coordinates = [
    { lat: 36.779098444109145, lng: 34.57202827508546 },
    { lat: 36.778754712956506, lng: 34.56898128564454 },
    { lat: 36.777414146732426, lng: 34.57179224069215 }
];

coordinate = { lat: 36.779098444109145, lng: 34.57202827508546 };

removeCoordinate(coordinate: Coordinate): Coordinate {
    const found = this.coordinates.find((coordinate) => coordinate == coordinate);
    if (found) {
      this.coordinates.splice(found, 1);
    }
    return coordinate;
  }

PHP pass variable to include

I found that the include parameter needs to be the entire file path, not a relative path or partial path for this to work.

what does "error : a nonstatic member reference must be relative to a specific object" mean?

EncodeAndSend is not a static function, which means it can be called on an instance of the class CPMSifDlg. You cannot write this:

 CPMSifDlg::EncodeAndSend(/*...*/);  //wrong - EncodeAndSend is not static

It should rather be called as:

 CPMSifDlg dlg; //create instance, assuming it has default constructor!
 dlg.EncodeAndSend(/*...*/);   //correct 

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

Why doesn't java.io.File have a close method?

The javadoc of the File class describes the class as:

An abstract representation of file and directory pathnames.

File is only a representation of a pathname, with a few methods concerning the filesystem (like exists()) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.

(My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile, causing much confusion with its inconsistent naming.)

How to search for a part of a word with ElasticSearch

Using wilcards (*) prevent the calc of a score

Accessing value inside nested dictionaries

As always in python, there are of course several ways to do it, but there is one obvious way to do it.

tmpdict["ONE"]["TWO"]["THREE"] is the obvious way to do it.

When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.

If you just want to just save you repetative typing, you can of course alias a subset of the dict:

>>> two_dict = tmpdict['ONE']['TWO'] # now you can just write two_dict for tmpdict['ONE']['TWO']
>>> two_dict["spam"] = 23
>>> tmpdict
{'ONE': {'TWO': {'THREE': 10, 'spam': 23}}}

How to retrieve the first word of the output of a command in bash?

echo "word1 word2" | cut -f 1 -d " "

cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")

Where to put default parameter value in C++?

Although this is an "old" thread, I still would like to add the following to it:

I've experienced the next case:

  • In the header file of a class, I had
int SetI2cSlaveAddress( UCHAR addr, bool force );
  • In the source file of that class, I had
int CI2cHal::SetI2cSlaveAddress( UCHAR addr, bool force = false )
{
   ...
}

As one can see, I had put the default value of the parameter "force" in the class source file, not in the class header file.

Then I used that function in a derived class as follows (derived class inherited the base class in a public way):

SetI2cSlaveAddress( addr );

assuming it would take the "force" parameter as "false" 'for granted'.

However, the compiler (put in c++11 mode) complained and gave me the following compiler error:

/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp: In member function 'void CMax6956Io::Init(unsigned char, unsigned char, unsigned int)':
/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp:26:30: error: no matching function for call to 'CMax6956Io::SetI2cSlaveAddress(unsigned char&)'
/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp:26:30: note: candidate is:
In file included from /home/geertvc/mystuff/domoproject/lib/i2cdevs/../../include/i2cdevs/max6956io.h:35:0,
                 from /home/geertvc/mystuff/domoproject/lib/i2cdevs/max6956io.cpp:1:
/home/.../mystuff/domoproject/lib/i2cdevs/../../include/i2chal/i2chal.h:65:9: note: int CI2cHal::SetI2cSlaveAddress(unsigned char, bool)
/home/.../mystuff/domoproject/lib/i2cdevs/../../include/i2chal/i2chal.h:65:9: note:   candidate expects 2 arguments, 1 provided
make[2]: *** [lib/i2cdevs/CMakeFiles/i2cdevs.dir/max6956io.cpp.o] Error 1
make[1]: *** [lib/i2cdevs/CMakeFiles/i2cdevs.dir/all] Error 2
make: *** [all] Error 2

But when I added the default parameter in the header file of the base class:

int SetI2cSlaveAddress( UCHAR addr, bool force = false );

and removed it from the source file of the base class:

int CI2cHal::SetI2cSlaveAddress( UCHAR addr, bool force )

then the compiler was happy and all code worked as expected (I could give one or two parameters to the function SetI2cSlaveAddress())!

So, not only for the user of a class it's important to put the default value of a parameter in the header file, also compiling and functional wise it apparently seems to be a must!

Zip lists in Python

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: "pip install ipython"

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

How can I test an AngularJS service from the console?

First of all, a modified version of your service.

a )

var app = angular.module('app',[]);

app.factory('ExampleService',function(){
    return {
        f1 : function(world){
            return 'Hello' + world;
        }
    };
});

This returns an object, nothing to new here.

Now the way to get this from the console is

b )

var $inj = angular.injector(['app']);
var serv = $inj.get('ExampleService');
serv.f1("World");

c )

One of the things you were doing there earlier was to assume that the app.factory returns you the function itself or a new'ed version of it. Which is not the case. In order to get a constructor you would either have to do

app.factory('ExampleService',function(){
        return function(){
            this.f1 = function(world){
                return 'Hello' + world;
            }
        };
    });

This returns an ExampleService constructor which you will next have to do a 'new' on.

Or alternatively,

app.service('ExampleService',function(){
            this.f1 = function(world){
                return 'Hello' + world;
            };
    });

This returns new ExampleService() on injection.

How to trim leading and trailing white spaces of a string?

For trimming your string, Go's "strings" package have TrimSpace(), Trim() function that trims leading and trailing spaces.

Check the documentation for more information.

Detecting negative numbers

Don't get me wrong, but you can do this way ;)

function nagitive_check($value){
if (isset($value)){
    if (substr(strval($value), 0, 1) == "-"){
    return 'It is negative<br>';
} else {
    return 'It is not negative!<br>';
}
    }
}

Output:

echo nagitive_check(-100);  // It is negative
echo nagitive_check(200);  // It is not negative!
echo nagitive_check(200-300);  // It is negative
echo nagitive_check(200-300+1000);  // It is not negative!

Defining and using a variable in batch file

input location.bat

@echo off
cls

set /p "location"="bob"
echo We're working with %location%
pause

output

We're working with bob

(mistakes u done : space and " ")

Invalid default value for 'create_date' timestamp field

Default values should start from the year 1000.

For example,

ALTER TABLE mytable last_active DATETIME DEFAULT '1000-01-01 00:00:00'

Hope this helps someone.

Form inline inside a form horizontal in twitter bootstrap?

For bootstrap 3 example above works but is overcomplicated, rather than using form-group use form-inline for the fields you want inline.

Eg:

<div class="form-group">
     <label>CVV</label>
     <input type="text" size="4" class="form-control" />
</div>

<div class="form-inline">
      <label>Expiration (MM/YYYY)</label><br>
      <input type="text" size="2" class="form-control" /> / <input type="text" size="4" class="form-control" />
</div>

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

If Andy Copley's answer worked for you but simply rebuilding the solution doesn't work, then go to Project | Project Dependencies and make sure that the project that has your Global.asax.cs file in it is dependent on all the other non-test projects in the solution.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

You can get table/view details through below query.

For table :sp_help table_name For View :sp_help view_name

How many values can be represented with n bits?

Okay, since it already "leaked": You're missing zero, so the correct answer is 512 (511 is the greatest one, but it's 0 to 511, not 1 to 511).

By the way, an good followup exercise would be to generalize this:

How many different values can be represented in n binary digits (bits)?

laravel collection to array

You can use toArray() of eloquent as below.

The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays

$comments_collection = $post->comments()->get()->toArray()

From Laravel Docs:

toArray also converts all of the collection's nested objects that are an instance of Arrayable to an array. If you want to get the raw underlying array, use the all method instead.

How to change the size of the font of a JLabel to take the maximum size

Not the most pretty code, but the following will pick an appropriate font size for a JLabel called label such that the text inside will fit the interior as much as possible without overflowing the label:

Font labelFont = label.getFont();
String labelText = label.getText();

int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();

// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;

int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();

// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);

// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

Basically, the code looks at how much space the text in the JLabel takes up by using the FontMetrics object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel.

The above code can be inserted into perhaps the paint method of the JFrame which holds the JLabel, or some method which will be invoked when the font size needs to be changed.

The following is an screenshot of the above code in action:

alt text
(source: coobird.net)

Validating with an XML schema in Python

You can easily validate an XML file or tree against an XML Schema (XSD) with the xmlschema Python package. It's pure Python, available on PyPi and doesn't have many dependencies.

Example - validate a file:

import xmlschema
xmlschema.validate('doc.xml', 'some.xsd')

The method raises an exception if the file doesn't validate against the XSD. That exception then contains some violation details.

If you want to validate many files you only have to load the XSD once:

xsd = xmlschema.XMLSchema('some.xsd')
for filename in filenames:
    xsd.validate(filename)

If you don't need the exception you can validate like this:

if xsd.is_valid('doc.xml'):
    print('do something useful')

Alternatively, xmlschema directly works on file objects and in memory XML trees (either created with xml.etree.ElementTree or lxml). Example:

import xml.etree.ElementTree as ET
t = ET.parse('doc.xml')
result = xsd.is_valid(t)
print('Document is valid? {}'.format(result))

jQuery - how can I find the element with a certain id?

If you're trying to find an element by id, you don't need to search the table only - it should be unique on the page, and so you should be able to use:

var verificaHorario = $('#' + horaInicial);

If you need to search only in the table for whatever reason, you can use:

var verificaHorario = $("#tbIntervalos").find("td#" + horaInicial)

Can I multiply strings in Java to repeat sequences?

No, you can't. However you can use this function to repeat a character.

public String repeat(char c, int times){
    StringBuffer b = new StringBuffer();

    for(int i=0;i &lt; times;i++){
        b.append(c);
    }

    return b.toString();
}

Disclaimer: I typed it here. Might have mistakes.

Pandas: convert dtype 'object' to int

Follow these steps:

1.clean your file -> open your datafile in csv format and see that there is "?" in place of empty places and delete all of them.

2.drop the rows containing missing values e.g.:

df.dropna(subset=["normalized-losses"], axis = 0 , inplace= True)

3.use astype now for conversion

df["normalized-losses"]=df["normalized-losses"].astype(int)

Note: If still finding erros in your program then again inspect your csv file, open it in excel to find whether is there an "?" in your required column, then delete it and save file and go back and run your program.

comment success! if it works. :)

Convert a string into an int

See the NSString Class Reference.

NSString *string = @"5";
int value = [string intValue];

How to change text color and console color in code::blocks?

This is a function online, I created a header file with it, and I use Setcolor(); instead, I hope this helped! You can change the color by choosing any color in the range of 0-256. :) Sadly, I believe CodeBlocks has a later build of the window.h library...

#include <windows.h>            //This is the header file for windows.
#include <stdio.h>              //C standard library header file

void SetColor(int ForgC);

int main()
{
    printf("Test color");       //Here the text color is white
    SetColor(30);               //Function call to change the text color
    printf("Test color");       //Now the text color is green
    return 0;
}

void SetColor(int ForgC)
{
     WORD wColor;
     //This handle is needed to get the current background attribute

     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     //csbi is used for wAttributes word

     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
          //To mask out all but the background attribute, and to add the color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
}

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

jQuery: Setting select list 'selected' based on text, failing strangely

I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.

$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());

another way of writing it in a more readable fasion:

var valofText = $("#my-Select" + " option").filter(function() {
    return this.text == myText
}).val();
$(ElementID).val(valofText);

Pseudocode:

$("#my-Select").val( getValOfText( myText ) );

Create instance of generic type whose constructor requires a parameter?

Recently I came across a very similar problem. Just wanted to share our solution with you all. I wanted to I created an instance of a Car<CarA> from a json object using which had an enum:

Dictionary<MyEnum, Type> mapper = new Dictionary<MyEnum, Type>();

mapper.Add(1, typeof(CarA));
mapper.Add(2, typeof(BarB)); 

public class Car<T> where T : class
{       
    public T Detail { get; set; }
    public Car(T data)
    {
       Detail = data;
    }
}
public class CarA
{  
    public int PropA { get; set; }
    public CarA(){}
}
public class CarB
{
    public int PropB { get; set; }
    public CarB(){}
}

var jsonObj = {"Type":"1","PropA":"10"}
MyEnum t = GetTypeOfCar(jsonObj);
Type objectT = mapper[t]
Type genericType = typeof(Car<>);
Type carTypeWithGenerics = genericType.MakeGenericType(objectT);
Activator.CreateInstance(carTypeWithGenerics , new Object[] { JsonConvert.DeserializeObject(jsonObj, objectT) });

Why should text files end with a newline?

Presumably simply that some parsing code expected it to be there.

I'm not sure I would consider it a "rule", and it certainly isn't something I adhere to religiously. Most sensible code will know how to parse text (including encodings) line-by-line (any choice of line endings), with-or-without a newline on the last line.

Indeed - if you end with a new line: is there (in theory) an empty final line between the EOL and the EOF? One to ponder...

Limit the output of the TOP command to a specific process name

Use the watch command

watch -d 'top -n1 | grep mysql'

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Close/kill the session when the browser or tab is closed

Not perfect but best solution for now :

var spcKey = false;
var hover = true;
var contextMenu = false;

function spc(e) {
    return ((e.altKey || e.ctrlKey || e.keyCode == 91 || e.keyCode==87) && e.keyCode!=82 && e.keyCode!=116);
}

$(document).hover(function () {
    hover = true;
    contextMenu = false;
    spcKey = false;
}, function () {
    hover = false;
}).keydown(function (e) {
    if (spc(e) == false) {
        hover = true;
        spcKey = false;
    }
    else {
        spcKey = true;
    }
}).keyup(function (e) {
    if (spc(e)) {
        spcKey = false;
    }
}).contextmenu(function (e) {
    contextMenu = true;
}).click(function () {
    hover = true;
    contextMenu = false;
});

window.addEventListener('focus', function () {
    spcKey = false;
});
window.addEventListener('blur', function () {
    hover = false;
});

window.onbeforeunload = function (e) {
    if ((hover == false || spcKey == true) && contextMenu==false) {
        window.setTimeout(goToLoginPage, 100);
        $.ajax({
            url: "/Account/Logoff",
            type: 'post',
            data: $("#logoutForm").serialize(),
        });
        return "Oturumunuz kapatildi.";
    }
    return;
};

function goToLoginPage() {
    hover = true;
    spcKey = false;
    contextMenu = false;
    location.href = "/Account/Login";
}

Overriding interface property type defined in Typescript d.ts file

It's funny I spend the day investigating possibility to solve the same case. I found that it not possible doing this way:

// a.ts - module
export interface A {
    x: string | any;
}

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

interface B extends A {
    x: SomeOtherType;
}

Cause A module may not know about all available types in your application. And it's quite boring port everything from everywhere and doing code like this.

export interface A {
    x: A | B | C | D ... Million Types Later
}

You have to define type later to have autocomplete works well.


So you can cheat a bit:

// a.ts - module
export interface A {
    x: string;
}

Left the some type by default, that allow autocomplete works, when overrides not required.

Then

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

// @ts-ignore
interface B extends A {
    x: SomeOtherType;
}

Disable stupid exception here using @ts-ignore flag, saying us the we doing something wrong. And funny thing everything works as expected.

In my case I'm reducing the scope vision of type x, its allow me doing code more stricted. For example you have list of 100 properties, and you reduce it to 10, to avoid stupid situations

How to allow only a number (digits and decimal point) to be typed in an input?

Here is a derivative that will also block the decimal point to be entered twice

HTML

    <input tabindex="1" type="text" placeholder="" name="salary" id="salary" data-ng-model="salary" numbers-only="numbers-only" required="required">

Angular

    var app = angular.module("myApp", []);

    app.directive('numbersOnly', function() {
    return {
            require : 'ngModel', link : function(scope, element, attrs,  modelCtrl) {
        modelCtrl.$parsers.push(function(inputValue) {

            if (inputValue == undefined) {
                return ''; //If value is required
            }

            // Regular expression for everything but [.] and [1 - 10] (Replace all)
            var transformedInput = inputValue.replace(/[a-z!@#$%^&*()_+\-=\[\]{};':"\\|,<>\/?]/g, '');

            // Now to prevent duplicates of decimal point
            var arr = transformedInput.split('');

            count = 0; //decimal counter
            for ( var i = 0; i < arr.length; i++) {
                if (arr[i] == '.') {
                    count++; //  how many do we have? increment
                }
            }

            // if we have more than 1 decimal point, delete and leave only one at the end
            while (count > 1) {
                for ( var i = 0; i < arr.length; i++) {
                    if (arr[i] == '.') {
                        arr[i] = '';
                        count = 0;
                        break;
                    }
                }
            }

            // convert the array back to string by relacing the commas
            transformedInput = arr.toString().replace(/,/g, '');

            if (transformedInput != inputValue) {
                modelCtrl.$setViewValue(transformedInput);
                modelCtrl.$render();
            }

            return transformedInput;
        });
    }
};
});

What is the difference between a generative and a discriminative algorithm?

An addition informative point that goes well with the answer by StompChicken above.

The fundamental difference between discriminative models and generative models is:

Discriminative models learn the (hard or soft) boundary between classes

Generative models model the distribution of individual classes

Edit:

A Generative model is the one that can generate data. It models both the features and the class (i.e. the complete data).

If we model P(x,y): I can use this probability distribution to generate data points - and hence all algorithms modeling P(x,y) are generative.

Eg. of generative models

  • Naive Bayes models P(c) and P(d|c) - where c is the class and d is the feature vector.

    Also, P(c,d) = P(c) * P(d|c)

    Hence, Naive Bayes in some form models, P(c,d)

  • Bayes Net

  • Markov Nets

A discriminative model is the one that can only be used to discriminate/classify the data points. You only require to model P(y|x) in such cases, (i.e. probability of class given the feature vector).

Eg. of discriminative models:

  • logistic regression

  • Neural Networks

  • Conditional random fields

In general, generative models need to model much more than the discriminative models and hence are sometimes not as effective. As a matter of fact, most (not sure if all) unsupervised learning algorithms like clustering etc can be called generative, since they model P(d) (and there are no classes:P)

PS: Part of the answer is taken from source

how to do "press enter to exit" in batch

Oops... Misunderstood the question...

Pause is the way to go

Old answer:

you can pipe commands into your patch file...

try

build.bat < responsefile.txt

How to create a zip archive of a directory in Python?

This function will recursively zip up a directory tree, compressing the files, and recording the correct relative filenames in the archive. The archive entries are the same as those generated by zip -r output.zip source_dir.

import os
import zipfile
def make_zipfile(output_filename, source_dir):
    relroot = os.path.abspath(os.path.join(source_dir, os.pardir))
    with zipfile.ZipFile(output_filename, "w", zipfile.ZIP_DEFLATED) as zip:
        for root, dirs, files in os.walk(source_dir):
            # add directory (needed for empty dirs)
            zip.write(root, os.path.relpath(root, relroot))
            for file in files:
                filename = os.path.join(root, file)
                if os.path.isfile(filename): # regular files only
                    arcname = os.path.join(os.path.relpath(root, relroot), file)
                    zip.write(filename, arcname)

how to have two headings on the same line in html

The Css vertical-align property should help you out here:

vertical-align: bottom;

is what you need for your smaller header :)

Vertical-Align

.ps1 cannot be loaded because the execution of scripts is disabled on this system

You need to run Set-ExecutionPolicy:

Set-ExecutionPolicy Unrestricted <-- Will allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy Restricted <-- Will not allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed PowerShell scripts to run.

Ruby String to Date Conversion

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

Where are static methods and static variables stored in Java?

In real world or project we have requirement in advance and needs to create variable and methods inside the class , On the basis of requirement we needs to decide whether we needs to create

  1. Local ( create n access within block or method constructor)
  2. Static,
  3. Instance Variable( every object has its own copy of it),

=>2. Static Keyword we will used with variable which going to same for particular class throughout for all objects, e.g in selenium : we decalre webDriver as static=> so we do not need to create webdriver again and again for every test case= Static Webdriver driver(but parallel execution it will cause problem but thats another case); then, Real world scenario=>If India is class then, flag, money would be same every indian so we might take as static. Anatoher example: utility method we always declare as static b'cos it will be used in different test cases. Static stored in CMA( PreGen space)=PreGen (Fixed memory)changed to Metaspace after Java8 as now its growing dynamically

Python/Json:Expecting property name enclosed in double quotes

Use the eval function.

It takes care of the discrepancy between single and double quotes.

How to remove "href" with Jquery?

If you remove the href attribute the anchor will be not focusable and it will look like simple text, but it will still be clickable.