Programs & Examples On #Fusioncharts

FusionCharts Suite XT is a JavaScript (HTML5) Charting library for web and mobile applications. It works on a majority of devices including PCs, Macs, iPads, iPhones and Android devices, and on all browsers including IE6. It offers 90+ chart types including Column, Bar, Line and Pie charts to the more advanced chart types like Funnel, Combination, Bubble and Zoom Line Charts.

How does "cat << EOF" work in bash?

This is called heredoc format to provide a string into stdin. See https://en.wikipedia.org/wiki/Here_document#Unix_shells for more details.


From man bash:

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen.

All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.

If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

How to delete SQLite database from Android programmatically

I used Android database delete method and database removed successfully

public bool DeleteDatabase()
        {
            var dbName = "TenderDb.db";
            var documentDirectoryPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(documentDirectoryPath, dbName);
            return Android.Database.Sqlite.SQLiteDatabase.DeleteDatabase(new Java.IO.File(path));
        }

TextView Marquee not working

To have your own scroll speed and flexibility to customize marquee properties, use the following:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:fadingEdge="horizontal"
    android:lines="1"
    android:id="@+id/myTextView"
    android:padding="4dp"
    android:scrollHorizontally="true"
    android:singleLine="true"
    android:text="Simple application that shows how to use marquee, with a long text" />

Within your activity:

private void setTranslation() {
        TranslateAnimation tanim = new TranslateAnimation(
                TranslateAnimation.ABSOLUTE, 1.0f * screenWidth,
                TranslateAnimation.ABSOLUTE, -1.0f * screenWidth,
                TranslateAnimation.ABSOLUTE, 0.0f,
                TranslateAnimation.ABSOLUTE, 0.0f);
        tanim.setDuration(1000);
        tanim.setInterpolator(new LinearInterpolator());
        tanim.setRepeatCount(Animation.INFINITE);
        tanim.setRepeatMode(Animation.ABSOLUTE);

        textView.startAnimation(tanim);
    } 

How can I escape white space in a bash loop list?

To add to what Jonathan said: use the -print0 option for find in conjunction with xargs as follows:

find test/* -type d -print0 | xargs -0 command

That will execute the command command with the proper arguments; directories with spaces in them will be properly quoted (i.e. they'll be passed in as one argument).

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

public class MainActivity extends Activity
        implements View.OnClickListener {
    private Button btnForward, btnBackword, btnPause, btnPlay;

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

    private void initControl() {
        btnForward = (Button) findViewById(R.id.btnForward);
        btnBackword = (Button) findViewById(R.id.btnBackword);
        btnPause = (Button) findViewById(R.id.btnPause);
        btnPlay = (Button) findViewById(R.id.btnPlay);
        btnForward.setOnClickListener(this);
        btnBackword.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnForward:
                break;
            case R.id.btnBackword:
                break;
            case R.id.btnPause:
                break;
            case R.id.btnPlay:
                break;
        }
    }
}

Search text in stored procedure in SQL Server

Escape the square brackets:

...
WHERE m.definition Like '%\[ABD\]%' ESCAPE '\'

Then the square brackets will be treated as a string literals not as wild cards.

Changing position of the Dialog on screen android

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

Dialog dlg = <code to create custom dialog>;

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

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

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


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

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

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

    dialog.show();
}

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

How to get StackPanel's children to fill maximum space downward?

It sounds like you want a StackPanel where the final element uses up all the remaining space. But why not use a DockPanel? Decorate the other elements in the DockPanel with DockPanel.Dock="Top", and then your help control can fill the remaining space.

XAML:

<DockPanel Width="200" Height="200" Background="PowderBlue">
    <TextBlock DockPanel.Dock="Top">Something</TextBlock>
    <TextBlock DockPanel.Dock="Top">Something else</TextBlock>
    <DockPanel
        HorizontalAlignment="Stretch" 
        VerticalAlignment="Stretch" 
        Height="Auto" 
        Margin="10">

      <GroupBox 
        DockPanel.Dock="Right" 
        Header="Help" 
        Width="100" 
        Background="Beige" 
        VerticalAlignment="Stretch" 
        VerticalContentAlignment="Stretch" 
        Height="Auto">
        <TextBlock Text="This is the help that is available on the news screen." 
                   TextWrapping="Wrap" />
     </GroupBox>

      <StackPanel DockPanel.Dock="Left" Margin="10" 
           Width="Auto" HorizontalAlignment="Stretch">
          <TextBlock Text="Here is the news that should wrap around." 
                     TextWrapping="Wrap"/>
      </StackPanel>
    </DockPanel>
</DockPanel>

If you are on a platform without DockPanel available (e.g. WindowsStore), you can create the same effect with a grid. Here's the above example accomplished using grids instead:

<Grid Width="200" Height="200" Background="PowderBlue">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0">
        <TextBlock>Something</TextBlock>
        <TextBlock>Something else</TextBlock>
    </StackPanel>
    <Grid Height="Auto" Grid.Row="1" Margin="10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        <GroupBox
            Width="100"
            Height="Auto"
            Grid.Column="1"
            Background="Beige"
            Header="Help">
            <TextBlock Text="This is the help that is available on the news screen." 
              TextWrapping="Wrap"/>
        </GroupBox>
        <StackPanel Width="Auto" Margin="10" DockPanel.Dock="Left">
            <TextBlock Text="Here is the news that should wrap around." 
              TextWrapping="Wrap"/>
        </StackPanel>
    </Grid>
</Grid>

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

$_POST Array from html form

You should get the array like in $_POST['id']. So you should be able to do this:

foreach ($_POST['id'] as $key => $value) {
    echo $value . "<br />";
}

Input names should be same:

<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...

Getting Spring Application Context

SpringApplicationContext.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Wrapper to always return a reference to the Spring Application 
Context from
 * within non-Spring enabled beans. Unlike Spring MVC's 
WebApplicationContextUtils
 * we do not need a reference to the Servlet context for this. All we need is
 * for this bean to be initialized during application startup.
 */
public class SpringApplicationContext implements 
ApplicationContextAware {

  private static ApplicationContext CONTEXT;

  /**
   * This method is called from within the ApplicationContext once it is 
   * done starting up, it will stick a reference to itself into this bean.
  * @param context a reference to the ApplicationContext.
  */
  public void setApplicationContext(ApplicationContext context) throws BeansException {
    CONTEXT = context;
  }

  /**
   * This is about the same as context.getBean("beanName"), except it has its
   * own static handle to the Spring context, so calling this method statically
   * will give access to the beans by name in the Spring application context.
   * As in the context.getBean("beanName") call, the caller must cast to the
   * appropriate target class. If the bean does not exist, then a Runtime error
   * will be thrown.
   * @param beanName the name of the bean to get.
   * @return an Object reference to the named bean.
   */
  public static Object getBean(String beanName) {
    return CONTEXT.getBean(beanName);
  }
}

Source: http://sujitpal.blogspot.de/2007/03/accessing-spring-beans-from-legacy-code.html

Unable to resolve host "<insert URL here>" No address associated with hostname

My bet is that you forgot to give your app the permission to use the internet. Try adding this to your android manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

get the titles of all open windows

http://pinvoke.net/default.aspx/user32.EnumDesktopWindows

There is an example of using user.dll's EnumWindow in C# to list all open windows.

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

Change class on mouseover in directive

I think it would be much easier to put an anchor tag around i. You can just use the css :hover selector. Less moving parts makes maintenance easier, and less javascript to load makes the page quicker.

This will do the trick:

<style>
 a.icon-link:hover {
   background-color: pink;
 }
</style>

<a href="#" class="icon-link" id="course-0"><i class="icon-thumbsup"></id></a>

jsfiddle example

Left join only selected columns in R with the merge() function

I think it's a little simpler to use the dplyr functions select and left_join ; at least it's easier for me to understand. The join function from dplyr are made to mimic sql arguments.

 library(tidyverse)

 DF2 <- DF2 %>%
   select(client, LO)

 joined_data <- left_join(DF1, DF2, by = "Client")

You don't actually need to use the "by" argument in this case because the columns have the same name.

Validate phone number using javascript

You can use this jquery plugin:

http://digitalbush.com/projects/masked-input-plugin/

Refer to demo tab, phone option.

Convert A String (like testing123) To Binary In Java

A shorter example

private static final Charset UTF_8 = Charset.forName("UTF-8");

String text = "Hello World!";
byte[] bytes = text.getBytes(UTF_8);
System.out.println("bytes= "+Arrays.toString(bytes));
System.out.println("text again= "+new String(bytes, UTF_8));

prints

bytes= [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
text again= Hello World!

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

How to have image and text side by side

You're already doing it correctly, it just that the <h4>Facebook</h4> tag is taking too much vertical margin. You can remove it by using the style margin:0px on the <h4> tag.

For your future convenience, you can put border (border:1px solid black) on your elements to see which part you actually get it wrong.

What does elementFormDefault do in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).

By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.

It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.

How to get tf.exe (TFS command line client)?

I'm in a virtual machine, and am trying to keep my VHD as small as possible, so I find Team Explorer is a really heavyweight solution (300+ MB install). As an alternative, I've had some luck copying a minimal set of EXEs/DLLs from a Team Explorer installation to a clean machine (.NET 4.0 is still required, of course).

I've only tried a handful of operations so far, but this set of files (about 8.5 MB) has been enough to get basic source-control functionality via tf.exe:

  • TF.exe
  • TF.exe.config
  • Microsoft.TeamFoundation.dll
  • Microsoft.TeamFoundation.Client.dll
  • Microsoft.TeamFoundation.Common.dll
  • Microsoft.TeamFoundation.Common.Library.dll
  • Microsoft.TeamFoundation.VersionControl.Client.dll
  • Microsoft.TeamFoundation.VersionControl.Common.dll
  • Microsoft.TeamFoundation.VersionControl.Controls.dll

(It should go without saying that this is a completely unsupported solution, and it doesn't free you from the normal TFS licensing requirements.)

Depending on the operations you perform, you may find that additional DLLs are required. Fortunately, tf.exe will produce a nice error message telling you exactly which ones are missing.

WPF MVVM: How to close a window

In your current window xaml.cs file, call the below code:

var curWnd = Window.GetWindow(this); // passing current window context
curWnd?.Close();

This should do the thing.
It worked for me, hope will do the same for you )

Trigger back-button functionality on button click in Android

You should use finish() when the user clicks on the button in order to go to the previous activity.

Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    finish();
  }
});

Alternatively, if you really need to, you can try to trigger your own back key press:

this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));

Execute both of these.

Convert file path to a file URI?

The System.Uri constructor has the ability to parse full file paths and turn them into URI style paths. So you can just do the following:

var uri = new System.Uri("c:\\foo");
var converted = uri.AbsoluteUri;

mysqli or PDO - what are the pros and cons?

PDO will make it a lot easier to scale if your site/web app gets really being as you can daily set up Master and slave connections to distribute the load across the database, plus PHP is heading towards moving to PDO as a standard.

PDO Info

Scaling a Web Application

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

If you just want to suppress warnings from a function, you can add an @ sign in front:

<?php @function_that_i_dont_want_to_see_errors_from(parameters); ?>

Update date + one year in mysql

This post helped me today, but I had to experiment to do what I needed. Here is what I found.

Should you want to add more complex time periods, for example 1 year and 15 days, you can use

UPDATE tablename SET datefieldname = curdate() + INTERVAL 15 DAY + INTERVAL 1 YEAR;

I found that using DATE_ADD doesn't allow for adding more than one interval. And there is no YEAR_DAYS interval keyword, though there are others that combine time periods. If you are adding times, use now() rather than curdate().

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

Handling click events on a drawable within an EditText

I've taked the solution of @AZ_ and converted it in a kotlin extension function:

So copy this in your code:

@SuppressLint("ClickableViewAccessibility")
fun EditText.setDrawableRightTouch(setClickListener: () -> Unit) {
    this.setOnTouchListener(View.OnTouchListener { _, event ->
        val DRAWABLE_LEFT = 0
        val DRAWABLE_TOP = 1
        val DRAWABLE_RIGHT = 2
        val DRAWABLE_BOTTOM = 3
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= this.right - this.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
            ) {
                setClickListener()
                return@OnTouchListener true
            }
        }
        false
    })
}

You can use it just calling the setDrawableRightTouch function on your EditText:

yourEditText.setDrawableRightTouch {
    //your code
}

How to add CORS request in header in Angular 5

You can also try the fetch function and the no-cors mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.

import { from } from 'rxjs';

// ...

result = from( // wrap the fetch in a from if you need an rxjs Observable
  fetch(
    this.baseurl,
    {
      body: JSON.stringify(data)
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      mode: 'no-cors'
    }
  )
);

CSS grid wrapping

You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Enter image description here

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Enter image description here

Remove multiple objects with rm()

Or using regular expressions

"rmlike" <- function(...) {
  names <- sapply(
    match.call(expand.dots = FALSE)$..., as.character)
  names = paste(names,collapse="|")
  Vars <- ls(1)
  r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
  rm(list=r,pos=1)
}

rmlike(temp)

Go to "next" iteration in JavaScript forEach loop

just return true inside your if statement

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {

      return true;

    // Go to "next" iteration. Or "continue" to next iteration...
  }

  console.log(elem);
});

Fixing the order of facets in ggplot

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

Then change the facet_grid(.~size) to facet_grid(.~size_f)

Then plot: enter image description here

The graphs are now in the correct order.

TypeError: Cannot read property "0" from undefined

Under normal circumstances,out of bound of array when you encounter the error. So,check uo your array subscript.

alert a variable value

show alert box with use variable with message

<script>
$(document).ready(function() {
var total = 30 ;
alert("your total is :"+ total +"rs");
});
</script>

How to go back to previous page if back button is pressed in WebView?

Official Kotlin Way:

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    // Check if the key event was the Back button and if there's history
    if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
        myWebView.goBack()
        return true
    }
    // If it wasn't the Back key or there's no web page history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event)
}

https://developer.android.com/guide/webapps/webview.html#NavigatingHistory

How to differ sessions in browser-tabs?

I think what you probably want is to maintain navigation state across tabs and not specifically creating a single session per tab. This is exactly what the Seam framework achieves with their Conversation scope/context. Their implementation relies on the fact that a conversation id is propagated with each request and creates the notion of a conversation on the server side, which is something that lies between a session and a request. It allows for navigation flow control and state management.

Although that's mainly aimed at JSF, have a look and check if that's something where you can take some ideas from: http://docs.jboss.org/seam/latest/reference/en-US/html_single/#d0e3620

Setting selected values for ng-options bound select elements

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.

<select 
    ng-model="Choice.SelectedOption"                 
    ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>

Updated fiddle http://jsfiddle.net/gFCzV/34/

How to start and stop/pause setInterval?

You can't stop a timer function mid-execution. You can only catch it after it completes and prevent it from triggering again.

Maven project.build.directory

It points to your top level output directory (which by default is target):

https://web.archive.org/web/20150527103929/http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:

http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html#resource-filtering-sect-project-properties

If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.

    project.build.sourceDirectory
    project.build.scriptSourceDirectory
    project.build.testSourceDirectory
    project.build.outputDirectory
    project.build.testOutputDirectory
    project.build.directory

sourceDirectory, scriptSourceDirectory, and testSourceDirectory provide access to the source directories for the project. outputDirectory and testOutputDirectory provide access to the directories where Maven is going to put bytecode or other build output. directory refers to the directory which contains all of these output directories.

How to add 10 minutes to my (String) time?

You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.

String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());

Output :

14:10
14:20

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

It can do so if you have implicitly or explicitly set the alignment of the struct. A struct that is aligned 4 will always be a multiple of 4 bytes even if the size of its members would be something that's not a multiple of 4 bytes.

Also a library may be compiled under x86 with 32-bit ints and you may be comparing its components on a 64-bit process would would give you a different result if you were doing this by hand.

window.open target _self v window.location.href?

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

Changing background color of text box input not working when empty

Don't add styles to value of input so use like

function checkFilled() {
    var inputElem = document.getElementById("subEmail");
    if (inputElem.value == "") {
        inputElem.style.backgroundColor = "yellow";
                }
        }

Is it better to use path() or url() in urls.py for django 2.0?

path is simply new in Django 2.0, which was only released a couple of weeks ago. Most tutorials won't have been updated for the new syntax.

It was certainly supposed to be a simpler way of doing things; I wouldn't say that URL is more powerful though, you should be able to express patterns in either format.

Open file dialog box in JavaScript

Here is a nice one

Fine Uploader demo

It is an <input type='file' /> control itself. But a div is placed over that and css styles are applied to get that feel. Opacity of the file control is set to 0 so that it appears that the dialog window is opened when clicking on the div.

How do you add an action to a button programmatically in xcode

IOS 14 SDK: you can add action with closure callback:

let button = UIButton(type: .system, primaryAction: UIAction(title: "Button Title", handler: { _ in
            print("Button tapped!")
        }))

Getting a reference to the control sender

let textField = UITextField()
textField.addAction(UIAction(title: "", handler: { action in
    let textField = action.sender as! UITextField
    print("Text is \(textField.text)")
}), for: .editingChanged)

source

How do I consume the JSON POST data in an Express application

@Daniel Thompson mentions that he had forgotten to add {"Content-Type": "application/json"} in the request. He was able to change the request, however, changing requests is not always possible (we are working on the server here).

In my case I needed to force content-type: text/plain to be parsed as json.

If you cannot change the content-type of the request, try using the following code:

app.use(express.json({type: '*/*'}));

Instead of using express.json() globally, I prefer to apply it only where needed, for instance in a POST request:

app.post('/mypost', express.json({type: '*/*'}), (req, res) => {
  // echo json
  res.json(req.body);
});

How do I properly clean up Excel interop objects?

I followed this exactly... But I still ran into issues 1 out of 1000 times. Who knows why. Time to bring out the hammer...

Right after the Excel Application class is instantiated I get a hold of the Excel process that was just created.

excel = new Microsoft.Office.Interop.Excel.Application();
var process = Process.GetProcessesByName("EXCEL").OrderByDescending(p => p.StartTime).First();

Then once I've done all the above COM clean-up, I make sure that process isn't running. If it is still running, kill it!

if (!process.HasExited)
   process.Kill();

jQuery check if it is clicked or not

<script>
    var listh = document.getElementById( 'list-home-list' );
    var hb = document.getElementsByTagName('hb');
    $("#list-home-list").click(function(){
    $(this).style.color = '#2C2E33';
    hb.style.color = 'white';
    });
</script>

ReferenceError: document is not defined (in plain JavaScript)

It depends on when the self executing anonymous function is running. It is possible that it is running before window.document is defined.

In that case, try adding a listener

window.addEventListener('load', yourFunction, false);
// ..... or 
window.addEventListener('DOMContentLoaded', yourFunction, false);

yourFunction () {
  // some ocde

}

Update: (after the update of the question and inclusion of the code)

Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head element:
- “getElementsByTagName(…)[0]” is undefined?
- Traversing the DOM

How to deploy correctly when using Composer's develop / production switch?

Why

There is IMHO a good reason why Composer will use the --dev flag by default (on install and update) nowadays. Composer is mostly run in scenario's where this is desired behavior:

The basic Composer workflow is as follows:

  • A new project is started: composer.phar install --dev, json and lock files are commited to VCS.
  • Other developers start working on the project: checkout of VCS and composer.phar install --dev.
  • A developer adds dependancies: composer.phar require <package>, add --dev if you want the package in the require-dev section (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • A developer wants newer versions of dependencies: composer.phar update --dev <package> (and commit).
  • Others go along: (checkout and) composer.phar install --dev.
  • Project is deployed: composer.phar install --no-dev

As you can see the --dev flag is used (far) more than the --no-dev flag, especially when the number of developers working on the project grows.

Production deploy

What's the correct way to deploy this without installing the "dev" dependencies?

Well, the composer.json and composer.lock file should be committed to VCS. Don't omit composer.lock because it contains important information on package-versions that should be used.

When performing a production deploy, you can pass the --no-dev flag to Composer:

composer.phar install --no-dev

The composer.lock file might contain information about dev-packages. This doesn't matter. The --no-dev flag will make sure those dev-packages are not installed.

When I say "production deploy", I mean a deploy that's aimed at being used in production. I'm not arguing whether a composer.phar install should be done on a production server, or on a staging server where things can be reviewed. That is not the scope of this answer. I'm merely pointing out how to composer.phar install without installing "dev" dependencies.

Offtopic

The --optimize-autoloader flag might also be desirable on production (it generates a class-map which will speed up autoloading in your application):

composer.phar install --no-dev --optimize-autoloader

Or when automated deployment is done:

composer.phar install --no-ansi --no-dev --no-interaction --no-plugins --no-progress --no-scripts --optimize-autoloader

If your codebase supports it, you could swap out --optimize-autoloader for --classmap-authoritative. More info here

space between divs - display table-cell

Well, the above does work, here is my solution that requires a little less markup and is more flexible.

_x000D_
_x000D_
.cells {_x000D_
  display: inline-block;_x000D_
  float: left;_x000D_
  padding: 1px;_x000D_
}_x000D_
.cells>.content {_x000D_
  background: #EEE;_x000D_
  display: table-cell;_x000D_
  float: left;_x000D_
  padding: 3px;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div id="div1" class="cells"><div class="content">My Cell 1</div></div>_x000D_
<div id="div2" class="cells"><div class="content">My Cell 2</div></div>
_x000D_
_x000D_
_x000D_

Angularjs loading screen on ajax request

Here's an example. It uses the simple ng-show method with a bool.

HTML

<div ng-show="loading" class="loading"><img src="...">LOADING...</div>
<div ng-repeat="car in cars">
  <li>{{car.name}}</li>
</div>
<button ng-click="clickMe()" class="btn btn-primary">CLICK ME</button>

ANGULARJS

  $scope.clickMe = function() {
    $scope.loading = true;
    $http.get('test.json')
      .success(function(data) {
        $scope.cars = data[0].cars;
        $scope.loading = false;
    });
  }

Of course you can move the loading box html code into a directive, then use $watch on $scope.loading. In which case:

HTML:

<loading></loading>

ANGULARJS DIRECTIVE:

  .directive('loading', function () {
      return {
        restrict: 'E',
        replace:true,
        template: '<div class="loading"><img src="..."/>LOADING...</div>',
        link: function (scope, element, attr) {
              scope.$watch('loading', function (val) {
                  if (val)
                      $(element).show();
                  else
                      $(element).hide();
              });
        }
      }
  })

PLUNK: http://plnkr.co/edit/AI1z21?p=preview

How to show/hide if variable is null

In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.

Check this out.

Get only the Date part of DateTime in mssql

We can use this method:

CONVERT(VARCHAR(10), GETDATE(), 120)

Last parameter changes the format to only to get time or date in specific formats.

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

If you don't have httpd.conf in folder /etc/apache2, you should have apache2.conf - simply add:

ServerName localhost

Then restart the apache2 service.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

  1. Just Disable Mock SD card optimization in the developer options
  2. Turn off "Turn on MIUI optimization"
  3. Mark force-closed apps

These Settings worked for me.Cheers!

Display an array in a readable/hierarchical format

I think that var_export(), the forgotten brother of var_dump() has the best output - it's more compact:

echo "<pre>";
var_export($menue);
echo "</pre>";

By the way: it's not allway necessary to use <pre>. var_dump() and var_export() are already formatted when you take a look in the source code of your webpage.

How to merge a specific commit in Git

'git cherry-pick' should be your answer here.

Apply the change introduced by an existing commit.

Do not forget to read bdonlan's answer about the consequence of cherry-picking in this post:
"Pull all commits from a branch, push specified commits to another", where:

A-----B------C
 \
  \
   D

becomes:

A-----B------C
 \
  \
   D-----C'

The problem with this commit is that git considers commits to include all history before them

Where C' has a different SHA-1 ID.
Likewise, cherry picking a commit from one branch to another basically involves generating a patch, then applying it, thus losing history that way as well.

This changing of commit IDs breaks git's merging functionality among other things (though if used sparingly there are heuristics that will paper over this).
More importantly though, it ignores functional dependencies - if C actually used a function defined in B, you'll never know.

How to compile LEX/YACC files on Windows?

I was having the same problem, it has a very simple solution.
Steps for executing the 'Lex' program:

  1. Tools->'Lex File Compiler'
  2. Tools->'Lex Build'
  3. Tools->'Open CMD'
  4. Then in command prompt type 'name_of_file.exe' example->'1.exe'
  5. Then entering the whole input press Ctrl + Z and press Enter.

Example

How to put two divs on the same line with CSS in simple_form in rails?

You can't float or set the width of an inline element. Remove display: inline; from both classes and your markup should present fine.

EDIT: You can set the width, but it will cause the element to be rendered as a block.

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

How to calculate the angle between a line and the horizontal axis?

deltaY = Math.Abs(P2.y - P1.y);
deltaX = Math.Abs(P2.x - P1.x);

angleInDegrees = Math.atan2(deltaY, deltaX) * 180 / PI

if(p2.y > p1.y) // Second point is lower than first, angle goes down (180-360)
{
  if(p2.x < p1.x)//Second point is to the left of first (180-270)
    angleInDegrees += 180;
  else //(270-360)
    angleInDegrees += 270;
}
else if (p2.x < p1.x) //Second point is top left of first (90-180)
  angleInDegrees += 90;

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

What's the use of ob_start() in php?

No, you are wrong, but the direction fits ;)

The Output-Buffering buffers the output of a script. Thats (in short) everthing after echo or print. The thing with the headers is, that they only can get sent, if they are not already sent. But HTTP says, that headers are the very first of the transmission. So if you output something for the first time (in a request) the headers are sent and you can not set any other headers.

How to force a UIViewController to Portrait orientation in iOS 6

Just go to project.plist then add Supported interface orientation and then add only Portrait (bottom home button) and Portrait (top home button).

You can add or remove there orientation as per your project requirement .

Thanks

Remove item from list based on condition

You can only remove something you have a reference to. So you will have to search the entire list:

stuff r;
foreach(stuff s in prods) {
  if(s.ID == 1) {
      r = s;
      break;
  }
}
prods.Remove(r);

or

for(int i = 0; i < prods.Length; i++) {
    if(prods[i].ID == 1) {
        prods.RemoveAt(i);
        break;
    }
}

Why Choose Struct Over Class?

With classes you get inheritance and are passed by reference, structs do not have inheritance and are passed by value.

There are great WWDC sessions on Swift, this specific question is answered in close detail in one of them. Make sure you watch those, as it will get you up to speed much more quickly then the Language guide or the iBook.

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

What is the difference between instanceof and Class.isAssignableFrom(...)?

How about some examples to show it in action...

@Test
public void isInstanceOf() {
    Exception anEx1 = new Exception("ex");
    Exception anEx2 = new RuntimeException("ex");
    RuntimeException anEx3 = new RuntimeException("ex");

    //Base case, handles inheritance
    Assert.assertTrue(anEx1 instanceof Exception);
    Assert.assertTrue(anEx2 instanceof Exception);
    Assert.assertTrue(anEx3 instanceof Exception);

    //Other cases
    Assert.assertFalse(anEx1 instanceof RuntimeException);
    Assert.assertTrue(anEx2 instanceof RuntimeException);
    Assert.assertTrue(anEx3 instanceof RuntimeException);
}

@Test
public void isAssignableFrom() {
    Exception anEx1 = new Exception("ex");
    Exception anEx2 = new RuntimeException("ex");
    RuntimeException anEx3 = new RuntimeException("ex");

    //Correct usage = The base class goes first
    Assert.assertTrue(Exception.class.isAssignableFrom(anEx1.getClass()));
    Assert.assertTrue(Exception.class.isAssignableFrom(anEx2.getClass()));
    Assert.assertTrue(Exception.class.isAssignableFrom(anEx3.getClass()));

    //Incorrect usage = Method parameter is used in the wrong order
    Assert.assertTrue(anEx1.getClass().isAssignableFrom(Exception.class));
    Assert.assertFalse(anEx2.getClass().isAssignableFrom(Exception.class));
    Assert.assertFalse(anEx3.getClass().isAssignableFrom(Exception.class));
}

Getting path relative to the current working directory?

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

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

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

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

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

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

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

Important points:

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

Change WPF window background image in C# code

I have been trying all the answers here with no success. Here is the simplest way to do it with ms-appx

        ImageBrush myBrush = new ImageBrush();
        Image image = new Image();
        image.Source = new BitmapImage(new Uri(@"ms-appx:///Assets/background.jpg"));
        myBrush.ImageSource = image.Source;
        TheGrid.Background = myBrush;

Assets folder is in the first level of my project, so make sure to change the path as convenient.

How do I split a string on a delimiter in Bash?

This also works:

IN="[email protected];[email protected]"
echo ADD1=`echo $IN | cut -d \; -f 1`
echo ADD2=`echo $IN | cut -d \; -f 2`

Be careful, this solution is not always correct. In case you pass "[email protected]" only, it will assign it to both ADD1 and ADD2.

Regular Expression to match string starting with a specific word

If you wish to match only lines beginning with stop use

^stop

If you wish to match lines beginning with the word stop followed by a space

^stop\s

Or, if you wish to match lines beginning with the word stop but followed by either a space or any other non word character you can use (your regex flavor permitting)

^stop\W

On the other hand, what follows matches a word at the beginning of a string on most regex flavors (in these flavors \w matches the opposite of \W)

^\w

If your flavor does not have the \w shortcut, you can use

^[a-zA-Z0-9]+

Be wary that this second idiom will only match letters and numbers, no symbol whatsoever.

Check your regex flavor manual to know what shortcuts are allowed and what exactly do they match (and how do they deal with Unicode.)

Generating a drop down list of timezones with PHP

$timezone = array(
    'Pacific/Midway' => '(GMT-11:00) Midway Island, Samoa',
    'America/Adak' => '(GMT-10:00) Hawaii-Aleutian',
    'Etc/GMT+10' => '(GMT-10:00) Hawaii',
    'Pacific/Marquesas' => '(GMT-09:30) Marquesas Islands',
    'Pacific/Gambier' => '(GMT-09:00) Gambier Islands',
    'America/Anchorage' => '(GMT-09:00) Alaska',
    'America/Ensenada' => '(GMT-08:00) Tijuana, Baja California',
    'Etc/GMT+8' => '(GMT-08:00) Pitcairn Islands',
    'America/Los_Angeles' => '(GMT-08:00) Pacific Time (US & Canada)',
    'America/Denver' => '(GMT-07:00) Mountain Time (US & Canada)',
    'America/Chihuahua' => '(GMT-07:00) Chihuahua, La Paz, Mazatlan',
    'America/Dawson_Creek' => '(GMT-07:00) Arizona',
    'America/Belize' => '(GMT-06:00) Saskatchewan, Central America',
    'America/Cancun' => '(GMT-06:00) Guadalajara, Mexico City, Monterrey',
    'Chile/EasterIsland' => '(GMT-06:00) Easter Island',
    'America/Chicago' => '(GMT-06:00) Central Time (US & Canada)',
    'America/New_York' => '(GMT-05:00) Eastern Time (US & Canada)',
    'America/Havana' => '(GMT-05:00) Cuba',
    'America/Bogota' => '(GMT-05:00) Bogota, Lima, Quito, Rio Branco',
    'America/Caracas' => '(GMT-04:30) Caracas',
    'America/Santiago' => '(GMT-04:00) Santiago',
    'America/La_Paz' => '(GMT-04:00) La Paz',
    'Atlantic/Stanley' => '(GMT-04:00) Faukland Islands',
    'America/Campo_Grande' => '(GMT-04:00) Brazil',
    'America/Goose_Bay' => '(GMT-04:00) Atlantic Time (Goose Bay)',
    'America/Glace_Bay' => '(GMT-04:00) Atlantic Time (Canada)',
    'America/St_Johns' => '(GMT-03:30) Newfoundland',
    'America/Araguaina' => '(GMT-03:00) UTC-3',
    'America/Montevideo' => '(GMT-03:00) Montevideo',
    'America/Miquelon' => '(GMT-03:00) Miquelon, St. Pierre',
    'America/Godthab' => '(GMT-03:00) Greenland',
    'America/Argentina/Buenos_Aires' => '(GMT-03:00) Buenos Aires',
    'America/Sao_Paulo' => '(GMT-03:00) Brasilia',
    'America/Noronha' => '(GMT-02:00) Mid-Atlantic',
    'Atlantic/Cape_Verde' => '(GMT-01:00) Cape Verde Is.',
    'Atlantic/Azores' => '(GMT-01:00) Azores',
    'Europe/Belfast' => '(GMT) Greenwich Mean Time : Belfast',
    'Europe/Dublin' => '(GMT) Greenwich Mean Time : Dublin',
    'Europe/Lisbon' => '(GMT) Greenwich Mean Time : Lisbon',
    'Europe/London' => '(GMT) Greenwich Mean Time : London',
    'Africa/Abidjan' => '(GMT) Monrovia, Reykjavik',
    'Europe/Amsterdam' => '(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'Europe/Belgrade' => '(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',
    'Europe/Brussels' => '(GMT+01:00) Brussels, Copenhagen, Madrid, Paris',
    'Africa/Algiers' => '(GMT+01:00) West Central Africa',
    'Africa/Windhoek' => '(GMT+01:00) Windhoek',
    'Asia/Beirut' => '(GMT+02:00) Beirut',
    'Africa/Cairo' => '(GMT+02:00) Cairo',
    'Asia/Gaza' => '(GMT+02:00) Gaza',
    'Africa/Blantyre' => '(GMT+02:00) Harare, Pretoria',
    'Asia/Jerusalem' => '(GMT+02:00) Jerusalem',
    'Europe/Minsk' => '(GMT+02:00) Minsk',
    'Asia/Damascus' => '(GMT+02:00) Syria',
    'Europe/Moscow' => '(GMT+03:00) Moscow, St. Petersburg, Volgograd',
    'Africa/Addis_Ababa' => '(GMT+03:00) Nairobi',
    'Asia/Tehran' => '(GMT+03:30) Tehran',
    'Asia/Dubai' => '(GMT+04:00) Abu Dhabi, Muscat',
    'Asia/Yerevan' => '(GMT+04:00) Yerevan',
    'Asia/Kabul' => '(GMT+04:30) Kabul',
    'Asia/Yekaterinburg' => '(GMT+05:00) Ekaterinburg',
    'Asia/Tashkent' => '(GMT+05:00) Tashkent',
    'Asia/Kolkata' => '(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi',
    'Asia/Katmandu' => '(GMT+05:45) Kathmandu',
    'Asia/Dhaka' => '(GMT+06:00) Astana, Dhaka',
    'Asia/Novosibirsk' => '(GMT+06:00) Novosibirsk',
    'Asia/Rangoon' => '(GMT+06:30) Yangon (Rangoon)',
    'Asia/Bangkok' => '(GMT+07:00) Bangkok, Hanoi, Jakarta',
    'Asia/Krasnoyarsk' => '(GMT+07:00) Krasnoyarsk',
    'Asia/Hong_Kong' => '(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi',
    'Asia/Irkutsk' => '(GMT+08:00) Irkutsk, Ulaan Bataar',
    'Australia/Perth' => '(GMT+08:00) Perth',
    'Australia/Eucla' => '(GMT+08:45) Eucla',
    'Asia/Tokyo' => '(GMT+09:00) Osaka, Sapporo, Tokyo',
    'Asia/Seoul' => '(GMT+09:00) Seoul',
    'Asia/Yakutsk' => '(GMT+09:00) Yakutsk',
    'Australia/Adelaide' => '(GMT+09:30) Adelaide',
    'Australia/Darwin' => '(GMT+09:30) Darwin',
    'Australia/Brisbane' => '(GMT+10:00) Brisbane',
    'Australia/Hobart' => '(GMT+10:00) Hobart',
    'Asia/Vladivostok' => '(GMT+10:00) Vladivostok',
    'Australia/Lord_Howe' => '(GMT+10:30) Lord Howe Island',
    'Etc/GMT-11' => '(GMT+11:00) Solomon Is., New Caledonia',
    'Asia/Magadan' => '(GMT+11:00) Magadan',
    'Pacific/Norfolk' => '(GMT+11:30) Norfolk Island',
    'Asia/Anadyr' => '(GMT+12:00) Anadyr, Kamchatka',
    'Pacific/Auckland' => '(GMT+12:00) Auckland, Wellington',
    'Etc/GMT-12' => '(GMT+12:00) Fiji, Kamchatka, Marshall Is.',
    'Pacific/Chatham' => '(GMT+12:45) Chatham Islands',
    'Pacific/Tongatapu' => '(GMT+13:00) Nukualofa',
    'Pacific/Kiritimati' => '(GMT+14:00) Kiritimati',

date_default_timezone_set($timezone);

Check if a string contains a string in C++

#include <algorithm>        // std::search
#include <string>
using std::search; using std::count; using std::string;

int main() {
    string mystring = "The needle in the haystack";
    string str = "needle";
    string::const_iterator it;
    it = search(mystring.begin(), mystring.end(), 
                str.begin(), str.end()) != mystring.end();

    // if string is found... returns iterator to str's first element in mystring
    // if string is not found... returns iterator to mystring.end()

if (it != mystring.end())
    // string is found
else
    // not found

return 0;
}

How can I round a number in JavaScript? .toFixed() returns a string?

You can simply use a '+' to convert the result to a number.

var x = 22.032423;
x = +x.toFixed(2); // x = 22.03

How to set env variable in Jupyter notebook

If you're using Python, you can define your environment variables in a .env file and load them from within a Jupyter notebook using python-dotenv.

Install python-dotenv:

pip install python-dotenv

Load the .env file in a Jupyter notebook:

%load_ext dotenv
%dotenv

Random state (Pseudo-random number) in Scikit learn

If there is no randomstate provided the system will use a randomstate that is generated internally. So, when you run the program multiple times you might see different train/test data points and the behavior will be unpredictable. In case, you have an issue with your model you will not be able to recreate it as you do not know the random number that was generated when you ran the program.

If you see the Tree Classifiers - either DT or RF, they try to build a try using an optimal plan. Though most of the times this plan might be the same there could be instances where the tree might be different and so the predictions. When you try to debug your model you may not be able to recreate the same instance for which a Tree was built. So, to avoid all this hassle we use a random_state while building a DecisionTreeClassifier or RandomForestClassifier.

PS: You can go a bit in depth on how the Tree is built in DecisionTree to understand this better.

randomstate is basically used for reproducing your problem the same every time it is run. If you do not use a randomstate in traintestsplit, every time you make the split you might get a different set of train and test data points and will not help you in debugging in case you get an issue.

From Doc:

If int, randomstate is the seed used by the random number generator; If RandomState instance, randomstate is the random number generator; If None, the random number generator is the RandomState instance used by np.random.

In Angular, how to pass JSON object/array into directive?

As you say, you don't need to request the file twice. Pass it from your controller to your directive. Assuming you use the directive inside the scope of the controller:

.controller('MyController', ['$scope', '$http', function($scope, $http) {
  $http.get('locations/locations.json').success(function(data) {
      $scope.locations = data;
  });
}

Then in your HTML (where you call upon the directive).
Note: locations is a reference to your controllers $scope.locations.

<div my-directive location-data="locations"></div>

And finally in your directive

...
scope: {
  locationData: '=locationData'
},
controller: ['$scope', function($scope){
  // And here you can access your data
  $scope.locationData
}]
...

This is just an outline to point you in the right direction, so it's incomplete and not tested.

What is the standard naming convention for html/css ids and classes?

tl;dr;

There is no one true answer. You can pick one of the many out there, or create your own standards based on what makes sense, depending upon who you're working with. And it is 100% dependent upon the platform.


Original Post

Just one more alternative standard to consider:

<div id="id_name" class="class-name"></div>

And in your script:

var variableName = $("#id_name .class-name");

This just uses a camelCase, under_score, and hyphen-ation respectively for variables, ids, and classes. I've read about this standard on a couple of different websites. Although a little redundant in css/jquery selectors, redundancies make it easier to catch errors. eg: If you see .unknown_name or #unknownName in your CSS file, you know you need to figure out what that's actually referring to.


UPDATE 2019

(Hyphens are called 'kebab-case', underscores are called 'snake_case', and then you have 'TitleCase', 'pascalCase')

I personally dislike hyphens. I originally posted this as one alternative (because the rules are simple). However, Hyphens make selection shortcuts very difficult (double click, ctrl/option + left/right, and ctrl/cmd+D in vsCode. Also, class names and file names are the only place where hyphens work, because they're almost always in quotes or in css, etc. But the shortcut thing still applies.

In addition to variables, class names, and ids, you also want to look at file name conventions. And Git Branches.

My office's coding group actually had a meeting a month or two ago to discuss how we were going to name things. For git branches, we couldn't decide between 321-the_issue_description or 321_the-issue-description. (I wanted 321_theIssueDescription, but my coworkers didn't like that.)

An Example, to demonstrate working with other peoples' standards...

Vue.js does have a standard. Actually they have two alternate standards for several of their items. I dislike both of their versions for filenames. They recommend either "/path/kebab-case.vue" or "/path/TitleCase.Vue". The former is harder to rename, unless you're specifically trying to rename part of it. The latter is not good for cross-platform compatibility. I would prefer "/path/snake_case.vue". However, when working with other people or existing projects, it's important to follow whatever standard was already laid out. Therefore I go with kebab-case for filenames in Vue, even though I'll totally complain about it. Because not following that means changing a lot of files that vue-cli sets up.

Sequence contains no matching element

For those of you who faced this issue while creating a controller through the context menu, reopening Visual Studio as an administrator fixed it.

Handling optional parameters in javascript

So use the typeof operator to determine if the second parameter is an Array or function.

This can give some suggestions: http://www.planetpdf.com/developer/article.asp?ContentID=testing_for_object_types_in_ja

I am not certain if this is work or homework, so I don't want to give you the answer at the moment, but the typeof will help you determine it.

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How can I count the occurrences of a string within a file?

I'm taking some guesses here, because I don't quite understand what you're asking.

I think that what you want is a count of the number of lines on which the pattern 'echo' appears in the given file.

I've pasted your sample text into a file called 6741967.

First, grep finds the matches:

james@Brindle:tmp$grep echo 6741967 
    echo "Preparing to add a new user..."
echo "1. Add user"
echo "2. Exit"
echo "Enter your choice: "

Second, use wc -l to count the lines

james@Brindle:tmp$grep echo 6741967  | wc -l
       4

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

If your newline character is CRLF, that means it's a CHR(13) followed by CHR(10). If you REPLACE(input, CHR(10), '_'), that turns into CHR(13) followed by an underscore. Since CR on its own can be just as well rendered as a newline character, it'll appear to you as if an underscore has ben inserted after your newline, but actually only half of your newline has been replaced.

Use REPLACE(REPLACE(input, CHR(13)), CHR(10)) to replace all CR's and LF's.

Time calculation in php (add 10 hours)?

$date = date('h:i:s A', strtotime($today . ' + 10 hours'));

(untested)

What is the difference between atan and atan2 in C++?

I guess the main question tries to figure out: "when should I use one or the other", or "which should I use", or "Am I using the right one"?

I guess the important point is atan only was intended to feed positive values in a right-upwards direction curve like for time-distance vectors. Cero is always at the bottom left, and thigs can only go up and right, just slower or faster. atan doesn't return negative numbers, so you can't trace things in the 4 directions on a screen just by adding/subtracting its result.

atan2 is intended for the origin to be in the middle, and things can go backwards or down. That's what you'd use in a screen representation, because it DOES matter what direction you want the curve to go. So atan2 can give you negative numbers, because its cero is in the center, and its result is something you can use to trace things in 4 directions.

How to run a PowerShell script

I have a very simple answer which works:

  1. Open PowerShell in administrator mode
  2. Run: set-executionpolicy unrestricted
  3. Open a regular PowerShell window and run your script.

I found this solution following the link that was given as part of error message: About Execution Policies

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

Blurry text after using CSS transform: scale(); in Chrome

I have this same problem. I fixed this using:

.element {
  display: table
}

Unique on a dataframe with only selected columns

Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:

dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]

In Git, how do I figure out what my current revision is?

below will work with any previously pushed revision, not only HEAD

for abbreviated revision hash:

git log -1 --pretty=format:%h

for long revision hash:

git log -1 --pretty=format:%H

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

UPDATE m
SET [status]=10
FROM (
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

ClassNotFoundException com.mysql.jdbc.Driver

I experienced the same error after upgrading my java to 1.8.0_101. Try this: i. Remove the mysql.jar fro your buildpath. ii. Clean the server and project iii. Add the jar file back to the build path.

Worked for me.

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

It maybe the reason The php mysql api is deprecated. if your using below < PHP5.5 just update in your server to 5.6 and above.

An example of how to use getopts in bash

The example packaged with getopt (my distro put it in /usr/share/getopt/getopt-parse.bash) looks like it covers all of your cases:

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a 
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
        -c|--c-long) 
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "$2" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done

Accessing MP3 metadata with Python

What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:

from ID3 import *
try:
  id3info = ID3('file.mp3')
  print id3info
  # Change the tags
  id3info['TITLE'] = "Green Eggs and Ham"
  id3info['ARTIST'] = "Dr. Seuss"
  for k, v in id3info.items():
    print k, ":", v
except InvalidTagError, message:
  print "Invalid ID3 tag:", message

Remove excess whitespace from within a string

If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . " And you expect the answer to be "this string have lots of space", you can use the following solution:

$strng = "this string                        have lots of                        space  .   ";

$strng = trim(preg_replace('/\s+/',' ', $strng));

echo $strng;

Rails 3 migrations: Adding reference column?

You can add references to your model through command line in the following manner:

rails g migration add_column_to_tester user_id:integer

This will generate a migration file like :

class AddColumnToTesters < ActiveRecord::Migration
  def change
    add_column :testers, :user_id, :integer
  end
end

This works fine every time i use it..

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

For me this problem still exists with SSMS version 2016 (13.0.16100.1).

A decent workaround is to not use the 'Right click' -> 'Add table...' dialog, but simply drag the table you want to add from the Object Explorer, onto the Diagram surface. While dragging the mouse icon changes into an 'add' symbol and the table is added when you release the mouse.

Beats having to close SSMS every time.

jQuery toggle CSS?

For jQuery versions lower than 1.9 (see https://api.jquery.com/toggle-event):

$('#user_button').toggle(function () {
    $("#user_button").css({borderBottomLeftRadius: "0px"});
}, function () {
    $("#user_button").css({borderBottomLeftRadius: "5px"});
});

Using classes in this case would be better than setting the css directly though, look at the addClass and removeClass methods alecwh mentioned.

$('#user_button').toggle(function () {
    $("#user_button").addClass("active");
}, function () {
    $("#user_button").removeClass("active");
});

How can I make a button redirect my page to another page?

This is here:

 <button onClick="window.location='page_name.php';" value="click here" />

How to remove square brackets from list in Python?

if you have numbers in list, you can use map to apply str to each element:

print ', '.join(map(str, LIST))

^ map is C code so it's faster than str(i) for i in LIST

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

To clarify the problem with @@Identity:

For instance, if you insert a table and that table has triggers doing inserts, @@Identity will return the id from the insert in the trigger (a log_id or something), while scope_identity() will return the id from the insert in the original table.

So if you don't have any triggers, scope_identity() and @@identity will return the same value. If you have triggers, you need to think about what value you'd like.

How can I add a hint or tooltip to a label in C# Winforms?

just another way to do it.

Label lbl = new Label();
new ToolTip().SetToolTip(lbl, "tooltip text here");

Adjust width of input field to its input

It sounds like your expectation is that the style be applied dynamically to the width of the textbox based on the contents of the textbox. If so you will need some js to run on textbox contents changing, something like this:

<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">

Note: this solution only works when every character is exactly 8px wide.

Why is PHP session_destroy() not working?

If you need to clear the values of $_SESSION, set the array equal to an empty array:

$_SESSION = array();

Of course, you can't access the values of $_SESSION on another page once you call session_destroy, so it doesn't matter that much.

Try the following:

session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable

Rails Active Record find(:all, :order => ) issue

Could be two things. First,

This code is deprecated:

Model.find(:all, :order => ...)

should be:

Model.order(...).all

Find is no longer supported with the :all, :order, and many other options.

Second, you might have had a default_scope that was enforcing some ordering before you called find on Show.

Hours of digging around on the internet led me to a few useful articles that explain the issue:

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

jQuery animate margin top

You had MarginTop instead of marginTop

http://jsfiddle.net/kX7b6/1/

It is also very buggy if you leave mid animation, here is update:

http://jsfiddle.net/kX7b6/3/

Note I changed it to mouseenter and mouseleave because I don't think the intention was to cancel the animation when you hover over the red or green area.

How to silence output in a Bash script?

Try with:

myprogram &>/dev/null

to get no output

HTML5 video won't play in Chrome only

Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?

Browsers might use the canPlayType method internally to check if a <source> is candidate to playback.

In Chrome, I have these results:

document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"

window.open(url, '_blank'); not working on iMac/Safari

window.location.assign(url) this fixs the window.open(url) issue in ios devices

How do I test if a variable does not equal either of two values?

This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).

switch(test) {
    case A:
    case B:
        do other stuff;
        break;
    default:
        do stuff;
}

How to display all elements in an arraylist?

Hi sorry the code for the second one should be:

private static void getAll(CarList c1) {

ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{   
      System.out.println(item.getMake()
                       + " "
                       + item.getReg()
                       );
}

}

I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:

CarList c1; c1 = new CarList();

everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.

What is the equivalent of the C++ Pair<L,R> in Java?

The biggest problem is probably that one can't ensure immutability on A and B (see How to ensure that type parameters are immutable) so hashCode() may give inconsistent results for the same Pair after is inserted in a collection for instance (this would give undefined behavior, see Defining equals in terms of mutable fields). For a particular (non generic) Pair class the programmer may ensure immutability by carefully choosing A and B to be immutable.

Anyway, clearing generic's warnings from @PeterLawrey's answer (java 1.7) :

public class Pair<A extends Comparable<? super A>,
                    B extends Comparable<? super B>>
        implements Comparable<Pair<A, B>> {

    public final A first;
    public final B second;

    private Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public static <A extends Comparable<? super A>,
                    B extends Comparable<? super B>>
            Pair<A, B> of(A first, B second) {
        return new Pair<A, B>(first, second);
    }

    @Override
    public int compareTo(Pair<A, B> o) {
        int cmp = o == null ? 1 : (this.first).compareTo(o.first);
        return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
    }

    @Override
    public int hashCode() {
        return 31 * hashcode(first) + hashcode(second);
    }

    // TODO : move this to a helper class.
    private static int hashcode(Object o) {
        return o == null ? 0 : o.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Pair))
            return false;
        if (this == obj)
            return true;
        return equal(first, ((Pair<?, ?>) obj).first)
                && equal(second, ((Pair<?, ?>) obj).second);
    }

    // TODO : move this to a helper class.
    private boolean equal(Object o1, Object o2) {
        return o1 == o2 || (o1 != null && o1.equals(o2));
    }

    @Override
    public String toString() {
        return "(" + first + ", " + second + ')';
    }
}

Additions/corrections much welcome :) In particular I am not quite sure about my use of Pair<?, ?>.

For more info on why this syntax see Ensure that objects implement Comparable and for a detailed explanation How to implement a generic max(Comparable a, Comparable b) function in Java?

ipad safari: disable scrolling, and bounce effect?

improved answer @Ben Bos and commented by @Tim

This css will help prevent scrolling and performance issue with css re-render because position changed / little lagging without width and height

body,
html {
  position: fixed;
  width: 100%; 
  height: 100%
}

How to pass ArrayList of Objects from one to another activity using Intent in android?

Pass your object via Parcelable. And here is a good tutorial to get you started.
First Question should implements Parcelable like this and add the those lines:

public class Question implements Parcelable{
    public Question(Parcel in) {
        // put your data using = in.readString();
  this.operands = in.readString();;
    this.choices = in.readString();;
    this.userAnswerIndex = in.readString();;

    }

    public Question() {
    }

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(operands);
        dest.writeString(choices);
        dest.writeString(userAnswerIndex);
    }

    public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {

        @Override
        public Question[] newArray(int size) {
            return new Question[size];
        }

        @Override
        public Question createFromParcel(Parcel source) {
            return new Question(source);
        }
    };

}

Then pass your data like this:

Question question = new Question();
// put your data
  Intent resultIntent = new Intent(this, ResultActivity.class);
  resultIntent.putExtra("QuestionsExtra", question);
  startActivity(resultIntent);

And get your data like this:

Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
    question = extras.getParcelable("QuestionsExtra");
}

This will do!

IOError: [Errno 32] Broken pipe: Python

I know this is not the "proper" way to do it, but if you are simply interested in getting rid of the error message, you could try this workaround:

python your_python_code.py 2> /dev/null | other_command

Gradle does not find tools.jar

Add this to gradle.properties:

org.gradle.java.home=C:\Program Files\Java\jdk1.8.0_91

Unable to make the session state request to the session state server

Check that:

stateConnectionString="tcpip=server:port"

is correct. Also please check that default port (42424) is available and your system does not have a firewall that is blocking the port on your system

How do I add space between two variables after a print in Python

print( "hello " +k+ "  " +ln);

where k and ln are variables

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

What are the rules for calling the superclass constructor?

The only way to pass values to a parent constructor is through an initialization list. The initilization list is implemented with a : and then a list of classes and the values to be passed to that classes constructor.

Class2::Class2(string id) : Class1(id) {
....
}

Also remember that if you have a constructor that takes no parameters on the parent class, it will be called automatically prior to the child constructor executing.

RSA encryption and decryption in Python

In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:

import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast

random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key

publickey = key.publickey() # pub key export for exchange

encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'

print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()

#decrypted code below

f = open('encryption.txt', 'r')
message = f.read()


decrypted = key.decrypt(ast.literal_eval(str(encrypted)))

print 'decrypted', decrypted

f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()

ORA-28001: The password has expired

C:\>sqlplus /nolog
SQL> connect / as SYSDBA
SQL> select * from dba_profiles;
SQL> alter profile default limit password_life_time unlimited;
SQL> alter user database_name identified by new_password;
SQL> commit;
SQL> exit;

Show spinner GIF during an $http request in AngularJS?

You can use angular interceptor to manage http request calls

  <div class="loader">
    <div id="loader"></div>
  </div>

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

    app.factory('httpRequestInterceptor', ['$rootScope', '$location', function ($rootScope, $location) {
        return {
            request: function ($config) {
                $('.loader').show();
                return $config;
            },
            response: function ($config) {
                $('.loader').hide();
                return $config;
            },
            responseError: function (response) {
                return response;
            }
        };
    }]);

    app.config(['$stateProvider', '$urlRouterProvider', '$httpProvider',
        function ($stateProvider, $urlRouterProvider, $httpProvider) {
            $httpProvider.interceptors.push('httpRequestInterceptor');
        }]);

</script>

https://stackoverflow.com/a/49632155/4976786

What's default HTML/CSS link color?

The best way to get a browser's default styling on something is to not style the element at all in the first place.

How to watch for form changes in Angular

I thought about using the (ngModelChange) method, then thought about the FormBuilder method, and finally settled on a variation of Method 3. This saves decorating the template with extra attributes and automatically picks up changes to the model - reducing the possibility of forgetting something with Method 1 or 2.

Simplifying Method 3 a bit...

oldPerson = JSON.parse(JSON.stringify(this.person));

ngDoCheck(): void {
    if (JSON.stringify(this.person) !== JSON.stringify(this.oldPerson)) {
        this.doSomething();
        this.oldPerson = JSON.parse(JSON.stringify(this.person));
    }
}

You could add a timeout to only call doSomething() after x number of milliseconds to simulate debounce.

oldPerson = JSON.parse(JSON.stringify(this.person));

ngDoCheck(): void {
    if (JSON.stringify(this.person) !== JSON.stringify(this.oldPerson)) {
        if (timeOut) clearTimeout(timeOut);
        let timeOut = setTimeout(this.doSomething(), 2000);
        this.oldPerson = JSON.parse(JSON.stringify(this.person));
    }
}

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Reload an iframe with jQuery

You need to use

[0].src

to find the source of the iframe and its URL needs to be on the same domain of the parent.

setInterval(refreshMe, 5000);
function refreshMe() {
    $("#currentElement")[0].src = $("#currentElement")[0].src;   
}

File opens instead of downloading in internet explorer in a href link

It is known HTTP headers problem with Internet Explorer. Try to edit your server's .htaccess file (if you use Apache) and include the following rules:

# IE: force download of .xxx files
AddType application/octect-stream .xxx
<Files *.xxx>
  ForceType application/octet-stream
  Header Set Content-Disposition attachment
</Files>

Wordpress - Images not showing up in the Media Library

I had this problem with wordpress 3.8.1 and it turned out that my functions.php wasn't saved as utf-8. Re-saved it and it

PowerShell: Format-Table without headers

Another approach is to use ForEach-Object to project individual items to a string and then use the Out-String CmdLet to project the final results to a string or string array:

gci Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CID | foreach { "CID Key {0}" -f $_.Name } | Out-String

#Result: One multi-line string equal to:
@"
CID Key HKEY_CLASSES_ROOT\CID\2a621c8a-7d4b-4d7b-ad60-a957fd70b0d0
CID Key HKEY_CLASSES_ROOT\CID\2ec6f5b2-8cdc-461e-9157-ffa84c11ba7d
CID Key HKEY_CLASSES_ROOT\CID\5da2ceaf-bc35-46e0-aabd-bd826023359b
CID Key HKEY_CLASSES_ROOT\CID\d13ad82e-d4fb-495f-9b78-01d2946e6426
"@

gci Microsoft.PowerShell.Core\Registry::HKEY_CLASSES_ROOT\CID | foreach { "CID Key {0}" -f $_.Name } | Out-String -Stream

#Result: An array of single line strings equal to:
@(
"CID Key HKEY_CLASSES_ROOT\CID\2a621c8a-7d4b-4d7b-ad60-a957fd70b0d0",
"CID Key HKEY_CLASSES_ROOT\CID\2ec6f5b2-8cdc-461e-9157-ffa84c11ba7d",
"CID Key HKEY_CLASSES_ROOT\CID\5da2ceaf-bc35-46e0-aabd-bd826023359b",
"CID Key HKEY_CLASSES_ROOT\CID\d13ad82e-d4fb-495f-9b78-01d2946e6426")

The benefit of this approach is that you can store the result to a variable and it will NOT have any empty lines.

How can I give an imageview click effect like a button on Android?

EDIT: Although the original answer below works and is easy to set up, refer to this post by an Android Developer Advocate at Google if you want / need a more efficient implementation. Also note that the android:foreground attribute is coming to all Views, including ImageView, by default in Android M.


The problem with using a selector for an ImageView is that you can only set it as the view's background - as long as your image is opaque, you will not see the selector's effect behind it.

The trick is to wrap your ImageView in a FrameLayout with the attribute android:foreground which allows us to define an overlay for its content. If we set android:foregroundto a selector (e.g.?android:attr/selectableItemBackground for API level 11+) and attach the OnClickListener to the FrameLayout instead of the ImageView, the image will be overlaid with our selector's drawable - the click effect we desire!

Behold:

<FrameLayout
    android:id="@+id/imageButton"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:foreground="?android:attr/selectableItemBackground" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/yourImageFile" />

</FrameLayout>

(Note this should be placed within your parent layout.)

final View imageButton = findViewById(R.id.imageButton);
imageButton.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View view) {
        // do whatever we wish!
    }
});

Calling an executable program using awk

#!/usr/bin/awk -f

BEGIN {
    command = "ls -lh"

    command |getline
}

Runs "ls -lh" in an awk script

How to add /usr/local/bin in $PATH on Mac

In MAC OS Catalina, this are the steps that worked for me, all the above solutions did help but didn't solve my problem.

  1. check node --version, still the old one in use.
  2. cd ~/
  3. atom .bash_profile
  4. Remove the $PATH pointing to old node version, in my case it was /usr/local/bin/node/@node8
  5. Add & save this to $PATH instead "export PATH=$PATH:/usr/local/git/bin:/usr/local/bin"
  6. Close all applications using node (terminal, simulator, browser expo etc)
  7. restart terminal and check node --version

How do I read the contents of a Node.js stream into a string variable?

(This answer is from years ago, when it was the best answer. There is now a better answer below this. I haven't kept up with node.js, and I cannot delete this answer because it is marked "correct on this question". If you are thinking of down clicking, what do you want me to do?)

The key is to use the data and end events of a Readable Stream. Listen to these events:

stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });

When you receive the data event, add the new chunk of data to a Buffer created to collect the data.

When you receive the end event, convert the completed Buffer into a string, if necessary. Then do what you need to do with it.

How to get a dependency tree for an artifact?

If you use a current version of m2eclipse (which you should if you use eclipse and maven):

Select the menu entry

Navigate -> Open Maven POM

and enter the artifact you are looking for.

The pom will open in the pom editor, from which you can select the tab Dependency Hierarchy to view the dependency hierarchy (as the name suggests :-) )

Resize svg when window is resized in d3.js

It's kind of ugly if the resizing code is almost as long as the code for building the graph in first place. So instead of resizing every element of the existing chart, why not simply reloading it? Here is how it worked for me:

function data_display(data){
   e = document.getElementById('data-div');
   var w = e.clientWidth;
   // remove old svg if any -- otherwise resizing adds a second one
   d3.select('svg').remove();
   // create canvas
   var svg = d3.select('#data-div').append('svg')
                                   .attr('height', 100)
                                   .attr('width', w);
   // now add lots of beautiful elements to your graph
   // ...
}

data_display(my_data); // call on page load

window.addEventListener('resize', function(event){
    data_display(my_data); // just call it again...
}

The crucial line is d3.select('svg').remove();. Otherwise each resizing will add another SVG element below the previous one.

Disable XML validation in Eclipse

In JBoss Developer 4.0 and above (Eclipse-based), this is a tad easier. Just right-click on your file or folder that contains xml-based files, choose "Exclude Validation", then click "Yes" to confirm. Then right-click the same files/folder again and click on "Validate", which will remove the errors with a confirmation.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Perhaps the answer to this question is of use here too: how to find libstdc++.so.6: that contain GLIBCXX_3.4.19 for RHEL 6?

curl -O http://ftp.de.debian.org/debian/pool/main/g/gcc-4.7/libstdc++6-4.7-dbg_4.7.2-5_i386.deb
ar -x libstdc++6-4.7-dbg_4.7.2-5_i386.deb && tar xvf data.tar.gz
mkdir backup
cp /usr/lib/libstdc++.so* backup/
cp ./usr/lib/i386-linux-gnu/debug/libstdc++.so.6.0.17 /usr/lib
ln -s libstdc++.so.6.0.17 libstdc++.so.6

Iterate through 2 dimensional array

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

pandas read_csv index_col=None not working with delimiters at the end of each line

Quick Answer

Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column.

More Detail

After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):

index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.


EDIT 10/20/2014 - More information

I found another valuable entry that is specifically about trailing limiters and how to simply ignore them:

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

Set value to currency in <input type="number" />

The browser only allows numerical inputs when the type is set to "number". Details here.

You can use the type="text" and filter out any other than numerical input using JavaScript like descripted here

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

How to get the Android Emulator's IP address?

public String getLocalIpAddress() {

    try {
        for (Enumeration < NetworkInterface > en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration < InetAddress > enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

C++ for each, pulling from vector elements

The for each syntax is supported as an extension to native c++ in Visual Studio.

The example provided in msdn

#include <vector>
#include <iostream>

using namespace std;

int main() 
{
  int total = 0;

  vector<int> v(6);
  v[0] = 10; v[1] = 20; v[2] = 30;
  v[3] = 40; v[4] = 50; v[5] = 60;

  for each(int i in v) {
    total += i;
  }

  cout << total << endl;
}

(works in VS2013) is not portable/cross platform but gives you an idea of how to use for each.

The standard alternatives (provided in the rest of the answers) apply everywhere. And it would be best to use those.

Question mark characters displaying within text, why is this?

Your browser hasn't interpretted the encoding of the page correctly (either because you've forced it to a particular setting, or the page is set incorrectly), and thus cannot display some of the characters.

Save matplotlib file to a directory

Here is a simple example for saving to a directory(external usb drive) using Python version 2.7.10 with Sublime Text 2 editor:

import numpy as np 
import matplotlib.pyplot as plt

X = np.linspace(-np.pi, np.pi, 256, endpoint = True)
C, S = np.cos(X), np.sin(X)

plt.plot(X, C, color = "blue", linewidth = 1.0, linestyle = "-")
plt.plot(X, S, color = "red", linewidth = 1.0, linestyle = "-")

plt.savefig("/Volumes/seagate/temp_swap/sin_cos_2.png", dpi = 72)

How to change the default docker registry from docker.io to my private registry?

There is the use case of a mirror of Docker Hub (such as Artifactory or a custom one), which I haven't seen mentioned here. This is one of the most valid cases where changing the default registry is needed.

Luckily, Docker (at least version 19.03.3) allows you to set a mirror (tested in Docker CE). I don't know if this will work with additional images pushed to that mirror that aren't on Docker Hub, but I do know it will use the mirror instead. Docker documentation: https://docs.docker.com/registry/recipes/mirror/#configure-the-docker-daemon.

Essentially, you need to add "registry-mirrors": [] to the /etc/docker/daemon.json configuration file. So if you have a mirror hosted at https://my-docker-repo.my.company.com, your /etc/docker/daemon.json should contain:

{
  "registry-mirrors": ["https://my-docker-repo-mirror.my.company.com"]
}

Afterwards, restart the Docker daemon. Now if you do a docker pull postgres:12, Docker should fetch the image from the mirror instead of directly from Docker Hub. This is much better than prepending all images with my-docker-repo.my.company.com

Excel: Can I create a Conditional Formula based on the Color of a Cell?

Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:

=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))

Hit OK then close the "Name Manager" window.

Now, in cell A1 enter the following:

=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))

This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html

Cheers.

::Edit::

The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:

=GET.CELL(63,Sheet1!B2)

Laravel 5 not finding css files

Laravel version 6.0.2

I also had the same problem. I used

<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" >
<link href="{{ asset('css/bootstrap.css') }}" rel="stylesheet">

And after moving the CSS folder from folder resource to folder public it works

IFrame: This content cannot be displayed in a frame

use <meta http-equiv="X-Frame-Options" content="allow"> in the one to show in the iframe to allow it.

PHP session lost after redirect

After trying many solutions here on SO and other blogs... what worked for me was adding .htaccess to my website root.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursitename.com$
RewriteRule ^.*$ "http\:\/\/www\.yoursitename\.com" [R=301,L]

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How can I delete a service in Windows?

Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):

SC STOP shortservicename
SC DELETE shortservicename

Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc is aliased to set-content. So sc delete service will actually create a file called delete with the content service. To do this in Powershell, use sc.exe delete service instead


If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:

SC QUERY state= all >"C:\Service List.txt"

For a more concise list, execute this command:

SC QUERY state= all | FIND "_NAME"

The short service name will be listed just above the display name, like this:

SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service

And thus to delete that service:

SC STOP MyService
SC DELETE MyService

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

CSS to stop text wrapping under image

If you want the margin-left to work on a span element you'll need to make it display: inline-block or display:block as well.

Get Enum from Description attribute

The solution works good except if you have a Web Service.

You would need to do the Following as the Description Attribute is not serializable.

[DataContract]
public enum ControlSelectionType
{
    [EnumMember(Value = "Not Applicable")]
    NotApplicable = 1,
    [EnumMember(Value = "Single Select Radio Buttons")]
    SingleSelectRadioButtons = 2,
    [EnumMember(Value = "Completely Different Display Text")]
    SingleSelectDropDownList = 3,
}

public static string GetDescriptionFromEnumValue(Enum value)
{
        EnumMemberAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(EnumMemberAttribute), false)
            .SingleOrDefault() as EnumMemberAttribute;
        return attribute == null ? value.ToString() : attribute.Value;
}

Leap year calculation

C# implementation

public bool LeapYear()
{
     int year = 2016;

     return year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ;
}

Print page numbers on pages when printing html

As @page with pagenumbers don't work in browsers for now I was looking for alternatives.
I've found an answer posted by Oliver Kohll.
I'll repost it here so everyone could find it more easily:
For this answer we are not using @page, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the link of an example.
The CSS is:

#content {
    display: table;
}

#pageFooter {
    display: table-footer-group;
}

#pageFooter:after {
    counter-increment: page;
    content: counter(page);
}

And the HTML code is:

<div id="content">
  <div id="pageFooter">Page </div>
  multi-page content here...
</div>

This way you can customize your page number by editing parametrs to #pageFooter. My example:

#pageFooter:after {
    counter-increment: page;
    content:"Page " counter(page);
    left: 0; 
    top: 100%;
    white-space: nowrap; 
    z-index: 20;
    -moz-border-radius: 5px; 
    -moz-box-shadow: 0px 0px 4px #222;  
    background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);  
  }

This trick worked for me fine. Hope it will help you.

fatal: ambiguous argument 'origin': unknown revision or path not in the working tree

The git diff command typically expects one or more commit hashes to generate your diff. You seem to be supplying the name of a remote.

If you had a branch named origin, the commit hash at tip of the branch would have been used if you supplied origin to the diff command, but currently (with no corresponding branch) the command will produce the error you're seeing. It may be the case that you were previously working with a branch named origin.

An alternative, if you're trying to view the difference between your local branch, and a branch on a remote would be something along the lines of:

git diff origin/<branchname>

git diff <branchname> origin/<branchname>

Or other documented variants.

Edit: Having read further, I realise I'm slightly wrong, git diff origin is shorthand for diffing against the head of the specified remote, so git diff origin = git diff origin/HEAD (compare local git branch with remote branch?, Why is "origin/HEAD" shown when running "git branch -r"?)

It sounds like your origin does not have a HEAD, in my case this is because my remote is a bare repository that has never had a HEAD set.

Running git branch -r will show you if origin/HEAD is set, and if so, which branch it points at (e.g. origin/HEAD -> origin/<branchname>).

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

At least 8 = {8,}:

str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)

How do I copy an object in Java?

Why is there no answer for using Reflection API?

private static Object cloneObject(Object obj){
        try{
            Object clone = obj.getClass().newInstance();
            for (Field field : obj.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                field.set(clone, field.get(obj));
            }
            return clone;
        }catch(Exception e){
            return null;
        }
    }

It's really simple.

EDIT: Include child object via recursion

private static Object cloneObject(Object obj){
        try{
            Object clone = obj.getClass().newInstance();
            for (Field field : obj.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                if(field.get(obj) == null || Modifier.isFinal(field.getModifiers())){
                    continue;
                }
                if(field.getType().isPrimitive() || field.getType().equals(String.class)
                        || field.getType().getSuperclass().equals(Number.class)
                        || field.getType().equals(Boolean.class)){
                    field.set(clone, field.get(obj));
                }else{
                    Object childObj = field.get(obj);
                    if(childObj == obj){
                        field.set(clone, clone);
                    }else{
                        field.set(clone, cloneObject(field.get(obj)));
                    }
                }
            }
            return clone;
        }catch(Exception e){
            return null;
        }
    }

Calculate logarithm in python

The math.log function is to the base e, i.e. natural logarithm. If you want to the base 10 use math.log10.

Change color of PNG image via CSS?

Think I have a solution for this that's a) exactly what you were looking for 5 years ago, and b) is a bit simpler than the other code options here.

With any white png (eg, white icon on transparent background), you can add an ::after selector to recolor.

.icon {
    background: url(img/icon.png); /* Your icon */
    position: relative; /* Allows an absolute positioned psuedo element */
}

.icon::after{
    position: absolute; /* Positions psuedo element relative to .icon */
    width: 100%; /* Same dimensions as .icon */
    height: 100%;
    content: ""; /* Allows psuedo element to show */
    background: #EC008C; /* The color you want the icon to change to */
    mix-blend-mode: multiply; /* Only apply color on top of white, use screen if icon is black */
}

See this codepen (applying the color swap on hover): http://codepen.io/chrscblls/pen/bwAXZO

The infamous java.sql.SQLException: No suitable driver found

In my case I was working on a Java project with Maven and encountered this error. In your pom.xml file make sure you have this dependencies

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>
  </dependencies>

and where you create connection have something like this

public Connection createConnection() {
        try {
            String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
            String username = "root"; //your my sql username here
            String password = "1234"; //your mysql password here

            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

Git fast forward VS no fast forward merge

It is possible also that one may want to have personalized feature branches where code is just placed at the end of day. That permits to track development in finer detail.

I would not want to pollute master development with non-working code, thus doing --no-ff may just be what one is looking for.

As a side note, it may not be necessary to commit working code on a personalized branch, since history can be rewritten git rebase -i and forced on the server as long as nobody else is working on that same branch.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

Getting value from appsettings.json in .net core

Its simple: In appsettings.json

  "MyValues": {
    "Value1": "Xyz"
  }

In .cs file:

static IConfiguration conf = (new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build());
        public static string myValue1= conf["MyValues:Value1"].ToString();

Open Source Alternatives to Reflector?

Actually, I'm pretty sure Reflector is considered a disassembler with some decompiler functionality. Disassembler because it reads the bytes out of an assembly's file and converts it to an assembly language (ILasm in this case). The Decompiler functionality it provides by parsing the IL into well known patterns (like expressions and statements) which then get translated into higher level languages like C#, VB.Net, etc. The addin api for Reflector allows you to write your own language translator if you wish ... however the magic of how it parses the IL into the expression trees is a closely guarded secret.

I would recommend looking at any of the three things mentioned above if you want to understand how IL disassemblers work: Dile, CCI and Mono are all good sources for this stuff.

I also highly recommend getting the Ecma 335 spec and Serge Lidin's book too.

Spring 3 MVC accessing HttpRequest from controller

Spring MVC will give you the HttpRequest if you just add it to your controller method signature:

For instance:

/**
 * Generate a PDF report...
 */
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
        @PathVariable("objectId") Long objectId, 
        HttpServletRequest request, 
        HttpServletResponse response) {

    // ...
    // Here you can use the request and response objects like:
    // response.setContentType("application/pdf");
    // response.getOutputStream().write(...);

}

As you see, simply adding the HttpServletRequest and HttpServletResponse objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession object too.

EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.

I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.

CSS Inset Borders

You may use background-clip: border-box;

Example:

.example {
padding: 2em;
border: 10px solid rgba(51,153,0,0.65);
background-clip: border-box;
background-color: yellow;
}

<div class="example">Example with background-clip: border-box;</div>

undefined reference to 'vtable for class' constructor

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

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

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

What's the difference between the atomic and nonatomic attributes?

To simplify the entire confusion, let us understand mutex lock.

Mutex lock, as per the name, locks the mutability of the object. So if the object is accessed by a class, no other class can access the same object.

In iOS, @sychronise also provides the mutex lock .Now it serves in FIFO mode and ensures the flow is not affected by two classes sharing the same instance. However, if the task is on main thread, avoid accessing object using atomic properties as it may hold your UI and degrade the performance.

python error: no module named pylab

The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

Which mime type should I use for mp3

The standard way is to use audio/mpeg which is something like this in your PHP header function ...

header('Content-Type: audio/mpeg');

Convert Rtf to HTML

If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.

Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.

I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.

Align button to the right

try to put your script and link on the head like this:

<html>
  <head>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"> 
     </script>
  </head>
  <body>
     <div class="row">
        <h3 class="one">Text</h3>
        <button class="btn btn-secondary pull-right">Button</button>
     </div>
  </body>
</html>

"The given path's format is not supported."

Try changing:

Server.MapPath("/UploadBucket/Raw/")

to

Server.MapPath(@"\UploadBucket\Raw\")

CURL and HTTPS, "Cannot resolve host"

Just a note which may be helpful- I was having this trouble with Apache on my laptop (which connects by wifi AFTER startup), and restarting the server (after connect) fixed the issue. I guess in my case this may be to do with apache starting offline and perhaps there noting that DNS lookups fail?

System has not been booted with systemd as init system (PID 1). Can't operate

If you are using Docker, you may try an image that has Ubuntu with System D already active with this command:

docker run -d --name redis --privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro jrei/systemd-ubuntu:18.04

Then you just need to run:

docker exec -it redis /bin/bash

and there you can just install Redis, start it, restart it or whatever you need.

Create a SQL query to retrieve most recent records

Aggregate in a subquery derived table and then join to it.

 Select Date, User, Status, Notes 
    from [SOMETABLE]
    inner join 
    (
        Select max(Date) as LatestDate, [User]
        from [SOMETABLE]
        Group by User
    ) SubMax 
    on [SOMETABLE].Date = SubMax.LatestDate
    and [SOMETABLE].User = SubMax.User 

How to add image that is on my computer to a site in css or html?

No, Not if your website is on a remote server, i.e not on localhost.

Adding image to JFrame

There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:

  1. As @Reimeus said: Use a JLabel with an icon.
  2. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:

    JImageComponent ic = new JImageComponent(myImageGoesHere);
    imagePanel.add(ic);
    

    where JImageComponent is a self created class that extends JComponent that overrides the paintComponent() method to draw the image.

Getting permission denied (public key) on gitlab

Go to the terminal and regenerate the ssh key again. Type ssh-keygen. It will ask you where you want to save it, type the path.

Then copy the public key to gitlabs platform. It usually starts with ssh-rsa.

How to determine one year from now in Javascript

You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).

Thus a date marking exactly one year from the present moment would be:

var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);

Note that the date will be adjusted if you do that on February 29.

Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}