Programs & Examples On #Mu

How do I get the command-line for an Eclipse run configuration?

You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.

You will probably also need the .classpath file in the project directory that contains the test class.

Like the run configurations, they're XML files (even if they don't have an xml extension).

How much should a function trust another function

That's where constructors come into play. If you have a default constructor (eg. with no parameters) that always creates a new Map, then you're sure that every instance of this class will always have an already instantiated Map.

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

How to implement a simple scenario the OO way

The approach I would take is: when reading the chapters from the database, instead of a collection of chapters, use a collection of books. This will have your chapters organised into books and you'll be able to use information from both classes to present the information to the user (you can even present it in a hierarchical way easily when using this approach).

How to make a variable accessible outside a function?

$.getJSON is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.

Alternatively you could use jQuery's $.when/.then(), similar to this:

var input = "netuetamundis";  var sID;  $(document).ready(function () {     $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () {         obj = name;         sID = obj.id;         console.log(sID);     })).then(function () {         $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) {             console.log(stats);         });     }); }); 

This would be more open for future modification and separates out the responsibility for the first call to know about the second call.

The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.

Method Call Chaining; returning a pointer vs a reference?

It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

python variable NameError

I would approach it like this:

sizes = [100, 250] print "How much space should the random song list occupy?" print '\n'.join("{0}. {1}Mb".format(n, s)                 for n, s in enumerate(sizes, 1)) # present choices choice = int(raw_input("Enter choice:")) # throws error if not int size = sizes[0] # safe starting choice if choice in range(2, len(sizes) + 1):     size = sizes[choice - 1] # note index offset from choice print "You  want to create a random song list that is {0}Mb.".format(size) 

You could also loop until you get an acceptable answer and cover yourself in case of error:

choice = 0 while choice not in range(1, len(sizes) + 1): # loop     try: # guard against error         choice = int(raw_input(...))     except ValueError: # couldn't make an int         print "Please enter a number"         choice = 0 size = sizes[choice - 1] # now definitely valid 

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

When to create variables (memory management)

I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?

You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging '5' into the println method?

The JIT is smart enough to turn fields which don't change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

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

In my case:

I had 4 configurations(+ DebugQa and ReleaseQa) Cocoapods is used as a dependency Manager

For Debug, I gathered on the device and in the simulator, and on qa only on the device.

It helped to set BuildActiveArchitecture to yes in PodsProject

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

I have tested all the answers here but non of them worked for me. So I decided to change angular.js file. there is a aot option there which is true. then I altered that to the false and the error vanished!

"options": {
            "outputPath": "dist/DateMeUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false, // here you have to change
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },

However, I got that there is 'tsconfig.app.json' which I couldn't find that in my project(maybe you have to add this manually ) by this file you can set the "enableIvy": false as others mention to it. tsconfig.app.json

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

Just need to remove and re-install react-scripts

To Remove yarn remove react-scripts To Add yarn add react-scripts

and then rm -rf node_modules/ yarn.lock && yarn

  • Remember don't update the react-scripts version maually

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

How to resolve the error on 'react-native start'

I had the same problem I altered the E:\NodeJS\ReactNativeApp\ExpoTest\node_modules\metro-config\src\defaults\blacklist.js in my project

from

var sharedBlacklist = [
  /node_modules[/\\]react[/\\]dist[/\\].*/,
  /website\/node_modules\/.*/,
 /heapCapture\/bundle\.js/,
 /.*\/__tests__\/.*/
];

to

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

this worked perfectly for me

How to prevent Google Colab from disconnecting?

GNU Colab lets you run a standard persistent desktop environment on top of a Colaboratory instance.

Indeed it contains a mechanism to not let machines die of idling.

Here's a video demonstration.

dotnet ef not found in .NET Core 3

Run PowerShell or command prompt as Administrator and run below command.

dotnet tool install --global dotnet-ef --version 3.1.3

"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure." when plotting figure with pyplot on Pycharm

If you use Arch Linux (distributions like Manjaro or Antegros) simply type:

sudo pacman -S tk

And all will work perfectly!

How to style components using makeStyles and still have lifecycle methods in Material UI?

What we ended up doing is stopped using the class components and created Functional Components, using useEffect() from the Hooks API for lifecycle methods. This allows you to still use makeStyles() with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.

Example:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: theme.spacing(1)
  },
  highlight: {
    backgroundColor: 'red',
  }
}));

// Highlight is a bool
const Welcome = ({highlight}) => { 
  const [userName, setUserName] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  useEffect(() => {
    axios.get('example.com/api/username/12')
         .then(res => setUserName(res.userName));
  }, []);

  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
   </Container>
   );
  }
}

export default Welcome;

Why am I getting Unknown error in line 1 of pom.xml?

Add 3.1.1 in to properties like below than fix issue

<properties>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>

Just Update Project => right click => Maven=> Update Project

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

I have also faced this issue. I resolved this following step.

Check android sdk path in Environment Veritable.

Add ANDROID_HOME = C:\Users\user_name\AppData\Local\Android\Sdk in System Variable
and C:\Users\user_name\AppData\Local\Android\Sdk\platform-tools path in System Variable

replace sharedBlacklist as below code segment,

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

in node_modules/metro-config/src/default/blacklist.js

Then run npx react-native run-android --port 9001

Happy Coding..!

How to set value to form control in Reactive Forms in Angular

Use patchValue() method which helps to update even subset of controls.

setValue(){
  this.editqueForm.patchValue({user: this.question.user, questioning: this.question.questioning})
}


From Angular docs setValue() method:

Error When strict checks fail, such as setting the value of a control that doesn't exist or if you excluding the value of a control.

In your case, object missing options and questionType control value so setValue() will fail to update.

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You need to add an event, before call your handleFunction like this:

function SingInContainer() {
..
..
handleClose = () => {
}

return (
    <SnackBar
        open={open}
        handleClose={() => handleClose}
        variant={variant}
        message={message}
        />
    <SignInForm/>
)

}

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

for cordova developers having this issue

try to set

<preference name="deployment-target" value="8.0" />

in confix.xml

Flutter Countdown Timer

Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class

TweenAnimationBuilder<Duration>(
              duration: Duration(minutes: 3),
              tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
              onEnd: () {
                print('Timer ended');
              },
              builder: (BuildContext context, Duration value, Widget child) {
              final minutes = value.inMinutes;
              final seconds = value.inSeconds % 60;
              return Padding(
                     padding: const EdgeInsets.symmetric(vertical: 5),
                     child: Text('$minutes:$seconds',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                            fontSize: 30)));
              }),

and You also get onEnd call back which notifies you when the animation completes;

here's the output

WARNING in budgets, maximum exceeded for initial

Open angular.json file and find budgets keyword.

It should look like:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "2mb",
          "maximumError": "5mb"
       }
    ]

As you’ve probably guessed you can increase the maximumWarning value to prevent this warning, i.e.:

    "budgets": [
       {
          "type": "initial",
          "maximumWarning": "4mb", <===
          "maximumError": "5mb"
       }
    ]

What does budgets mean?

A performance budget is a group of limits to certain values that affect site performance, that may not be exceeded in the design and development of any web project.

In our case budget is the limit for bundle sizes.

See also:

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

This issue is due to incompatible of your plugin Verison and required Gradle version; they need to match with each other. I am sharing how my problem was solved.

plugin version Plugin version

Required Gradle version is here

Required gradle version

more compatibility you can see from here. Android Plugin for Gradle Release Notes

if you have the android studio version 4.0.1 android studio version

then your top level gradle file must be like this

buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:4.0.2'
    classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

and the gradle version should be

gradle version must be like this

and your app gradle look like this

app gradle file

Pandas Merging 101

A supplemental visual view of pd.concat([df0, df1], kwargs). Notice that, kwarg axis=0 or axis=1 's meaning is not as intuitive as df.mean() or df.apply(func)


on pd.concat([df0, df1])

Why do I keep getting Delete 'cr' [prettier/prettier]?

Add this to your .prettierrc file and open the VSCODE

"endOfLine": "auto"

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

How to compare oldValues and newValues on React Hooks useEffect?

You can write a custom hook to provide you a previous props using useRef

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

and then use it in useEffect

const Component = (props) => {
    const {receiveAmount, sendAmount } = props
    const prevAmount = usePrevious({receiveAmount, sendAmount});
    useEffect(() => {
        if(prevAmount.receiveAmount !== receiveAmount) {

         // process here
        }
        if(prevAmount.sendAmount !== sendAmount) {

         // process here
        }
    }, [receiveAmount, sendAmount])
}

However its clearer and probably better and clearer to read and understand if you use two useEffect separately for each change id you want to process them separately

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Until React provides a better way, you can create a helper, useEffectAsync.js:

import { useEffect } from 'react';


export default function useEffectAsync(effect, inputs) {
    useEffect(() => {
        effect();
    }, inputs);
}

Now you can pass an async function:

useEffectAsync(async () => {
    const items = await fetchSomeItems();
    console.log(items);
}, []);

Update

If you choose this approach, note that it's bad form. I resort to this when I know it's safe, but it's always bad form and haphazard.

Suspense for Data Fetching, which is still experimental, will solve some of the cases.

In other cases, you can model the async results as events so that you can add or remove a listener based on the component life cycle.

Or you can model the async results as an Observable so that you can subscribe and unsubscribe based on the component life cycle.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

From Xcode 12.2, you need to remove the $(VALID_ARCHS) build setting from your main and CocoaPods targets, and use $(ARCHS_STANDARD) for all targets. Also, switching to the Legacy Build System is no longer a good solution, since Xcode will deprecate this in a future release. Clear derived data after applying these changes, and before a new rebuild.

Flutter: RenderBox was not laid out

I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.

Expanded(child:MyListView())

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

Xcode 10, Command CodeSign failed with a nonzero exit code

May sound stupid, but, try with no password, when it asked.

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

You can simply run sudo service docker start which will start running your docker server. You can check if you have the docker server by running service --status-all, you should see docker listed.

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

Can I use library that used android support with Androidx projects.

I used these two lines of code in application tag in manifest.xml and it worked.

 tools:replace="android:appComponentFactory"    
 android:appComponentFactory="whateverString"

Source: https://github.com/android/android-ktx/issues/576#issuecomment-437145192

Flutter plugin not installed error;. When running flutter doctor

I met similar error after updating android studio, turns out I need to update the existing flutter plugin.

To fix it, go to android studio → preferences → plugins → installed → update your installed flutter plugin

Android Material and appcompat Manifest merger failed

just add these two lines of code to your Manifest file

tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"

standard_init_linux.go:190: exec user process caused "no such file or directory" - Docker

Replacing CRLF with LF using Notepad++

  1. Notepad++'s Find/Replace feature handles this requirement quite nicely. Simply bring up the Replace dialogue (CTRL+H), select Extended search mode (ALT+X), search for “\r\n” and replace with “\n”:
  2. Hit Replace All (ALT+A)

Rebuild and run the docker image should solve your problem.

Google Recaptcha v3 example demo

I thought a fully-functioning reCaptcha v3 example demo in PHP, using a Bootstrap 4 form, might be useful to some.

Reference the shown dependencies, swap in your email address and keys (create your own keys here), and the form is ready to test and use. I made code comments to better clarify the logic and also included commented-out console log and print_r lines to quickly enable viewing the validation token and data generated from Google.

The included jQuery function is optional, though it does create a much better user prompt experience in this demo.


PHP file (mail.php):

Add secret key (2 places) and email address where noted.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  # BEGIN Setting reCaptcha v3 validation data
  $url = "https://www.google.com/recaptcha/api/siteverify";
  $data = [
    'secret' => "your-secret-key-here",
    'response' => $_POST['token'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
  ];

  $options = array(
    'http' => array(
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    )
    );
  
  # Creates and returns stream context with options supplied in options preset 
  $context  = stream_context_create($options);
  # file_get_contents() is the preferred way to read the contents of a file into a string
  $response = file_get_contents($url, false, $context);
  # Takes a JSON encoded string and converts it into a PHP variable
  $res = json_decode($response, true);
  # END setting reCaptcha v3 validation data
   
    // print_r($response); 
# Post form OR output alert and bypass post if false. NOTE: score conditional is optional
# since the successful score default is set at >= 0.5 by Google. Some developers want to
# be able to control score result conditions, so I included that in this example.

  if ($res['success'] == true && $res['score'] >= 0.5) {
 
    # Recipient email
    $mail_to = "[email protected]";
    
    # Sender form data
    $subject = trim($_POST["subject"]);
    $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $phone = trim($_POST["phone"]);
    $message = trim($_POST["message"]);
    
    if (empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
      # Set a 400 (bad request) response code and exit
      http_response_code(400);
      echo '<p class="alert-warning">Please complete the form and try again.</p>';
      exit;
    }

    # Mail content
    $content = "Name: $name\n";
    $content .= "Email: $email\n\n";
    $content .= "Phone: $phone\n";
    $content .= "Message:\n$message\n";

    # Email headers
    $headers = "From: $name <$email>";

    # Send the email
    $success = mail($mail_to, $subject, $content, $headers);
    
    if ($success) {
      # Set a 200 (okay) response code
      http_response_code(200);
      echo '<p class="alert alert-success">Thank You! Your message has been successfully sent.</p>';
    } else {
      # Set a 500 (internal server error) response code
      http_response_code(500);
      echo '<p class="alert alert-warning">Something went wrong, your message could not be sent.</p>';
    }   

  } else {

    echo '<div class="alert alert-danger">
        Error! The security token has expired or you are a bot.
       </div>';
  }  

} else {
  # Not a POST request, set a 403 (forbidden) response code
  http_response_code(403);
  echo '<p class="alert-warning">There was a problem with your submission, please try again.</p>';
} ?>

HTML <head>

Bootstrap CSS dependency and reCaptcha client-side validation Place between <head> tags - paste your own site-key where noted.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://www.google.com/recaptcha/api.js?render=your-site-key-here"></script>

HTML <body>

Place between <body> tags.

<!-- contact form demo container -->
<section style="margin: 50px 20px;">
  <div style="max-width: 768px; margin: auto;">
    
    <!-- contact form -->
    <div class="card">
      <h2 class="card-header">Contact Form</h2>
      <div class="card-body">
        <form class="contact_form" method="post" action="mail.php">

          <!-- form fields -->
          <div class="row">
            <div class="col-md-6 form-group">
              <input name="name" type="text" class="form-control" placeholder="Name" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="email" type="email" class="form-control" placeholder="Email" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="phone" type="text" class="form-control" placeholder="Phone" required>
            </div>
            <div class="col-md-6 form-group">
              <input name="subject" type="text" class="form-control" placeholder="Subject" required>
            </div>
            <div class="col-12 form-group">
              <textarea name="message" class="form-control" rows="5" placeholder="Message" required></textarea>
            </div>

            <!-- form message prompt -->
            <div class="row">
              <div class="col-12">
                <div class="contact_msg" style="display: none">
                  <p>Your message was sent.</p>
                </div>
              </div>
            </div>

            <div class="col-12">
              <input type="submit" value="Submit Form" class="btn btn-success" name="post">
            </div>

            <!-- hidden reCaptcha token input -->
            <input type="hidden" id="token" name="token">
          </div>

        </form>
      </div>
    </div>

  </div>
</section>
<script>
  grecaptcha.ready(function() {
    grecaptcha.execute('your-site-key-here', {action: 'homepage'}).then(function(token) {
       // console.log(token);
       document.getElementById("token").value = token;
    });
    // refresh token every minute to prevent expiration
    setInterval(function(){
      grecaptcha.execute('your-site-key-here', {action: 'homepage'}).then(function(token) {
        console.log( 'refreshed token:', token );
        document.getElementById("token").value = token;
      });
    }, 60000);

  });
</script>

<!-- References for the optional jQuery function to enhance end-user prompts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="form.js"></script>

Optional jQuery function for enhanced UX (form.js):

(function ($) {
'use strict';

var form = $('.contact_form'),
  message = $('.contact_msg'),
  form_data;

// Success function
function done_func(response) {
  message.fadeIn()
  message.html(response);
  setTimeout(function () {
    message.fadeOut();
  }, 10000);
  form.find('input:not([type="submit"]), textarea').val('');
}

// fail function
function fail_func(data) {
  message.fadeIn()
  message.html(data.responseText);
  setTimeout(function () {
    message.fadeOut();
  }, 10000);
}

form.submit(function (e) {
  e.preventDefault();
  form_data = $(this).serialize();
  $.ajax({
    type: 'POST',
    url: form.attr('action'),
    data: form_data
  })
  .done(done_func)
  .fail(fail_func);
}); })(jQuery);

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

How do I install the Nuget provider for PowerShell on a unconnected machine so I can install a nuget package from the PS command line?

MSDocs state this for your scenario:

In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:

  1. Run Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force to install the provider from a computer with an internet connection.

  2. After the install, you can find the provider installed in $env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\> or $env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>.

  3. Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.

  4. Restart PowerShell to auto-load the package provider. Alternatively, run Get-PackageProvider -ListAvailable to list all the package providers available on the computer. Then use Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 to import the provider to the current Windows PowerShell session.

How to resolve TypeError: can only concatenate str (not "int") to str

Use this:

print("Program for calculating sum")
numbers=[1, 2, 3, 4, 5, 6, 7, 8]
sum=0
for number in numbers:
    sum += number
print("Total Sum is: %d" %sum )

ADB.exe is obsolete and has serious performance problems

First you need to check which SDK your Emulator is using and as @kuya suggested you need to follow those steps and install the latest version of that SDK Build Tool. Suppose your Emulator uses SDK 27 then you need to install latest in that series. For me it was 27.0.3. After that the error was gone.

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

The problem is that you are using gulp 4 and the syntax in gulfile.js is of gulp 3. So either downgrade your gulp to 3.x.x or make use of gulp 4 syntaxes.

Syntax Gulp 3:

gulp.task('default', ['sass'], function() {....} );

Syntax Gulp 4:

gulp.task('default', gulp.series(sass), function() {....} );

You can read more about gulp and gulp tasks on: https://medium.com/@sudoanushil/how-to-write-gulp-tasks-ce1b1b7a7e81

Flask at first run: Do not use the development server in a production environment

Unless you tell the development server that it's running in development mode, it will assume you're using it in production and warn you not to. The development server is not intended for use in production. It is not designed to be particularly efficient, stable, or secure.

Enable development mode by setting the FLASK_ENV environment variable to development.

$ export FLASK_APP=example
$ export FLASK_ENV=development
$ flask run

If you're running in PyCharm (or probably any other IDE) you can set environment variables in the run configuration.

Development mode enables the debugger and reloader by default. If you don't want these, pass --no-debugger or --no-reloader to the run command.


That warning is just a warning though, it's not an error preventing your app from running. If your app isn't working, there's something else wrong with your code.

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Using Environment Variables with Vue.js

In the root of your project create your environment files:

  • .env
  • .env.someEnvironment1
  • .env.SomeEnvironment2

To then load those configs, you would specify the environment via mode i.e.

npm run serve --mode development //default mode
npm run serve --mode someEnvironment1

In your env files you simply declare the config as key-value pairs, but if you're using vue 3, you must prefix with VUE_APP_:

In your .env:

VUE_APP_TITLE=This will get overwritten if more specific available

.env.someEnvironment1:

VUE_APP_TITLE=My App (someEnvironment1)

You can then use this in any of your components via:

myComponent.vue:

<template>
  <div> 
    {{title}}
  </div>
</template>

<script>
export default {
  name: "MyComponent",
  data() {
    return {
      title: process.env.VUE_APP_TITLE
    };
  }
};
</script>

Now if you ran the app without a mode it will show the 'This will get...' but if you specify a someEnvironment1 as your mode then you will get the title from there.

You can create configs that are 'hidden' from git by appending .local to your file: .env.someEnvironment1.local - very useful for when you have secrets.

Read the docs for more info.

Xcode 10 Error: Multiple commands produce

If you develop private cocoapod, and had already added it via Podfile,

remove it from Embedded Binaries section:

Embedded Binaries in test app

Trying to merge 2 dataframes but get ValueError

At first check the type of columns which you want to merge. You will see one of them is string where other one is int. Then convert it to int as following code:

df["something"] = df["something"].astype(int)

merged = df.merge[df1, on="something"]

How to install OpenSSL in windows 10?

Check openssl tool which is a collection of Openssl from the LibreSSL project and Cygwin libraries (2.5 MB). NB! We're the packager.

One liner to create a self signed certificate:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt

Python Pandas User Warning: Sorting because non-concatenation axis is not aligned

tl;dr:

concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.


The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 
                    columns=['c','b','a','d'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)
                                                       .sort_index()

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

In your AndroidManifest.xml add this two-line.

android:usesCleartextTraffic="true"  
<uses-library android:name="org.apache.http.legacy" android:required="false"/>

See this below code

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name=".activity.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    </application>

How to do a timer in Angular 5

This may be overkill for what you're looking for, but there is an npm package called marky that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer. You just need to install it via npm and then import the dependency anywhere you'd like to use it. Here is a link to the npm package: https://www.npmjs.com/package/marky

An example of use after installing via npm would be as follows:

import * as _M from 'marky';

@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: ['./test.component.scss']
})

export class TestComponent implements OnInit {
 Marky = _M;
}

constructor() {}

ngOnInit() {}

startTimer(key: string) {
 this.Marky.mark(key);
}

stopTimer(key: string) {
 this.Marky.stop(key);
}

key is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.

Iterating through a list to render multiple widgets in Flutter?

All you need to do is put it in a list and then add it as the children of the widget.

you can do something like this:

Widget listOfWidgets(List<String> item) {
  List<Widget> list = List<Widget>();
  for (var i = 0; i < item.length; i++) {
    list.add(Container(
        child: FittedBox(
          fit: BoxFit.fitWidth,
          child: Text(
            item[i],
          ),
        )));
  }
  return Wrap(
      spacing: 5.0, // gap between adjacent chips
      runSpacing: 2.0, // gap between lines
      children: list);
}

After that call like this

child: Row(children: <Widget>[
   listOfWidgets(itemList),
])

enter image description here

HTTP POST with Json on Body - Flutter/Dart

This works!

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

Future<http.Response> postRequest () async {
  var url ='https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';

  Map data = {
    'apikey': '12345678901234567890'
  }
  //encode Map to JSON
  var body = json.encode(data);

  var response = await http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body
  );
  print("${response.statusCode}");
  print("${response.body}");
  return response;
}

Can't bind to 'dataSource' since it isn't a known property of 'table'

Material example is using the wrong table tags. Change

<table mat-table></table>
<th mat-header-cell></th>
<td mat-cell></td>

<tr mat-header-row></tr>
<tr mat-row></tr>

to

<mat-table></mat-table>
<mat-header-cell></mat-header-cell>
<mat-cell></mat-cell>

<mat-header-row></<mat-header-row>
<mat-row></<mat-row>

How to set environment via `ng serve` in Angular 6

Angular no longer supports --env instead you have to use

ng serve -c dev

for development environment and,

ng serve -c prod 

for production.

NOTE: -c or --configuration

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

If you are using docker, it worked for me!

in the docker-compose.yml add the following lines:

mysql:
   ...    
   command: --default-authentication-plugin=mysql_native_password
   restart: always

after that, down the container and up again.

phpMyAdmin on MySQL 8.0

As @kgr mentioned, MySQL 8.0.11 made some changes to the authentication method.

I've opened a phpMyAdmin bug report about this: https://github.com/phpmyadmin/phpmyadmin/issues/14220.

MySQL 8.0.4-rc was working fine for me, and I kind of think it's ridiculous for MySQL to make such a change in a patch level release.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

Might have todo with one of these:

  1. Install a newer SDK.
  2. In .csproj check for Reference Include="netstandard"
  3. Check the assembly versions in the compilation tags in the Views\Web.config and Web.config.

Adding an .env file to React Project

  1. Install dotenv as devDependencies:
npm i --save-dev dotenv
  1. Create a .env file in the root directory:
my-react-app/
|- node-modules/
|- public/
|- src/
|- .env
|- .gitignore
|- package.json
|- package.lock.json.
|- README.md
  1. Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name.
REACT_APP_BASE_URL=http://localhost:8000
REACT_APP_API_KEY=YOUR-API-KEY
  1. [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file.

For example, I've create a file named base.js and update it like below:

export const BASE_URL = process.env.REACT_APP_BASE_URL;
export const API_KEY = process.env.REACT_APP_API_KEY;
  1. Or you can simply just call the environment variable in your JS file in the following way:
process.env.REACT_APP_BASE_URL

Default interface methods are only supported starting with Android N

This also happened to me but using Dynamic Features. I already had Java 8 compatibility enabled in the app module but I had to add this compatibility lines to the Dynamic Feature module and then it worked.

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

I had the SAME issue today and it was driving me nuts!!! What I had done was upgrade to node 8.10 and upgrade my NPM to the latest I uninstalled angular CLI

npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli

I then verified my Cache from NPM if it wasn't up to date I cleaned it and ran the install again if npm version is < 5 then use npm cache clean --force

npm install -g @angular/cli@latest

and created a new project file and create a new angular project.

Getting "TypeError: failed to fetch" when the request hasn't actually failed

Note that there is an unrelated issue in your code but that could bite you later: you should return res.json() or you will not catch any error occurring in JSON parsing or your own function processing data.

Back to your error: You cannot have a TypeError: failed to fetch with a successful request. You probably have another request (check your "network" panel to see all of them) that breaks and causes this error to be logged. Also, maybe check "Preserve log" to be sure the panel is not cleared by any indelicate redirection. Sometimes I happen to have a persistent "console" panel, and a cleared "network" panel that leads me to have error in console which is actually unrelated to the visible requests. You should check that.

Or you (but that would be vicious) actually have a hardcoded console.log('TypeError: failed to fetch') in your final .catch ;) and the error is in reality in your .then() but it's hard to believe.

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

How to set bot's status

    client.user.setStatus('dnd', 'Made by KwinkyWolf') 

And change 'dnd' to whatever status you want it to have. And then the next field 'Made by KwinkyWolf' is where you change the game. Hope this helped :)

List of status':

  • online
  • idle
  • dnd
  • invisible

Not sure if they're still the same, or if there's more but hope that helped too :)

How to set up devices for VS Code for a Flutter emulator

you can use 'Android iOS Emulator' plugin and Add the Android Studio emulator script to your settings in Visual Studio Code:

Mac: emulator.emulatorPath": "~/Library/Android/sdk/tools/emulator

Windows: emulator.emulatorPath": "<your android home>\\Sdk\\emulator\\emulator.exe

Linux: emulator.emulatorPath": "~/Documents/SDK/tools

Your visual studio code settings are found here: File -> Preferences -> Setting -> User Setting -> Extensions -> Emulator Configuration. Open command pallete Cmd-Shift-P -> Type Emulator

How to clear Flutter's Build cache?

I tried flutter clean and that didn't work for me. Then I went to wipe the emulator's data and voila, the cached issue was gone. If you have Android Studio you can launch the AVD Manager by following this Create and Manage virtual machine. Otherwise you can wipe the emulator's data using the emulator.exe command line that's included in the android SDK. Simply follow this instructions here Start the emulator from the command line.

error: resource android:attr/fontVariationSettings not found

This is caused by an incompatibility with the android support library that changed to version 28. I solved the problem by forcing the build to use a lower support library. //like build gradle

configurations.all {
        resolutionStrategy {
                force 'com.android.support:support-v4:27.1.0'
    }
} 

My project built successfully immediately after I changed this. Hope this might help you too. I lost a day of development because of this!.

How to remove the Flutter debug banner?

You can give simply hide this by giving a boolean parameter-----> debugShowCheckedModeBanner: false,

void main() {
  Bloc.observer = SimpleBlocDelegate();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Prescription Writing Software',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.white,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: SplashScreen(),
    );
  }
}

Dart SDK is not configured

Perhaps you can try to sync up the dependencies by executing 'flutter pub get' in terminal.

How do I deal with installing peer dependencies in Angular CLI?

NPM package libraries have a section in the package.json file named peerDependencies. For example; a library built in Angular 8, will usually list Angular 8 as a dependency. This is a true dependency for anyone running less than version 8. But for anyone running version 8, 9 or 10, it's questionable whether any concern should be pursued.

I have been safely ignoring these messages on Angular Updates, but then again we do have Unit and Cypress Tests!

Docker error: invalid reference format: repository name must be lowercase

Let me emphasise that Docker doesn't even allow mixed characters.

Good: docker build -t myfirstechoimage:0.1 .

Bad: docker build -t myFirstEchoImage:0.1 .

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Check C:\Users\User path. Change User directory name (may be something different name) from your alphabet to English alphabet. Warning: it is dangerous operation, learn it before changing. Android Studio can not access to AVD throw users\Your alphabet name\.android.

ReactJS: Maximum update depth exceeded error

In this case , this code

{<td><span onClick={this.toggle()}>Details</span></td>}

causes toggle function to call immediately and re render it again and again thus making infinite calls.

so passing only the reference to that toggle method will solve the problem.

so ,

{<td><span onClick={this.toggle}>Details</span></td>}

will be the solution code.

If you want to use the () , you should use an arrow function like this

{<td><span onClick={()=> this.toggle()}>Details</span></td>}

In case you want to pass parameters you should choose the last option and you can pass parameters like this

{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}

In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.

Bootstrap 4: responsive sidebar menu to top navbar

It could be done in Bootstrap 4 using the responsive grid columns. One column for the sidebar and one for the main content.

Bootstrap 4 Sidebar switch to Top Navbar on mobile

<div class="container-fluid h-100">
    <div class="row h-100">
        <aside class="col-12 col-md-2 p-0 bg-dark">
            <nav class="navbar navbar-expand navbar-dark bg-dark flex-md-column flex-row align-items-start">
                <div class="collapse navbar-collapse">
                    <ul class="flex-md-column flex-row navbar-nav w-100 justify-content-between">
                        <li class="nav-item">
                            <a class="nav-link pl-0" href="#">Link</a>
                        </li>
                        ..
                    </ul>
                </div>
            </nav>
        </aside>
        <main class="col">
            ..
        </main>
    </div>
</div>

Alternate sidebar to top
Fixed sidebar to top

For the reverse (Top Navbar that becomes a Sidebar), can be done like this example

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

It is located on the Android Studio folder itself, on where you installed it.

enter image description here

Changing directory in Google colab (breaking out of the python interpreter)

!pwd
import os
os.chdir('/content/drive/My Drive/Colab Notebooks/Data')
!pwd

view this answer for detailed explaination https://stackoverflow.com/a/61636734/11535267

Issue in installing php7.2-mcrypt

@praneeth-nidarshan has covered mostly all the steps, except some:

  • Check if you have pear installed (or install):

$ sudo apt-get install php-pear

  • Install, if isn't already installed, php7.2-dev, in order to avoid the error:

sh: phpize: not found

ERROR: `phpize’ failed

$ sudo apt-get install php7.2-dev

  • Install mcrypt using pecl:

$ sudo pecl install mcrypt-1.0.1

  • Add the extention extension=mcrypt.so to your php.ini configuration file; if you don't know where it is, search with:

$ sudo php -i | grep 'Configuration File'

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Failed to start mongod.service: Unit mongod.service not found

I just encountered this on my parrot os and this is how I solved it.

sudo service mongodb start

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

As @COLDSPEED so eloquently pointed out the error explicitly tells you to install xlrd.

pip install xlrd

And you will be good to go.

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true
    }

    Or for VS 2017:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
    }
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"

pip3: command not found

Writing the whole path/directory eg. (for windows) C:\Programs\Python\Python36-32\Scripts\pip3.exe install mypackage. This worked well for me when I had trouble with pip.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Work for me.. Ubuntu 18.04

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

Find for count($analyzed_sql_results['select_expr'] code on file. You can get this at line ~613.

|| (count($analyzed_sql_results['select_expr'] == 1)

Just replace with code :

|| ((count($analyzed_sql_results['select_expr']) == 1)

Save the file and reload PhpMyAdmin.

Done!!!

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I was running into this issue and it turned out that I needed to do this:

docker run ${image_name} bash -c "${command}"

Hope that helps someone who finds this error.

How to shift a block of code left/right by one space in VSCode?

Recent versions of VSCode (e.g., Version 1.29 at the time of posting this answer) allow you to change the Tab/Space size to 1 (or any number between 1 and 8). You may change the Tab/Space size from the bottom-right corner as shown in the below image:

Change Tab/Space size

Click on Spaces:4. Then, select Indent Using Spaces or Indent Using Tabs and choose the size 1.

Hope it helps.

What is the use of verbose in Keras while validating the model?

Check documentation for model.fit here.

By setting verbose 0, 1 or 2 you just say how do you want to 'see' the training progress for each epoch.

verbose=0 will show you nothing (silent)

verbose=1 will show you an animated progress bar like this:

progres_bar

verbose=2 will just mention the number of epoch like this:

enter image description here

React Native version mismatch

I've never seen this error before, but whenever I can't get Xcode and React-Native to play well together, I do a couple of things. Check what version of Xcode I'm working with. If it needs to be updated, I update it. Then clearing watchman and the cache are the second place I go. I don't use the reset cache command. It always says that I need to verify the cache, so I skip that (you can do it though, I just get confused). I use rm -rf $TMPDIR/react-* to get rid of any cached builds. If that doesn't work, I try to build the app in Xcode, then work my way from there, to build it with react-native run-ios. With this error message, it seems you might start by trying to build it with Xcode. Hope that helps...let me know your progress with it. Good luck! (Also, you could update to RN 0.51 as another attempt to get your versions synced.)

Android Studio AVD - Emulator: Process finished with exit code 1

None of the solutions worked for me. I ended up downloading a different emulator image.

First I had arm64-v8a, which was giving this error. I download armeabi-v7a, which worked fine.

Unfortunately I was not able to install HAXM accelerator as organization's softwares were blocking the installation. Hence, had to go with arm.

Android Studio Emulator and "Process finished with exit code 0"

I solved this issue by offing all of advantage features of my graphics card in its settings(Nvidaa type). It started to throw such hanging error less a lot. But finally I found a simplier way: In avd manager you need to put less resolution for the avd. Say, 400x800. Then I reenabled graphics card features again and now it runs all ok. (I suspect my graphics card or cpu are weaker than needed. )

axios post request to send form data

Using application/x-www-form-urlencoded format in axios

By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

Browser

In a browser, you can use the URLSearchParams API as follows:

const params = new URLSearchParams();

params.append('param1', 'value1');

params.append('param2', 'value2');

axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment).

Alternatively, you can encode data using the qs library:

const qs = require('qs');

axios.post('/foo', qs.stringify({ 'bar': 123 }));

Or in another way (ES6),

import qs from 'qs';

const data = { 'bar': 123 };

const options = {

method: 'POST',

headers: { 'content-type': 'application/x-www-form-urlencoded' },

data: qs.stringify(data),

url, };

axios(options);

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.

Credits goes to @JeroenMostert for giving me the solution.

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

In my case, this error occur when i tried to use gridView

I resolved it by removing this line from build.grade(Module) file

implementation 'com.android.support:gridlayout-v7:28.0.0-alpha3'

How can I fix "Design editor is unavailable until a successful build" error?

Go online before starting android studio. Then go file->New project Follow onscreen steps. Then wait It will download the necessary files over internet. And that should fix it.

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

The most upvoted answer is not implementing a real slide in/out (or down/up), as:

  1. It's not doing a soft transition on the height attribute. At time zero the element already has the 100% of its height producing a sudden glitch on the elements below it.
  2. When sliding out/up, the element does a translateY(-100%) and then suddenly disappears, causing another glitch on the elements below it.

You can implement a slide in and slide out like so:

my-component.ts

import { animate, style, transition, trigger } from '@angular/animations';

@Component({
  ...
  animations: [
    trigger('slideDownUp', [
      transition(':enter', [style({ height: 0 }), animate(500)]),
      transition(':leave', [animate(500, style({ height: 0 }))]),
    ]),
  ],
})

my-component.html

<div @slideDownUp *ngIf="isShowing" class="box">
  I am the content of the div!
</div>

my-component.scss

.box {
  overflow: hidden;
}

No provider for HttpClient

I was facing the same problem, then in my app.module.ts I updated the file this way,

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

and in the same file (app.module.ts) in my @NgModule imports[]array I wrote this way,

HttpModule,
HttpClientModule

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Many times as API's are updated. We forgot to update SDK Managers. For accessing recent API's one should always have highest API Level updated if possible should also have other regularly used lower level APIs to accommodate backward compatibility.
Go to build.gradle (module.app) file change compileSdkVersion buildToolsVersion targetSdkVersion, all should have the highest level of API.

Angular 4 checkbox change value

Inside your component class:

checkValue(event: any) {
  this.userForm.patchValue({
    state: event
  })
}

Now in controls you have value A or B

Import data into Google Colaboratory

This allows you to upload your files through Google Drive.

Run the below code (found this somewhere previously but I can't find the source again - credits to whoever wrote it!):

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass

!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

Click on the first link that comes up which will prompt you to sign in to Google; after that another will appear which will ask for permission to access to your Google Drive.

Then, run this which creates a directory named 'drive', and links your Google Drive to it:

!mkdir -p drive
!google-drive-ocamlfuse drive

If you do a !ls now, there will be a directory drive, and if you do a !ls drive you can see all the contents of your Google Drive.

So for example, if I save my file called abc.txt in a folder called ColabNotebooks in my Google Drive, I can now access it via a path drive/ColabNotebooks/abc.txt

How to solve npm install throwing fsevents warning on non-MAC OS?

If you want to hide this warn, you just need to install fsevents as a optional dependency. Just execute:

npm i fsevents@latest -f --save-optional

..And the warn will no longer be a bother.

How to clear react-native cache?

I went into this issue today, too. The cause was kinda silly -- vscode auto imported something from express-validator and caused the bug.

Just mentioning this in case anyone has done all the steps to clear cache/ delete modules or what not.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

Action Definition

const selectSlice = () => {
  return {
    type: 'SELECT_SLICE'
  }
};

Action Dispatch

store.dispatch({
  type:'SELECT_SLICE'
});

Make sure the object structure of action defined is same as action dispatched. In my case, while dispatching action, type was not assigned to property type.

How to use Angular4 to set focus by element id

One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:

const element = this.renderer.selectRootElement('#input1');

// setTimeout(() => element.focus, 0);
setTimeout(() => element.focus(), 0);

Thank you @MrBlaise for the solution!

mat-form-field must contain a MatFormFieldControl

I had the module imported and directive set and after executing 'ng add @angular/material' again it started working. Maybe it would be enough just to restart app with 'ng serve'

Is it safe to clean docker/overlay2/

I had this issue... It was the log that was huge. Logs are here :

/var/lib/docker/containers/<container id>/<container id>-json.log

You can manage this in the run command line or in the compose file. See there : Configure logging drivers

I personally added these 3 lines to my docker-compose.yml file :

my_container:
  logging:
    options:
      max-size: 10m

How do I post form data with fetch api?

Client

Do not set the content-type header.

// Build formData object.
let formData = new FormData();
formData.append('name', 'John');
formData.append('password', 'John123');

fetch("api/SampleData",
    {
        body: formData,
        method: "post"
    });

Server

Use the FromForm attribute to specify that binding source is form data.

[Route("api/[controller]")]
public class SampleDataController : Controller
{
    [HttpPost]
    public IActionResult Create([FromForm]UserDto dto)
    {
        return Ok();
    }
}

public class UserDto
{
    public string Name { get; set; }
    public string Password { get; set; }
}

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

How to use switch statement inside a React component?

You can do something like this.

 <div>
          { object.map((item, index) => this.getComponent(item, index)) }
 </div>

getComponent(item, index) {
    switch (item.type) {
      case '1':
        return <Comp1/>
      case '2':
        return <Comp2/>
      case '3':
        return <Comp3 />
    }
  }

ERROR in ./node_modules/css-loader?

My case:

Missing node-sass in package.json

Solution:

  1. npm i --save node-sass@latest
  2. remove node-modules folder
  3. npm i
  4. check "@angular-devkit/build-angular": "^0.901.0" version in package.json

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.

df[cat]=df[cat].astype('category')

And then check df.dtypes and perform label encoding.

Automatically set appsettings.json for dev and release environments in asp.net core?

  1. Create multiple appSettings.$(Configuration).json files like:

    • appSettings.staging.json
    • appSettings.production.json
  2. Create a pre-build event on the project which copies the respective file to appSettings.json:

    copy appSettings.$(Configuration).json appSettings.json
    
  3. Use only appSettings.json in your Config Builder:

    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
    
    Configuration = builder.Build();
    

Xcode 9 Swift Language Version (SWIFT_VERSION)

In my case, all warn disappeared after I directly changed swift version from 2.x to 4.0 in build settings except two warn.

These warning related to myprojectnameTests and myprojectnameUITests folder. I didn't notice and I thought its relate to direct immigration from Xcode 7 to Xcode 9 and I thought I couldn't solve this problem and I should install missed Xcode 8 version.

In my case, I deleted these folders and all warns disappeared, but you can recreate this folder and contains using this:

file > new > target > (uitest or unittest extensions)

and use this article for create test cases: https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/testing_with_xcode/chapters/04-writing_tests.html

How do I use Safe Area Layout programmatically?

SafeAreaLayoutGuide is UIView property,

The top of the safeAreaLayoutGuide indicates the unobscured top edge of the view (e.g, not behind the status bar or navigation bar, if present). Similarly for the other edges.

Use safeAreaLayoutGuide for avoid our objects clipping/overlapping from rounded corners, navigation bars, tab bars, toolbars, and other ancestor views.

We can create safeAreaLayoutGuide object & set object constraints respectively.

Constraints for Portrait + Landscape is -

Portrait image

Landscape image

        self.edgesForExtendedLayout = []//Optional our as per your view ladder

        let newView = UIView()
        newView.backgroundColor = .red
        self.view.addSubview(newView)
        newView.translatesAutoresizingMaskIntoConstraints = false
        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            newView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
            newView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
            newView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
            newView.heightAnchor.constraint(equalToConstant: 100).isActive = true

        }
        else {
            NSLayoutConstraint(item: newView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: newView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: newView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true

            newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
        }

UILayoutGuide

safeAreaLayoutGuide

Unable to merge dex

This hasn't been shared here yet so hopefully it can help someone.

Following this link solved the same issue for me.

To begin, I'll note that I did not have to set multiDexEnabled to true.

First I set dependencies in my pubspec.yaml to

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^0.8.2 

and ran flutter packages get in my IDE's terminal.

Also I had to change the minimum target SDK version:

  1. Open android/app/build.gradle, then find the line that says minSdkVersion 16.
  2. Change that line to minSdkVersion 21.
  3. Save the file.

This alone may fix your problem; however I had to also do the following because some of my dependency versions were mismatched.

I had to open android/app/build.gradle, then add the following line as the last line in the file: apply plugin: 'com.google.gms.google-services'

Next, I had to open android/build.gradle, then inside the buildscript tag, add a new dependency:

buildscript {
   repositories {
       // ...
   }

   dependencies {
       // ...
       classpath 'com.google.gms:google-services:3.2.1'   // new
   }
}

After this my app finally ran on the android emulator.

The link has a more complete walkthrough if you get stuck.

Also, to note, I did not have to set multiDexEnabled to true.

Change arrow colors in Bootstraps carousel

I hope this works, cheers.

_x000D_
_x000D_
.carousel-control-prev-icon,_x000D_
.carousel-control-next-icon {_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  outline: black;_x000D_
  background-size: 100%, 100%;_x000D_
  border-radius: 50%;_x000D_
  border: 1px solid black;_x000D_
  background-image: none;_x000D_
}_x000D_
_x000D_
.carousel-control-next-icon:after_x000D_
{_x000D_
  content: '>';_x000D_
  font-size: 55px;_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
.carousel-control-prev-icon:after {_x000D_
  content: '<';_x000D_
  font-size: 55px;_x000D_
  color: red;_x000D_
}
_x000D_
_x000D_
_x000D_

Cordova app not displaying correctly on iPhone X (Simulator)

Fix for iPhone X/XS screen rotation issue

On iPhone X/XS, a screen rotation will cause the header bar height to use an incorrect value, because the calculation of safe-area-inset-* was not reflecting the new values in time for UI refresh. This bug exists in UIWebView even in the latest iOS 12. A workaround is inserting a 1px top margin and then quickly reversing it, which will trigger safe-area-inset-* to be re-calculated immediately. A somewhat ugly fix but it works if you have to stay with UIWebView for one reason or another.

_x000D_
_x000D_
window.addEventListener("orientationchange", function() {_x000D_
    var originalMarginTop = document.body.style.marginTop;_x000D_
    document.body.style.marginTop = "1px";_x000D_
    setTimeout(function () {_x000D_
        document.body.style.marginTop = originalMarginTop;_x000D_
    }, 100);_x000D_
}, false);
_x000D_
_x000D_
_x000D_

The purpose of the code is to cause the document.body.style.marginTop to change slightly and then reverse it. It doesn't necessarily have to be "1px". You can pick a value that doesn't cause your UI to flicker but achieves its purpose.

Vuex - Computed property "name" was assigned to but it has no setter

For me it was changing.

this.name = response.data;

To what computed returns so;

this.$store.state.name = response.data;

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

"A requires a peer of B but none was installed". Consider it as "A requires one of B's peers but that peer was not installed and we're not telling you which of B's peers you need."

The automatic installation of peer dependencies was explicitly removed with npm 3.

NPM Blog

Release notes of v3

So you cannot install peer dependencies automatically with npm 3 and upwards.

Updated Solution:

Use following for each peer dependency to install that and remove the error

npm install --save-dev xxxxx

Deprecated Solution:

  1. You can use npm-install-peers to find and install required peer dependencies.

    npm install -g npm-install-peers

    npm-install-peers

  2. If you are getting this error after updating any package's version then remove node_modules directory and reinstall packages by npm install or npm cache clean and npm install.

exporting multiple modules in react.js

You can have only one default export which you declare like:

export default App; or export default class App extends React.Component {...

and later do import App from './App'

If you want to export something more you can use named exports which you declare without default keyword like:

export {
  About,
  Contact,
}

or:

export About;
export Contact;

or:

export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);

and later you import them like:

import App, { About, Contact } from './App';

EDIT:

There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js file. Other than that why export anything if it is no used outside the file?. Correct main.js :

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute  } from 'react-router'

class App extends React.Component {
...
}

class Home extends React.Component {
...
}


class About extends React.Component {
...
}


class Contact extends React.Component {
...
}


ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>

), document.getElementById('app'))

EDIT2:

another thing is that this tutorial is based on react-router-V3 which has different api than v4.

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties
}

interface ResponseOrders {
  results: Order[];
}

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       params
    }).pipe(
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))
    );
} 

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().

ORIGINAL ANSWER:

In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties
}

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
       params
    })
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
  }
} 

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

Only on Firefox "Loading failed for the <script> with source"

This could also be a simple syntax error. I had a syntax error which threw on FF but not Chrome as follows:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
        defer
    </script>

Node.js: Python not found exception due to node-sass and node-gyp

Hey I got this error resolved by following the steps

  • first I uninstalled python 3.8.6 (latest version)
  • then I installed python 2.7.1 (any Python 2 version will work, but not much older and this is recommended)
  • then I added c:\python27 to environment variables
  • my OS is windows, so I followed this link
  • It worked

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

I understand this has been marked as answered but I ran into a bit of a problem when I was working on a project where I have my EF Core Data Access Layer in a .DLL Project separated from the rest of my project, API, Auth and Web and mostly will like my other projects to reference this Data project. And I don't want to want to come into the Data project to change connection strings everytime.

STEP 1: Include this in the OnConfiguring Method

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
           var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
           IConfigurationRoot configuration = new ConfigurationBuilder()
                **.SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))**
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile($"appsettings.{envName}.json", optional: false)
                .Build();
           optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
      }

NOTE: .SetBasePath(Path.Combine(Directory.GetCurrentDirectory())) This will negate or invalidate the need to copy the file to a directory as ASP.NET CORE is smart enough to pick the the right file. Also the environment specified will pick right file when the building for Release or Production, assuming the Prod environment file is selected.

STEP 2: Create appsettings.json

{
"ConnectionStrings": {       
  "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        
} 

}

PLEASE: Referece: Microsoft.Extensions.Configuration

Unable to create migrations after upgrading to ASP.NET Core 2.0

For me it was because I changed the Output Type of my startup project from Console Application to Class Library.

Reverting to Console Application did the trick.

Fixing a systemd service 203/EXEC failure (no such file or directory)

I ran across a Main process exited, code=exited, status=203/EXEC today as well and my bug was that I forgot to add the executable bit to the file.

How to downgrade tensorflow, multiple versions possible?

Pip allows to specify the version

pip install tensorflow==1.1

Is there a Google Sheets formula to put the name of the sheet into a cell?

if you want to use build-in functions:

=REGEXEXTRACT(cell("address";'Sheet1'!A1);"^'(.*)'!\$A\$1$")

Explanation: cell("address";'Sheet1'!A1) gives you the address of the sheet, output is 'Sheet1'!$A$1. Now we need to extract the actual sheet name from this output. I'm using REGEXEXTRACT to match it by regex ^'(.*)'!\$A\$1$, but you can either use more/less specific regex or use functions like SUBSTITUTE or REPLACE

Typescript Date Type?

Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:

myDate : Date;

Xcode 9 error: "iPhone has denied the launch request"

These simple steps helped me.

  1. Remove your connected iPhone, iPad from the mac.
  2. Restart your device.
  3. Select "Automatically manage signing" in Xcode settings.
  4. Reconnect your iPhone, iPad.

select rows in sql with latest date for each ID repeated multiple times

One way is:

select table.* 
from table
join 
(
    select ID, max(Date) as max_dt 
    from table
    group by ID
) t
on table.ID= t.ID and table.Date = t.max_dt 

Note that if you have multiple equally higher dates for same ID, then you will get all those rows in result

How to format JSON in notepad++

You have to use the plugin manager of Notepad++ and search for the JSON plugin. There you can easily install it.

This answer explains it pretty good: How to reformat JSON in Notepad++?

Any difference between await Promise.all() and multiple await?

Note:

This answer just covers the timing differences between await in series and Promise.all. Be sure to read @mikep's comprehensive answer that also covers the more important differences in error handling.


For the purposes of this answer I will be using some example methods:

  • res(ms) is a function that takes an integer of milliseconds and returns a promise that resolves after that many milliseconds.
  • rej(ms) is a function that takes an integer of milliseconds and returns a promise that rejects after that many milliseconds.

Calling res starts the timer. Using Promise.all to wait for a handful of delays will resolve after all the delays have finished, but remember they execute at the same time:

Example #1
const data = await Promise.all([res(3000), res(2000), res(1000)])
//                              ^^^^^^^^^  ^^^^^^^^^  ^^^^^^^^^
//                               delay 1    delay 2    delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========O                     delay 3
//
// =============================O Promise.all

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }

  const data = await Promise.all([res(3000), res(2000), res(1000)])
  console.log(`Promise.all finished`, Date.now() - start)
}

example()
_x000D_
_x000D_
_x000D_

This means that Promise.all will resolve with the data from the inner promises after 3 seconds.

But, Promise.all has a "fail fast" behavior:

Example #2
const data = await Promise.all([res(3000), res(2000), rej(1000)])
//                              ^^^^^^^^^  ^^^^^^^^^  ^^^^^^^^^
//                               delay 1    delay 2    delay 3
//
// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========X                     delay 3
//
// =========X                     Promise.all

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  function rej(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject()
        console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  try {
    const data = await Promise.all([res(3000), res(2000), rej(1000)])
  } catch (error) {
    console.log(`Promise.all finished`, Date.now() - start)
  }
}

example()
_x000D_
_x000D_
_x000D_

If you use async-await instead, you will have to wait for each promise to resolve sequentially, which may not be as efficient:

Example #3
const delay1 = res(3000)
const delay2 = res(2000)
const delay3 = rej(1000)

const data1 = await delay1
const data2 = await delay2
const data3 = await delay3

// ms ------1---------2---------3
// =============================O delay 1
// ===================O           delay 2
// =========X                     delay 3
//
// =============================X await

_x000D_
_x000D_
async function example() {
  const start = Date.now()
  let i = 0
  function res(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
        console.log(`res #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  function rej(n) {
    const id = ++i
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject()
        console.log(`rej #${id} called after ${n} milliseconds`, Date.now() - start)
      }, n)
    })
  }
  
  try {
    const delay1 = res(3000)
    const delay2 = res(2000)
    const delay3 = rej(1000)

    const data1 = await delay1
    const data2 = await delay2
    const data3 = await delay3
  } catch (error) {
    console.log(`await finished`, Date.now() - start)
  }
}

example()
_x000D_
_x000D_
_x000D_

No String-argument constructor/factory method to deserialize from String value ('')

I found a different way to handle this error. (the variables is according to the original question)

   JsonNode parsedNodes = mapper.readValue(jsonMessage , JsonNode.class);
        Response response = xmlMapper.enable(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_SINGLE_VALUE_AS_ARRAY )
                .disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES)
                .convertValue(parsedNodes, Response.class);

ESLint not working in VS Code?

General issues

Open the terminal Ctrl+`

Under output ESLint dropdown, you find useful debugging data (Errors, warnings, info).

enter image description here

For example, missing .eslintrc-.json throw this error: enter image description here

Error: ENOENT: no such file or directory, realpath

Next, check if the plugin enabled: enter image description here

Last, Since v 2.0.4 - eslint.validate in normal cases not necessary anymore (old legacy setting):

eslint.probe = an array for language identifiers for which the ESLint extension should be activated and should try to validate the file. If validation fails for probed languages the extension says silent. Defaults to [javascript, javascriptreact, typescript, typescriptreact, html, vue, markdown].

Specific Issue - First-time plugin instalation

My issue was related to the ESLint plugin "currently block" status bar enter image description here on New/First instalation (v2.1.14).

Since ESLint plugin Version 2.1.10 (08/10/2020)

no modal dialog is shown when the ESLint extension tries to load an ESLint library for the first time and an approval is necessary. Instead the ESLint status bar item changes to ESLint status icon indicating that the execution is currently block.

Click on the status-bar (Right-Bottom corner): enter image description here

Opens this popup:

enter image description here

Approve ==> Allows Everywhere

enter image description here

-or- by commands:

ctrl + Shift + p -- ESLint: Manage Library Execution

enter image description here

Read more here under "Release Notes":

https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

Vue js error: Component template should contain exactly one root element

Just make sure that you have one root div and put everything inside this root

  <div class="root">
    <!--and put all child here --!>
   <div class='child1'></div>
   <div class='child2'></div>
  </div>

and so on

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

Recommended solution is to install and trust a self-signed certificate (root). Assuming you created your own CA and the hierarchy of the certificated is correct you don't need to change the server trust evaluation. This is recommended because it doesn't require any changes in the code.

  1. Generate CA and the certificates (you can use openssl: Generating CA and self-signed certificates.
  2. Install root certificate (*.cer file) on the device - you can open it by Safari and it should redirect you to Settings
  3. When the certificated is installed, go to Certificate Trust Settings (Settings > General > About > Certificate Trust Settings) as in MattP answer.

If it is not possible then you need to change server trust evaluation.

More info in this document: Technical Q&A QA1948 HTTPS and Test Servers

Python TypeError must be str not int

print("the furnace is now " + str(temperature) + "degrees!")

cast it to str

Multiple conditions in ngClass - Angular 4

you need object notation

<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" > 

ref: NgClass

EF Core add-migration Build Failed

I had exact same error but I am using Visual Studio Community 2017 Version 15.2 (26430.14) to build .Net Core projects.

I have a ASP.NET Core MVC web project and a separate security project using ASP.NET Core Identity. The web project contains connection string in aspsettings.json config file.

I also installed Bundler & Minifier and Web Essentials 2017 extensions in Visual Studio so that I can compile, minify and bundle my assets and put them to wwwroot.

I figured out it was the MSBuild those 2 extensions secretly download that caused the problem, because I had Enable Bundle on Build and Enable Compile on Build on. After I disable that, everything works fine.

Probably not the cause to your problem, but might be worthy to just give it a try.

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

Set value to an entire column of a pandas dataframe

Python can do unexpected things when new objects are defined from existing ones. You stated in a comment above that your dataframe is defined along the lines of df = df_all.loc[df_all['issueid']==specific_id,:]. In this case, df is really just a stand-in for the rows stored in the df_all object: a new object is NOT created in memory.

To avoid these issues altogether, I often have to remind myself to use the copy module, which explicitly forces objects to be copied in memory so that methods called on the new objects are not applied to the source object. I had the same problem as you, and avoided it using the deepcopy function.

In your case, this should get rid of the warning message:

from copy import deepcopy
df = deepcopy(df_all.loc[df_all['issueid']==specific_id,:])
df['industry'] = 'yyy'

EDIT: Also see David M.'s excellent comment below!

df = df_all.loc[df_all['issueid']==specific_id,:].copy()
df['industry'] = 'yyy'

Android dependency has different version for the compile and runtime

Switching my conflicting dependencies from implementation to api does the trick. Here's a good article by mindorks explaining the difference.

https://medium.com/mindorks/implementation-vs-api-in-gradle-3-0-494c817a6fa

Edit:

Here's my dependency resolutions as well

 subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "28.0.0"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && details.requested.name.contains('play-services-base')) {
                    details.useVersion "15.0.1"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && details.requested.name.contains('play-services-tasks')) {
                    details.useVersion "15.0.1"
                }
            }
        }
    }

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

The practical reason why this doesn't work is not related to threads. The point is that node.left is effectively translated into node.getLeft().

This property getter might be defined as:

val left get() = if (Math.random() < 0.5) null else leftPtr

Therefore two calls might not return the same result.

Flutter - Wrap text on overflow, like insert ellipsis or fade

First, wrap your Row or Column in Expanded widget

Then

Text(
    'your long text here',
    overflow: TextOverflow.fade,
    maxLines: 1,
    softWrap: false,
    style: Theme.of(context).textTheme.body1,
)

Angular ngClass and click event for toggling class

Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-

<div (click)="status=!status"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

So when status is true the class success is applied. When it is false danger class is applied.

This will work without any additional code in the ts file.

HTTP Basic: Access denied fatal: Authentication failed

Before digging into the solution lets first see why this happens.

Before any transaction with git that your machine does git checks for your authentication which can be done using

  1. An SSH key token present in your machine and shared with git-repo(most preferred) OR
  2. Using your username/password (mostly used)

Why did this happen

In simple words, this happened because the credentials stored in your machine are not authentic i.e.there are chances that your password stored in the machine has changed from whats there in git therefore

Solution

Head towards, control panel and search for Credential Manager look for your use git url and change the creds.

There you go this works with mostly every that windows keep track off

Setting up Gradle for api 26 (Android)

Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.

Bootstrap 4: Multilevel Dropdown Inside Navigation

Updated 2018

Here is another variation on the Bootstrap 4.1 Navbar with multi-level dropdown. This one uses minimal CSS for the submenu, and can be re-positioned as desired:

enter image description here

https://www.codeply.com/go/nG6iMAmI2X

.dropdown-submenu {
  position: relative;
}

.dropdown-submenu .dropdown-menu {
  top: 0;
  left: 100%;
  margin-top: -1px;
}

jQuery to control display of submenus:

$('.dropdown-submenu > a').on("click", function(e) {
    var submenu = $(this);
    $('.dropdown-submenu .dropdown-menu').removeClass('show');
    submenu.next('.dropdown-menu').addClass('show');
    e.stopPropagation();
});

$('.dropdown').on("hidden.bs.dropdown", function() {
    // hide any open menus when parent closes
    $('.dropdown-menu.show').removeClass('show');
});

See this answer for activating the Bootstrap 4 submenus on hover

Enums in Javascript with ES6

you can also use es6-enum package (https://www.npmjs.com/package/es6-enum). It's very easy to use. See the example below:

import Enum from "es6-enum";
const Colors = Enum("red", "blue", "green");
Colors.red; // Symbol(red)

Angular 2 'component' is not a known element

These are the 5 steps I perform when I got such an error.

  • Are you sure the name is correct? (also check the selector defined in the component)
  • Declare the component in a module?
  • If it is in another module, export the component?
  • If it is in another module, import that module?
  • Restart the cli?

When the error eccors during unit testing, make sure your declared the component or imported the module in TestBed.configureTestingModule

I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

You can't declare a component twice. You should declare and export your component in a new separate module. Next you should import this new module in every module you want to use your component.

It is hard to tell when you should create new module and when you shouldn't. I usually create a new module for every component I reuse. When I have some components that I use almost everywhere I put them in a single module. When I have a component that I don't reuse I won't create a separate module until I need it somewhere else.

Though it might be tempting to put all you components in a single module, this is bad for the performance. While developing, a module has to recompile every time changes are made. The bigger the module (more components) the more time it takes. Making a small change to big module takes more time than making a small change in a small module.

More than one file was found with OS independent path 'META-INF/LICENSE'

You can add this in yourProject/app/build.gradle inside android{}

android {      
      packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module") 
      }          
}

Python: pandas merge multiple dataframes

There are 2 solutions for this, but it return all columns separately:

import functools

dfs = [df1, df2, df3]

df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
          date     a_x   b_x       a_y      b_y   c_x         a        b   c_y
0  May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
                0_a   0_b       1_a      1_b   1_c       2_a      2_b   2_c
date                                                                       
May 15,2017  900.00  0.2%  1,900.00  1000000  0.2%  2,900.00  2000000  0.2%

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

Customize Bootstrap checkboxes

_x000D_
_x000D_
/* The customcheck */_x000D_
.customcheck {_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    padding-left: 35px;_x000D_
    margin-bottom: 12px;_x000D_
    cursor: pointer;_x000D_
    font-size: 22px;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
    position: absolute;_x000D_
    opacity: 0;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 25px;_x000D_
    width: 25px;_x000D_
    background-color: #eee;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
    background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
    background-color: #02cf32;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
    content: "";_x000D_
    position: absolute;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
    left: 9px;_x000D_
    top: 5px;_x000D_
    width: 5px;_x000D_
    height: 10px;_x000D_
    border: solid white;_x000D_
    border-width: 0 3px 3px 0;_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
 <h1>Custom Checkboxes</h1></br>_x000D_
 _x000D_
        <label class="customcheck">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Three_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Four_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I change the font color in an html table?

<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

Faced the same issue, another solution is to add default includes, this fixed the problem for me:

$(IncludePath);

Val and Var in Kotlin

You can easily think it as:

var is used for setter (value will change).

val is used for getter (read-only, value won't change).

Android Room - simple select query - Cannot access database on the main thread

You have to execute request in background. A simple way could be using an Executors :

Executors.newSingleThreadExecutor().execute { 
   yourDb.yourDao.yourRequest() //Replace this by your request
}

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

'Property does not exist on type 'never'

Because you are assigning instance to null. The compiler infers that it can never be anything other than null. So it assumes that the else block should never be executed so instance is typed as never in the else block.

Now if you don't declare it as the literal value null, and get it by any other means (ex: let instance: Foo | null = getFoo();), you will see that instance will be null inside the if block and Foo inside the else block.

Never type documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html#never

Edit:

The issue in the updated example is actually an open issue with the compiler. See:

https://github.com/Microsoft/TypeScript/issues/11498 https://github.com/Microsoft/TypeScript/issues/12176

Android Studio 3.0 Flavor Dimension Issue

Here you can resolve this issue, you need to add flavorDimension with productFlavors's name and need to define dimension as well, see below example and for more information see here https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html

flavorDimensions 'yourAppName' //here defined dimensions
productFlavors {
    production {
        dimension 'yourAppName' //you just need to add this line
        //here you no need to write applicationIdSuffix because by default it will point to your app package which is also available inside manifest.xml file.

    }

    staging {
        dimension 'yourAppName' //added here also
        applicationIdSuffix ".staging"//(.staging) will be added after your default package name.
        //or you can also use applicationId="your_package_name.staging" instead of applicationIdSuffix but remember if you are using applicationId then You have to mention full package name.
        //versionNameSuffix "-staging"

    }

    develop {
        dimension 'yourAppName' //add here too
        applicationIdSuffix ".develop"
        //versionNameSuffix "-develop"

    }

Build .NET Core console application to output an EXE

If a .bat file is acceptable, you can create a bat file with the same name as the DLL file (and place it in the same folder), then paste in the following content:

dotnet %~n0.dll %*

Obviously, this assumes that the machine has .NET Core installed and globally available.

c:\> "path\to\batch\file" -args blah

(This answer is derived from Chet's comment.)

Try-catch block in Jenkins pipeline script

You're using the declarative style of specifying your pipeline, so you must not use try/catch blocks (which are for Scripted Pipelines), but the post section. See: https://jenkins.io/doc/book/pipeline/syntax/#post-conditions

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

Just my two cents... regarding How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems

For those of you working with php at the backend, deploying a "CORS proxy" is as simple as:

  1. create a file named 'no-cors.php' with the following content:

    $URL = $_GET['url'];
    echo json_encode(file_get_contents($URL));
    die();
    
  2. on your front end, do something like:

    fetch('https://example.com/no-cors.php' + '?url=' + url)
      .then(response=>{*/Handle Response/*})`
    

How to get the width of a react element

A simple and up to date solution is to use the React React useRef hook that stores a reference to the component/element, combined with a useEffect hook, which fires at component renders.

import React, {useState, useEffect, useRef} from 'react';

export default App = () => {
  const [width, setWidth] = useState(0);
  const elementRef = useRef(null);

  useEffect(() => {
    setWidth(elementRef.current.getBoundingClientRect().width);
  }, []); //empty dependency array so it only runs once at render

  return (
    <div ref={elementRef}>
      {width}
    </div>
  )
}

*ngIf else if in template

Or maybe just use conditional chains with ternary operator. if … else if … else if … else chain.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator#Conditional_chains

<ng-container *ngIf="isFirst ? first: isSecond ? second : third"></ng-container>

<ng-template #first></ng-template>
<ng-template #second></ng-template>
<ng-template #third></ng-template>

I like this aproach better.

angular 4: *ngIf with multiple conditions

<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">

Simulate a button click in Jest

You may use something like this to call the handler written on click:

import { shallow } from 'enzyme'; // Mount is not required

page = <MyCoolPage />;
pageMounted = shallow(page);

// The below line will execute your click function
pageMounted.instance().yourOnClickFunction();

React JS get current date

OPTION 1: if you want to make a common utility function then you can use this

export function getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

and use it by just importing it as

import {getCurrentDate} from './utils'
console.log(getCurrentDate())

OPTION 2: or define and use in a class directly

getCurrentDate(separator=''){

let newDate = new Date()
let date = newDate.getDate();
let month = newDate.getMonth() + 1;
let year = newDate.getFullYear();

return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
}

re.sub erroring with "Expected string or bytes-like object"

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

UIScrollView scroll to bottom programmatically

Xamarin.iOS version for UICollectionView of the accepted answer for ease in copying and pasting

var bottomOffset = new CGPoint (0, CollectionView.ContentSize.Height - CollectionView.Frame.Size.Height + CollectionView.ContentInset.Bottom);          
CollectionView.SetContentOffset (bottomOffset, false);

Expansion of variables inside single quotes in a command in Bash

EDIT: (As per the comments in question:)

I've been looking into this since then. I was lucky enough that I had repo laying around. Still it's not clear to me whether you need to enclose your commands between single quotes by force. I looked into the repo syntax and I don't think you need to. You could used double quotes around your command, and then use whatever single and double quotes you need inside provided you escape double ones.

SQL Server Profiler - How to filter trace to only display events from one database?

By experiment I was able to observe this:

When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!

In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.

The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)

  1. Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below

    SELECT * 
    FROM master..sysdatabases 
    WHERE name like '%your_db_name%'   -- Remove this line to see all databases
    ORDER BY dbid
    
  2. Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

How do I write a custom init for a UIView subclass in Swift?

Swift 5 Solution

You can try out this implementation for running Swift 5 on XCode 11


class CustomView: UIView {

    var customParam: customType
    
    var container = UIView()
    
    required init(customParamArg: customType) {
        self.customParam = customParamArg
        super.init(frame: .zero)
        // Setting up the view can be done here
        setupView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    func setupView() {
        // Can do the setup of the view, including adding subviews

        setupConstraints()
    }
    
    func setupConstraints() {
        // setup custom constraints as you wish
    }
    
    
}


Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

How can I see which Git branches are tracking which remote / upstream branch?

git remote show origin

Replace 'origin' with whatever the name of your remote is.

Two divs side by side - Fluid display

_x000D_
_x000D_
<div style="height:50rem; width:100%; margin: auto;">
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left; background-color: black;"></div>
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left;  background-color: black;"></div>
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left;  background-color: black;"></div>
  <div style="height:50rem; width:20%; margin-left:4%; margin-right:0%; float:left;  background-color: black;"></div>
</div>
_x000D_
_x000D_
_x000D_

margin-right isn't needed though.

SQL Server 2008: TOP 10 and distinct together

Few ideas:

  1. You have quite a few fields in your select statement. Any value being different from another will make that row distinct.
  2. TOP clauses are usually paired with WHERE clauses. Otherwise TOP doesn't mean much. Top of what? The way you specify "top of what" is to sort by using WHERE
  3. It's entirely possible to get the same results even though you use TOP and DISTINCT and WHERE. Check to make sure that the data you're querying is indeed capable of being filtered and ordered in the manner you expect.

Try something like this:

SELECT DISTINCT TOP 10 p.id, pl.nm -- , pl.val, pl.txt_val
FROM dm.labs pl
JOIN mas_data.patients p    
on pl.id = p.id
where pl.nm like '%LDL%'
and val is not null
ORDER BY pl.nm

Note that i commented out some of the SELECT to limit your result set and DISTINCT logic.

Java String.split() Regex

    String str = "a + b - c * d / e < f > g >= h <= i == j";
    String reg = "\\s*[a-zA-Z]+";

    String[] res = str.split(reg);
    for (String out : res) {
        if (!"".equals(out)) {
            System.out.print(out);
        }
    }

Output : + - * / < > >= <= ==

How to get value of checked item from CheckedListBox?

try:

  foreach (var item in chlCompanies.CheckedItems){
     item.Value //ID
     item.Text //CompanyName
  }

How to count the number of observations in R like Stata command count

The with function will let you use shorthand column references and sum will count TRUE results from the expression(s).

sum(with(aaa, sex==1 & group1==2))
## [1] 3

sum(with(aaa, sex==1 & group2=="A"))
## [1] 2

As @mnel pointed out, you can also do:

nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3

nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2

The benefit of that is that you can do:

nrow(aaa)
## [1] 6

And, the behaviour matches Stata's count almost exactly (syntax notwithstanding).

Angular: date filter adds timezone, how to output UTC?

I just used getLocaleString() function for my application. It should adapt the timeformat common to the locale, so no +0200 etc. Ofcourse, there will be less possibility for controlling the width of your string then.

var str = (new Date(1400167800)).toLocaleString();

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

I like the challenge and wanted to give an answer, which solves the issue, I think.

  1. Extract features (keypoints, descriptors such as SIFT, SURF) of the logo
  2. Match the points with a model image of the logo (using Matcher such as Brute Force )
  3. Estimate the coordinates of the rigid body (PnP problem - SolvePnP)
  4. Estimate the cap position according to the rigid body
  5. Do back-projection and calculate the image pixel position (ROI) of the cap of the bottle (I assume you have the intrinsic parameters of the camera)
  6. Check with a method whether the cap is there or not. If there, then this is the bottle

Detection of the cap is another issue. It can be either complicated or simple. If I were you, I would simply check the color histogram in the ROI for a simple decision.

Please, give the feedback if I am wrong. Thanks.

The term "Add-Migration" is not recognized

I had the same problem and found that it was a Visual Studio versioning problem in the Solution file.

I was targeting:

VisualStudioVersion = 14.0.25123.0

But I needed to target:

VisualStudioVersion = 14.0.25420.1

After making that change directly to the Solution file, EF Core cmdlets started working in the Package Manager Console.

Create an array with same element repeated multiple times

If you need to repeat an array, use the following.

Array(3).fill(['a','b','c']).flat() 

will return

Array(9) [ "a", "b", "c", "a", "b", "c", "a", "b", "c" ]

Segmentation Fault - C

Catastrophically bad:

int main(void){
      char *s;
      int ln;
      puts("Enter String");
      // scanf("%s", s);
      gets(s);
      ln = strlen(s); // remove this line to end seg fault
      char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
      dyn_s = s;
      dyn_s[strlen(s)] = '\0';
      puts(dyn_s);
      return 0;
    }

Better:

#include <stdio.h>
#define BUF_SIZE 80

int 
main(int argc, char *argv[])
{
      char s[BUF_SIZE];
      int ln;
      puts("Enter String");
      // scanf("%s", s);
      gets(s);
      ln = strlen(s); // remove this line to end seg fault
      char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
      dyn_s = s;
      dyn_s[strlen(s)] = '\0';
      puts(dyn_s);
      return 0;
    }

Best:

#include <stdio.h>
#define BUF_SIZE 80

int 
main(int argc, char *argv[])
{
      char s[BUF_SIZE];
      int ln;
      puts("Enter String");
      fgets(s, BUF_SIZE, stdin); // Use fgets (our "cin"): NEVER "gets()"

      int ln = strlen(s); 
      char *dyn_s = (char*) malloc (ln+1);
      strcpy (dyn_s, s);
      puts(dyn_s);
      return 0;
    }

MySQL: Curdate() vs Now()

CURDATE() will give current date while NOW() will give full date time.

Run the queries, and you will find out whats the difference between them.

SELECT NOW();     -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

regex match any single character (one character only)

Simple answer

If you want to match single character, put it inside those brackets [ ]

Examples

  • match + ...... [+] or +
  • match a ...... a
  • match & ...... &

...and so on. You can check your regular expresion online on this site: https://regex101.com/

(updated based on comment)

Use dynamic (variable) string as regex pattern in JavaScript

To create the regex from a string, you have to use JavaScript's RegExp object.

If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:

var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.


In the general case, escape the string before using as regex:

Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:

function escapeRegExp(stringToGoIntoTheRegex) {
    return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;

var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.

JSFiddle demo here.



Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.

Pure JavaScript: a function like jQuery's isNumeric()

There is Javascript function isNaN which will do that.

isNaN(90)
=>false

so you can check numeric by

!isNaN(90)
=>true

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

Understanding inplace=True

The inplace parameter:

df.dropna(axis='index', how='all', inplace=True)

in Pandas and in general means:

1. Pandas creates a copy of the original data

2. ... does some computation on it

3. ... assigns the results to the original data.

4. ... deletes the copy.

As you can read in the rest of my answer's further below, we still can have good reason to use this parameter i.e. the inplace operations, but we should avoid it if we can, as it generate more issues, as:

1. Your code will be harder to debug (Actually SettingwithCopyWarning stands for warning you to this possible problem)

2. Conflict with method chaining


So there is even case when we should use it yet?

Definitely yes. If we use pandas or any tool for handeling huge dataset, we can easily face the situation, where some big data can consume our entire memory. To avoid this unwanted effect we can use some technics like method chaining:

(
    wine.rename(columns={"color_intensity": "ci"})
    .assign(color_filter=lambda x: np.where((x.hue > 1) & (x.ci > 7), 1, 0))
    .query("alcohol > 14 and color_filter == 1")
    .sort_values("alcohol", ascending=False)
    .reset_index(drop=True)
    .loc[:, ["alcohol", "ci", "hue"]]
)

which make our code more compact (though harder to interpret and debug too) and consumes less memory as the chained methods works with the other method's returned values, thus resulting in only one copy of the input data. We can see clearly, that we will have 2 x original data memory consumption after this operations.

Or we can use inplace parameter (though harder to interpret and debug too) our memory consumption will be 2 x original data, but our memory consumption after this operation remains 1 x original data, which if somebody whenever worked with huge datasets exactly knows can be a big benefit.


Final conclusion:

Avoid using inplace parameter unless you don't work with huge data and be aware of its possible issues in case of still using of it.

How do I create a GUI for a windows application using C++?

If you want to learn about win32, WTL http://wtl.sourceforge.net/ is the pretty lightweight equivalent to MFC, but you have to love template to use it.

If you want something simple MFC is already integrated with VS, also it has a large base of extra code and workarounds of know bugs in the net already.

Also Qt is really great framework it have a nice set of tools, dialog editor, themes, and a lot of other stuff, plus your application will be ready to be cross platform, although it will require some time to get accustomed.

You also have Gtk, wxWindow, and you will have no problems if you have already used it on linux.

SVG drop shadow using css3

Probably an evolution, it appears that inline css filters works nicely on elements, in a certain way.

Declaring a drop-shadow css filter, in an svg element, in both a class or inline does NOT works, as specified earlier.

But, at least in Firefox, with the following wizardry:

Appending the filter declaration inline, with javascript, after DOM load.

_x000D_
_x000D_
// Does not works, with regular dynamic css styling:

shadow0.oninput = () => {
  rect1.style.filter = "filter:drop-shadow(0 0 " + shadow0.value + "rem black);"
}

// Okay! Inline styling, appending.

shadow1.oninput = () => {
  rect1.style += " ;filter:drop-shadow(0 0 " + shadow1.value + "rem black);"
  rect2.style += " ;filter:drop-shadow(0 0 " + shadow1.value + "rem black);"
}
_x000D_
<h2>Firefox only</h2>
<h4>
Does not works! 
<input id="shadow0" type="number" min="0" max="100" step="0.1">

 | Okay!
<input id="shadow1" type="number" min="0" max="100" step="0.1">

<svg viewBox="0 0 120 70">  
    <rect id="rect1" x="10" y="10" width="100" height="50" fill="#c66" />
    
    <!-- Inline style declaration does NOT works at svg level, no shadow at loading: -->
    <rect id="rect2" x="40" y="30" width="10" height="10" fill="#aaa" style="filter:drop-shadow(0 0 20rem black)" />
    
</svg>
_x000D_
_x000D_
_x000D_

enter image description here

Android Color Picker

We have just uploaded AmbilWarna color picker to Maven:

https://github.com/yukuku/ambilwarna

It can be used either as a dialog or as a Preference entry.

enter image description here

C++ static virtual members?

Many say it is not possible, I would go one step further and say it is not meaningfull.

A static member is something that does not relate to any instance, only to the class.

A virtual member is something that does not relate directly to any class, only to an instance.

So a static virtual member would be something that does not relate to any instance or any class.

How can I include a YAML file inside another?

No, YAML does not include any kind of "import" or "include" statement.

How to check whether a given string is valid JSON in Java

import static net.minidev.json.JSONValue.isValidJson;

and then call this function passing in your JSON String :)

Sort a List of Object in VB.NET

If you need a custom string sort, you can create a function that returns a number based on the order you specify.

For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:

Private Function sortpictures(s As String) As Integer
    If Regex.IsMatch(s, "FRONT") Then
        Return 0
    ElseIf Regex.IsMatch(s, "SIDE") Then
        Return 1
    ElseIf Regex.IsMatch(s, "CLASP") Then
        Return 2
    Else
        Return 3
    End If
End Function

Then I call the sort function like this:

list.Sort(Function(elA As String, elB As String)
                  Return sortpictures(elA).CompareTo(sortpictures(elB))
              End Function)

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Alright so after trying every solution out there to solve this exact issues on a wordpress blog, I might have done something either really stupid or genius... With no idea why there's an increase in Mysql connections, I used the php script below in my header to kill all sleeping processes..

So every visitor to my site helps in killing the sleeping processes..

<?php
$result = mysql_query("SHOW processlist");
while ($myrow = mysql_fetch_assoc($result)) {
if ($myrow['Command'] == "Sleep") {
mysql_query("KILL {$myrow['Id']}");}
}
?>

How does one add keyboard languages and switch between them in Linux Mint 16?

For Linux Mint 18 Cinnamon

Menu > Keyboard Preferences > Layouts > Options > Switching to another layout.

Error when creating a new text file with python?

This works just fine, but instead of

name = input('Enter name of text file: ')+'.txt' 

you should use

name = raw_input('Enter name of text file: ')+'.txt'

along with

open(name,'a') or open(name,'w')

Measure the time it takes to execute a t-sql query

Another way is using a SQL Server built-in feature named Client Statistics which is accessible through Menu > Query > Include Client Statistics.

You can run each query in separated query window and compare the results which is given in Client Statistics tab just beside the Messages tab.

For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.

Result

You can read all 3 ways for acquiring execution time in here. You may even need to display Estimated Execution Plan ctrlL for further investigation about your query.

Capturing mobile phone traffic on Wireshark

Packet Capture Android app implements a VPN that logs all network traffic on the Android device. You don't need to setup any VPN/proxy server on your PC. Does not needs root. Supports SSL decryption which tPacketCapture does not. It also includes a good log viewer.

PHP Session data not being saved

Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.

Pythonic way to find maximum value and its index in a list?

There are many options, for example:

import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

As BMSAndroidDroid said, this problem may be caused by a wrong build path configuration.

If you included some libraries to your build path, then move the libraries, the build path will conserve the wrong references, will not found the libraries during compilation and you will get an error.

To fix it, right click on your project folder > build path > configure build path Then take a look to the library tab, and remove the old libraries.

Break a previous commit into multiple commits

If you have this:

A - B <- mybranch

Where you have committed some content in commit B:

/modules/a/file1
/modules/a/file2
/modules/b/file3
/modules/b/file4

But you want to split B into C - D, and get this result:

A - C - D <-mybranch

You can divide the content like this for example (content from different directories in different commits)...

Reset the branch back to the commit before the one to split:

git checkout mybranch
git reset --hard A

Create first commit (C):

git checkout B /modules/a
git add -u
git commit -m "content of /modules/a"

Create second commit (D):

git checkout B /modules/b
git add -u
git commit -m "content of /modules/b"

Error Code: 1005. Can't create table '...' (errno: 150)

Sometimes it is due to the master table is dropped (maybe by disabling foreign_key_checks), but the foreign key CONSTRAINT still exists in other tables. In my case I had dropped the table and tried to recreate it, but it was throwing the same error for me.

So try dropping all the foreign key CONSTRAINTs from all the tables if there are any and then update or create the table.

How can I create a border around an Android LinearLayout?

Try This in your res/drawable

    <?xml version="1.0" encoding="UTF-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
  <shape
    android:shape="rectangle">
    <padding android:left="15dp"
        android:right="15dp"
        android:top="15dp"
        android:bottom="15dp"/>
    <stroke android:width="10dp"
        android:color="@color/colorPrimary"/>
  </shape>
</item><item android:left="-5dp"
        android:right="-5dp"
        android:top="-5dp"
        android:bottom="-5dp">
  <shape android:shape="rectangle">
    <solid android:color="@color/background" />
  </shape></item></layer-list>

Sass Nesting for :hover does not work

You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

Golang read request body

I could use the GetBody from Request package.

Look this comment in source code from request.go in net/http:

GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."

GetBody func() (io.ReadCloser, error)

This way you can get the body request without make it empty.

Sample:

getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
    // Do something return err
}
http.DefaultClient.Do(request)

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

How to read the value of a private field from a different class in Java?

In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type

Expand a random range from 1–5 to 1–7

rand25() =5*(rand5()-1) + rand5()

rand7() { 
   while(true) {
       int r = rand25();
       if (r < 21) return r%3;         
   }
}

Why this works: probability that the loop will run forever is 0.

Generating a PNG with matplotlib when DISPLAY is undefined

I will just repeat what @Ivo Bosticky said which can be overlooked. Put these lines at the VERY start of the py file.

import matplotlib
matplotlib.use('Agg') 

Or one would get error

*/usr/lib/pymodules/python2.7/matplotlib/__init__.py:923: UserWarning:  This call to   matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,*

This will resolve all Display issue

How to process SIGTERM signal gracefully?

I think you are near to a possible solution.

Execute mainloop in a separate thread and extend it with the property shutdown_flag. The signal can be caught with signal.signal(signal.SIGTERM, handler) in the main thread (not in a separate thread). The signal handler should set shutdown_flag to True and wait for the thread to end with thread.join()

Using %f with strftime() in Python to get microseconds

If you want speed, try this:

def _timestamp(prec=0):
    t = time.time()
    s = time.strftime("%H:%M:%S", time.localtime(t))
    if prec > 0:
        s += ("%.9f" % (t % 1,))[1:2+prec]
    return s

Where prec is precision -- how many decimal places you want. Please note that the function does not have issues with leading zeros in fractional part like some other solutions presented here.

cocoapods - 'pod install' takes forever

you can run

pod install --verbose 

to see what's going on behind the scenes.. at least you'll know where it's stuck at (it could be a git clone operation that's taking too long because of your slow network etc)

to have an even better idea of why it seems to be stuck (running verbose can get you something like this

-> Installing Typhoon (2.2.1)
 > GitHub download
 > Creating cache git repo (~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92)
 > Cloning to Pods folder
       $ /usr/bin/git clone https://github.com/typhoon-framework/Typhoon.git ~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92 --mirror
       Cloning into bare repository '~/Library/Caches/CocoaPods/GitHub/0363445acc1ed036ea1f162b4d8d143134f53b92'...

is to find out the size of the git repo you're cloning.. if you're cloning from github.. you can use this format:

/repos/:user/:repo

so, for example, to find out about the above repo type

https://api.github.com/repos/typhoon-framework/Typhoon

and the returned JSON will have a size key, value. so the above returned

"size": 94014,

which is approx 90mb. no wonder it's taking forever! (btw.. by the time I wrote this.. it just finished.. ha!)


update: one common thing that cocoa pods do before it even starts downloading the dependencies listed in your podfile, is to download/update its own repo (they call it Setting up Cocoapods Master repo.. look at this:

pod install --verbose

Analyzing dependencies

Updating spec repositories
  $ /usr/bin/git rev-parse  >/dev/null 2>&1
  $ /usr/bin/git ls-remote
  From https://github.com/CocoaPods/Specs.git
  09b0e7431ab82063d467296904a85d72ed40cd73  HEAD
  ..

the bad news is that if you follow the above procedure to find out how big the cocoa pod repo is.. you'll get this: "size": 614373,.. which is a lot.

so to get a more accurate way of knowing how long it takes to just install your own repo.. you can set up the cocoa pods master repo separately by using pod setup:

$ pod help setup
Usage:

$ pod setup

  Creates a directory at `~/.cocoapods/repos` which will hold your spec-repos.
  This is where it will create a clone of the public `master` spec-repo from:

      https://github.com/CocoaPods/Specs

  If the clone already exists, it will ensure that it is up-to-date.

then running pod install

How to prevent downloading images and video files from my website?

This is how I do it in case anyone in the future is wondering.

I put this in the .htaccess file on the root server:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain.com/ [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?domain.com.*$ [NC]
RewriteRule \.(mp4|avi)$ - [F]

This stops them from say going to domain.com/videos/myVid.mp4 and then saving it from there.

nodejs get file name from absolute path?

To get the file name portion of the file name, the basename method is used:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);

console.log(file); // 'python.exe'

If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);

console.log(file); // 'python'

Test if object implements interface

What worked for me is:

Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));

Angularjs loading screen on ajax request

Create a Directive with the show and size attributes ( you can add more also )

    app.directive('loader',function(){
    return {
    restrict:'EA',
    scope:{
        show : '@',
      size : '@'
    },
    template : '<div class="loader-container"><div class="loader" ng-if="show" ng-class="size"></div></div>'
  }
})

and in html use as

 <loader show="{{loader1}}" size="sm"></loader>

In the show variable pass true when any promise is running and make that false when request is completed. Active demo - Angular Loader directive example demo in JsFiddle

Unable to open debugger port in IntelliJ IDEA

For anyone who comes here with the similar message:

Unable to open debugger port (127.0.0.1:50470):
    java.net.SocketException "Interrupted function call: accept failed"

This may be caused by something completely independent, i.e. it's not a port configuration. If you're running Tomcat, for instance, it may be that you have an invalid web.xml. Check your Event Log for any previous errors:

Cannot load C:\...\conf\web.xml: ParseError at [row,col]:[480,29]
            Message: The element type "param-value" must be terminated by the matching end-tag "</param-value>".

IntellIj error log screenshot

How to call stopservice() method of Service class from the calling activity class

In fact to stopping the service we must use the method stopService() and you are doing in right way:

Start service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  startService(myService);

Stop service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  stopService(myService);

if you call stopService(), then the method onDestroy() in the service is called (NOT the stopService() method):

  @Override
    public void onDestroy() {
      timer.cancel();
      task.cancel();    
        Log.i(TAG, "onCreate() , service stopped...");
    }

you must implement the onDestroy() method!.

Here is a complete example including how to start/stop the service.

Angular 2: How to access an HTTP response body?

The response data are in JSON string form. The app must parse that string into JavaScript objects by calling response.json().

  this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
  .map(res => res.json())
  .subscribe(data => {
    console.log(data);
  })

https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data

What is the difference between Cloud Computing and Grid Computing?

Grid computing is where more than one computer coordinates to solve a problem together. Often used for problems involving a lot of number crunching, which can be easily parallelisable.

Cloud computing is where an application doesn't access resources it requires directly, rather it accesses them through something like a service. So instead of talking to a specific hard drive for storage, and a specific CPU for computation, etc. it talks to some service that provides these resources. The service then maps any requests for resources to its physical resources, in order to provide for the application. Usually the service has access to a large amount of physical resources, and can dynamically allocate them as they are needed.

In this way, if an application requires only a small amount of some resource, say computation, then the service only allocates a small amount, say on a single physical CPU (that may be shared with some other application using the service). If the application requires a large amount of some resource, then the service allocates that large amount, say a grid of CPUs. The application is relatively oblivious to this, and all the complex handling and coordination is performed by the service, not the application. In this way the application can scale well.

For example a web site written "on the cloud" may share a server with many other web sites while it has a low amount of traffic, but may be moved to its own dedicated server, or grid of servers, if it ever has massive amounts of traffic. This is all handled by the cloud service, so the application shouldn't have to be modified drastically to cope.

A cloud would usually use a grid. A grid is not necessarily a cloud or part of a cloud.

Wikipedia articles: Grid computing, Cloud computing.

How to get summary statistics by group

take a look at the plyr package. Specifically, ddply

ddply(df, .(group), summarise, mean=mean(dt), sum=sum(dt))

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

If you want to test if an object is strictly or extends a Hash, use:

value = {}
value.is_a?(Hash) || value.is_a?(Array) #=> true

But to make value of Ruby's duck typing, you could do something like:

value = {}
value.respond_to?(:[]) #=> true

It is useful when you only want to access some value using the value[:key] syntax.

Please note that Array.new["key"] will raise a TypeError.

How do I add a Font Awesome icon to input field?

.fa-file-o {
    position: absolute;
    left: 50px;
    top: 15px;
    color: #ffffff
}

<div>
 <span class="fa fa-file-o"></span>
 <input type="button" name="" value="IMPORT FILE"/>
</div>

How can I easily add storage to a VirtualBox machine with XP installed?

After resizing and not being able to view the resizing on my windows XP guest machine, I had to

  1. clone it
  2. resize it with "VBoxManage modifyhd winxppro\ Clone.vdi --resize 30720" and everything worked

I saw in other forums that snapshots can interfere for resizing and not being able to remove all snapshots for different errors I got, the only found solution for me was to clone it to remove the snapshots and then resize it, and everything worked. For resizing outside windows, a gparted boot cd that can be found here can help

proper hibernate annotation for byte[]

Here goes what O'reilly Enterprise JavaBeans, 3.0 says

JDBC has special types for these very large objects. The java.sql.Blob type represents binary data, and java.sql.Clob represents character data.

Here goes PostgreSQLDialect source code

public PostgreSQLDialect() {
    super();
    ...
    registerColumnType(Types.VARBINARY, "bytea");
    /**
      * Notice it maps java.sql.Types.BLOB as oid
      */
    registerColumnType(Types.BLOB, "oid");
}

So what you can do

Override PostgreSQLDialect as follows

public class CustomPostgreSQLDialect extends PostgreSQLDialect {

    public CustomPostgreSQLDialect() {
        super();

        registerColumnType(Types.BLOB, "bytea");
    }
}

Now just define your custom dialect

<property name="hibernate.dialect" value="br.com.ar.dialect.CustomPostgreSQLDialect"/>

And use your portable JPA @Lob annotation

@Lob
public byte[] getValueBuffer() {

UPDATE

Here has been extracted here

I have an application running in hibernate 3.3.2 and the applications works fine, with all blob fields using oid (byte[] in java)

...

Migrating to hibernate 3.5 all blob fields not work anymore, and the server log shows: ERROR org.hibernate.util.JDBCExceptionReporter - ERROR: column is of type oid but expression is of type bytea

which can be explained here

This generaly is not bug in PG JDBC, but change of default implementation of Hibernate in 3.5 version. In my situation setting compatible property on connection did not helped.

...

Much more this what I saw in 3.5 - beta 2, and i do not know if this was fixed is Hibernate - without @Type annotation - will auto-create column of type oid, but will try to read this as bytea

Interesting is because when he maps Types.BOLB as bytea (See CustomPostgreSQLDialect) He get

Could not execute JDBC batch update

when inserting or updating

jQuery UI - Close Dialog When Clicked Outside

I use this solution based in one posted here:

var g_divOpenDialog = null;
function _openDlg(l_d) {

  // http://stackoverflow.com/questions/2554779/jquery-ui-close-dialog-when-clicked-outside
  jQuery('body').bind(
   'click',
   function(e){
    if(
      g_divOpenDialog!=null 
      && !jQuery(e.target).is('.ui-dialog, a')
      && !jQuery(e.target).closest('.ui-dialog').length
    ){
      _closeDlg();
    }
   }
  );

  setTimeout(function() {
    g_divOpenDialog = l_d;
    g_divOpenDialog.dialog();
  }, 500);
}
function _closeDlg() {
  jQuery('body').unbind('click');
  g_divOpenDialog.dialog('close');
  g_divOpenDialog.dialog('destroy');
  g_divOpenDialog = null;
}

Python send UDP packet

With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:

print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))

Common CSS Media Queries Break Points

I've been using:

@media only screen and (min-width: 768px) {
    /* tablets and desktop */
}

@media only screen and (max-width: 767px) {
    /* phones */
}

@media only screen and (max-width: 767px) and (orientation: portrait) {
    /* portrait phones */
}

It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).

How do I set session timeout of greater than 30 minutes

Setting session timeout through the deployment descriptor should work - it sets the default session timeout for the web app. Calling session.setMaxInactiveInterval() sets the timeout for the particular session it is called on, and overrides the default. Be aware of the unit difference, too - the deployment descriptor version uses minutes, and session.setMaxInactiveInterval() uses seconds.

So

<session-config>
    <session-timeout>60</session-timeout>
</session-config>

sets the default session timeout to 60 minutes.

And

session.setMaxInactiveInterval(600);

sets the session timeout to 600 seconds - 10 minutes - for the specific session it's called on.

This should work in Tomcat or Glassfish or any other Java web server - it's part of the spec.

The way to check a HDFS directory's size?

hdfs dfs -count <dir>

info from man page:

-count [-q] [-h] [-v] [-t [<storage type>]] [-u] <path> ... :
  Count the number of directories, files and bytes under the paths
  that match the specified file pattern.  The output columns are:
  DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME
  or, with the -q option:
  QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA
        DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME

How do I reload a page without a POSTDATA warning in Javascript?

I've written a function that will reload the page without post submission and it will work with hashes, too.

I do this by adding / modifying a GET parameter in the URL called reload by updating its value with the current timestamp in ms.

var reload = function () {
    var regex = new RegExp("([?;&])reload[^&;]*[;&]?");
    var query = window.location.href.split('#')[0].replace(regex, "$1").replace(/&$/, '');
    window.location.href =
        (window.location.href.indexOf('?') < 0 ? "?" : query + (query.slice(-1) != "?" ? "&" : ""))
        + "reload=" + new Date().getTime() + window.location.hash;
};

Keep in mind, if you want to trigger this function in a href attribute, implement it this way: href="javascript:reload();void 0;" to make it work, successfully.

The downside of my solution is it will change the URL, so this "reload" is not a real reload, instead it's a load with a different query. Still, it could fit your needs like it does for me.

How to convert DateTime to a number with a precision greater than days in T-SQL?

SELECT CAST(CONVERT(datetime,'2009-06-15 23:01:00') as float)

yields 39977.9590277778

Flutter Countdown Timer

If all you need is a simple countdown timer, this is a good alternative instead of installing a package. Happy coding!

countDownTimer() async {
 int timerCount;
 for (int x = 5; x > 0; x--) {
   await Future.delayed(Duration(seconds: 1)).then((_) {
     setState(() {
       timerCount -= 1;
    });
  });
 }
}

Javascript variable access in HTML

In raw javascript, you'll want to put an id on your anchor tag and do this:

<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];

function insertText(){
    document.getElementById('someId').InnerHTML = splitText;}
</script>

<body onload="insertText()">
<a href = test.html id="someId">I need the value of "splitText" variable here</a>
</body>
</html>

How to convert Double to int directly?

double myDb = 12.3;
int myInt = (int) myDb;

Result is: myInt = 12

Run a Java Application as a Service on Linux

From Spring Boot Reference Guide

Installation as an init.d service (System V)

Simply symlink the jar to init.d to support the standard start, stop, restart and status commands. Assuming that you have a Spring Boot application installed in /var/myapp, to install a Spring Boot application as an init.d service simply create a symlink:

$ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp

Once installed, you can start and stop the service in the usual way. For example, on a Debian based system:

$ service myapp start

Tip If your application fails to start, check the log file written to /var/log/<appname>.log for errors.

Continue reading to know how to secure a deployed service.

After doing as written I've discovered that my service fails to start with this error message in logs: start-stop-daemon: unrecognized option --no-close. And I've managed to fix it by creating a config file /var/myapp/myapp.conf with the following content

USE_START_STOP_DAEMON=false

What is MVC and what are the advantages of it?

One of the major advantages of MVC which has not mentioned here is that MVC provides RESTful urls which enables SEO. When you name your Controllers and Actions wisely, it makes it easier for search engines to find your site if they only take a look at your site Urls. For example you have a car sale website and a page which displays available Lamborghini Veneno cars, instead of having www.MyCarSale.com/product/6548 referring to the page you can choose www.MyCarSale.com/SportCar/Lamborghini-Veneno url for SEO purpose.

Here is a good answer to MVC Advantages and here is an article How to create a SEO friendly Url.

How can I map True/False to 1/0 in a Pandas DataFrame?

A succinct way to convert a single column of boolean values to a column of integers 1 or 0:

df["somecolumn"] = df["somecolumn"].astype(int)

How to add message box with 'OK' button?

The code compiles ok for me. May be you have forgotten to add the import:

import android.app.AlertDialog;

Anyway, you have a good tutorial here.

How to subtract n days from current date in java?

this will subtract ten days of the current date (before Java 8):

int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();

If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):

LocalDate tenDaysAgo = LocalDate.now().minusDays(10);

For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date

Get the ID of a drawable in ImageView

As of today, there is no support on this function. However, I found a little hack on this one.

 imageView.setImageResource(R.drawable.ic_star_black_48dp);
 imageView.setTag(R.drawable.ic_star_black_48dp);

So if you want to get the ID of the view, just get it's tag.

if (imageView.getTag() != null) {
   int resourceID = (int) imageView.getTag();

   //
   // drawable id.
   //   
}

Is iterating ConcurrentHashMap values thread safe?

You may use this class to test two accessing threads and one mutating the shared instance of ConcurrentHashMap:

import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Map<String, String> map;

    public Accessor(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (Map.Entry<String, String> entry : this.map.entrySet())
      {
        System.out.println(
            Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']'
        );
      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        System.out.println(Thread.currentThread().getName() + ": " + i);
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.map);
    Accessor a2 = new Accessor(this.map);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

No exception will be thrown.

Sharing the same iterator between accessor threads can lead to deadlock:

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while(iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st = Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Map<String, String> map;
    private final Random random = new Random();

    public Mutator(Map<String, String> map)
    {
      this.map = map;
    }

    @Override
    public void run()
    {
      for (int i = 0; i < 100; i++)
      {
        this.map.remove("key" + random.nextInt(MAP_SIZE));
        this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
      }
    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(this.map);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

As soon as you start sharing the same Iterator<Map.Entry<String, String>> among accessor and mutator threads java.lang.IllegalStateExceptions will start popping up.

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentMapIteration
{
  private final Map<String, String> map = new ConcurrentHashMap<String, String>();
  private final Iterator<Map.Entry<String, String>> iterator;

  private final static int MAP_SIZE = 100000;

  public static void main(String[] args)
  {
    new ConcurrentMapIteration().run();
  }

  public ConcurrentMapIteration()
  {
    for (int i = 0; i < MAP_SIZE; i++)
    {
      map.put("key" + i, UUID.randomUUID().toString());
    }
    this.iterator = this.map.entrySet().iterator();
  }

  private final ExecutorService executor = Executors.newCachedThreadPool();

  private final class Accessor implements Runnable
  {
    private final Iterator<Map.Entry<String, String>> iterator;

    public Accessor(Iterator<Map.Entry<String, String>> iterator)
    {
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        Map.Entry<String, String> entry = iterator.next();
        try
        {
          String st =
              Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
        } catch (Exception e)
        {
          e.printStackTrace();
        }

      }
    }
  }

  private final class Mutator implements Runnable
  {

    private final Random random = new Random();

    private final Iterator<Map.Entry<String, String>> iterator;

    private final Map<String, String> map;

    public Mutator(Map<String, String> map, Iterator<Map.Entry<String, String>> iterator)
    {
      this.map = map;
      this.iterator = iterator;
    }

    @Override
    public void run()
    {
      while (iterator.hasNext())
      {
        try
        {
          iterator.remove();
          this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
        } catch (Exception ex)
        {
          ex.printStackTrace();
        }
      }

    }
  }

  private void run()
  {
    Accessor a1 = new Accessor(this.iterator);
    Accessor a2 = new Accessor(this.iterator);
    Mutator m = new Mutator(map, this.iterator);

    executor.execute(a1);
    executor.execute(m);
    executor.execute(a2);
  }
}

Alternative to itoa() for converting integer to string C++?

boost::lexical_cast works pretty well.

#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
    std::string foo = boost::lexical_cast<std::string>(argc);
}

Convert String to int array in java

String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());

How to get a .csv file into R?

You can use

df <- read.csv("filename.csv", header=TRUE)

# To loop each column
for (i in 1:ncol(df))
    {
    dosomething(df[,i])
    }
# To loop each row
for (i in 1:nrow(df))
    {
    dosomething(df[i,])
    }

Also, you may want to have a look to the apply function (type ?apply or help(apply))if you want to use the same function on each row/column

How to shutdown my Jenkins safely?

You can kill Jenkins safely. It will catch SIGTERM and SIGINT and perform an orderly shutdown. However, if Jenkins was in the middle of building something, it will abort the builds and they will show up gray in the status display.

If you want to avoid this, you must put Jenkins into shutdown mode to prevent it from starting new builds and wait until currently running builds are done before killing Jenkins.

You can also use the Jenkins command line interface and tell Jenkins to safe-shutdown, which does the same. You can find more info on Jenkins cli at http://YOURJENKINS/cli

Error parsing yaml file: mapping values are not allowed here

Change

application:climate-change

to

application: climate-change

The space after the colon is mandatory in yaml if you want a key-value pair. (See http://www.yaml.org/spec/1.2/spec.html#id2759963)

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

Why and how to fix? IIS Express "The specified port is in use"

netstat didn't show anything already using the port

netstat -ano | findstr <your port number> showed nothing for me. I found out that port was excluded using this command to see what ranges are reserved by something else:

netsh interface ipv4 show excludedportrange protocol=tcp

You can try to unblock the range from the start port for a number of ports (need Command Prompt with Administrator):

netsh int ip delete excludedportrange protocol=tcp numberofports=<number of ports> startport=<start port>

However, in my case I couldn't unblock the range, I just got "Access is denied", so I ended up having to pick another port for my site.

My original solution: The only thing that worked was deleting the .vs folder in the solution folder. (I've since found you can just delete the .vs/config/applicationhost.config instead to avoid losing so many settings).

why is plotting with Matplotlib so slow?

To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook

However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.

Put these two lines before you import anything else from matplotlib:

import matplotlib
matplotlib.use('GTKAgg') 

Of course, there are various options to use instead of GTKAgg, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.

Confirm postback OnClientClick button ASP.NET

Try this:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
                       OnClick="BtnUserDelete_Click"
                       OnClientClick="if ( ! UserDeleteConfirmation()) return false;" 
 meta:resourcekey="BtnUserDeleteResource1" />

This way the "return" is only executed when the user clicks "cancel" and not when he clicks "ok".

By the way, you can shorten the UserDeleteConfirmation function to:

function UserDeleteConfirmation() {
    return confirm("Are you sure you want to delete this user?");
}

insert datetime value in sql database with c#

The following should work and is my recommendation (parameterized query):

DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

No templates in Visual Studio 2017

In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.

When running the Team Explorer version, only the Blank Solution option was available.

The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"

Once I launched the correct EXE, Visual Studio started working as expected.

The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"

Print the address or pointer for value in C

char c = 'A';
printf("ptr: %p,\tvalue: %c,\tand also address: %zu", &c, c, &c);

Result:

ptr: 0x7ffc48e5105f,    value: A,    and also address: 140721531457631

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

Java enum - why use toString instead of name

A practical example when name() and toString() make sense to be different is a pattern where single-valued enum is used to define a singleton. It looks surprisingly at first but makes a lot of sense:

enum SingletonComponent {
    INSTANCE(/*..configuration...*/);

    /* ...behavior... */

    @Override
    String toString() {
      return "SingletonComponent"; // better than default "INSTANCE"
    }
}

In such case:

SingletonComponent myComponent = SingletonComponent.INSTANCE;
assertThat(myComponent.name()).isEqualTo("INSTANCE"); // blah
assertThat(myComponent.toString()).isEqualTo("SingletonComponent"); // better

Google Geocoding API - REQUEST_DENIED

I've noticed that you also get REQUEST_DENIED for some addresses if you don't properly URL encode your address. For example, in

123 Main St #B, Mytown, CA 94110

the '#' character needs to be encoded as %23

Search all tables, all columns for a specific value SQL Server

You could query the sys.tables database view to get out the names of the tables, and then use this query to build yourself another query to do the update on the back of that. For instance:

select 'select * from '+name from sys.tables

will give you a script that will run a select * against all the tables in the system catalog, you could alter the string in the select clause to do your update, as long as you know the column name is the same on all the tables you wish to update, so your script would look something like:

select 'update '+name+' set comments = ''(*)''+comments where comments like ''%comment to be updated%'' ' from sys.tables

You could also then predicate on the tables query to only include tables that have a name in a certain format, or are in a subset you want to create the update script for.

Using ng-if as a switch inside ng-repeat?

I will suggest move all templates to separate files, and don't do spagetti inside repeat

take a look here:

html:

<div ng-repeat = "data in comments">
    <div ng-include src="buildUrl(data.type)"></div>
 </div>

js:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {

  $scope.comments = [
    {"_id":"52fb84fac6b93c152d8b4569",
       "post_id":"52fb84fac6b93c152d8b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"hoot"},  
    {"_id":"52fb798cc6b93c74298b4568",
       "post_id":"52fb798cc6b93c74298b4567",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"story"},        
    {"_id":"52fb7977c6b93c5c2c8b456b",
       "post_id":"52fb7977c6b93c5c2c8b456a",
       "user_id":"52df9ab5c6b93c8e2a8b4567",
       "type":"article"}
  ];

  $scope.buildUrl = function(type) {
    return type + '.html';
  }
});

http://plnkr.co/edit/HxnirSvMHNQ748M2WeRt?p=preview

Convert NSDate to String in iOS Swift

you get the detail information from Apple Dateformatter Document.If you want to set the dateformat for your dateString, see this link , the detail dateformat you can get here for e.g , do like

let formatter = DateFormatter()
// initially set the format based on your datepicker date / server String
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let myString = formatter.string(from: Date()) // string purpose I add here 
// convert your string to date
let yourDate = formatter.date(from: myString)
//then again set the date format whhich type of output you need
formatter.dateFormat = "dd-MMM-yyyy"
// again convert your date to string
let myStringafd = formatter.string(from: yourDate!)

print(myStringafd)

you get the output as

enter image description here

Combining C++ and C - how does #ifdef __cplusplus work?

extern "C" doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).

What extern "C" does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.

Code inside an extern "C" is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage. You can't define any new symbols that can't be built with C linkage. That means no classes or templates, for example.

extern "C" blocks nest nicely. There's also extern "C++" if you find yourself hopelessly trapped inside of extern "C" regions, but it isn't such a good idea from a cleanliness perspective.

Now, specifically regarding your numbered questions:

Regarding #1: __cplusplus will stay defined inside of extern "C" blocks. This doesn't matter, though, since the blocks should nest neatly.

Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have extern "C" when being interpreted as C++, and they should not have extern "C" when being interpreted as C -- hence the #ifdef __cplusplus checking.

To answer your question #3: functions without prototypes will have C++ linkage if they are in .cpp files and not inside of an extern "C" block. This is fine, though, because if it has no prototype, it can only be called by other functions in the same file, and then you don't generally care what the linkage looks like, because you aren't planning on having that function be called by anything outside the same compilation unit anyway.

For #4, you've got it exactly. If you are including a header for code that has C linkage (such as code that was compiled by a C compiler), then you must extern "C" the header -- that way you will be able to link with the library. (Otherwise, your linker would be looking for functions with names like _Z1hic when you were looking for void h(int, char)

5: This sort of mixing is a common reason to use extern "C", and I don't see anything wrong with doing it this way -- just make sure you understand what you are doing.

How to select last one week data from today's date

  1. The query is correct

2A. As far as last seven days have much less rows than whole table an index can help

2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size

Inheritance and Overriding __init__ in python

The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.

It looks like this nowadays:

class FileInfo(dict):
    """store file metadata"""
    def __init__(self, filename=None):
        super(FileInfo, self).__init__()
        self["name"] = filename

Note the following:

  1. We can directly subclass built-in classes, like dict, list, tuple, etc.

  2. The super function handles tracking down this class's superclasses and calling functions in them appropriately.

How do I create a timer in WPF?

Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

Migration: Cannot add foreign key constraint

We cannot add relations, unless related tables gets created. Laravel run migrations order by date of migration files. So if you want to create a relation with a table that exists in 2nd migration file it fails.

I faced the same problem, so I created one more migration file at last to specify all relations.

Schema::table('properties', function(Blueprint $table) {
        $table->foreign('user')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('area')->references('id')->on('areas')->onDelete('cascade');
        $table->foreign('city')->references('id')->on('cities')->onDelete('cascade');
        $table->foreign('type')->references('id')->on('property_types')->onDelete('cascade');
    });

    Schema::table('areas', function(Blueprint $table) {
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
    });

How to negate specific word in regex?

The accepted answer is nice but is really a work-around for the lack of a simple sub-expression negation operator in regexes. This is why grep --invert-match exits. So in *nixes, you can accomplish the desired result using pipes and a second regex.

grep 'something I want' | grep --invert-match 'but not these ones'

Still a workaround, but maybe easier to remember.

How do I get the dialer to open with phone number displayed?

Okay, it is going to be extremely late answer to this question. But here is just one sample if you want to do it in Kotlin.

val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:<number>")
startActivity(intent)

Thought it might help someone.

How to use split?

According to MDN, the split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.

Example

var str = 'Hello my friend'

var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]

In your case

var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]

console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

How do I catch a numpy warning like it's an exception (not just for testing)?

Remove warnings.filterwarnings and add:

numpy.seterr(all='raise')

How to declare an array of strings in C++?

One possiblity is to use a NULL pointer as a flag value:

const char *list[] = {"dog", "cat", NULL};
for (char **iList = list; *iList != NULL; ++iList)
{
    cout << *iList;
}

Set HTML element's style property in javascript

I'd like to note that it's usually preferable to change the class of the node instead of it's style and let CSS handle what that means.

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

For those using Microsoft products with a web.config file:

Merge this with your web.config.

To allow on any domain replace value="domain" with value="*"

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.webserver>
    <httpprotocol>
      <customheaders>
        <add name="Access-Control-Allow-Origin" value="domain" />
      </customheaders>
    </httpprotocol>
  </system.webserver>
</configuration>

If you don't have permission to edit web.config, then add this line in your server-side code.

Response.AppendHeader("Access-Control-Allow-Origin", "domain");

Upgrading PHP in XAMPP for Windows?

I just upgrade my old XAMPP portable with PHP 5.3.X(Include Mercury & FileZilla & Tomcat) to XAMPP portable with PHP 5.6.X ( Include previous versions ) ...
My way:

  1. First download last xampp portable(my using version: xampp-portable-win32-5.6.14-3-VC11Direct Download Link) Last XAMPP
  2. Extract new download file to drive d , because new version dont have mercury,filezilla,tomcat in it , then i copy these packages from my old version to new one
  3. Now on old xampp first copy all htdocs files to new xampp htdocs
  4. Now on old xampp backup all of database in 5 two 10 separated sql files
  5. Now on new xampp going and change some settings like max_upload_size and etc on php.ini and also in /apache/conf/extra/httpd-xampp.conf
  6. Now delete ( make a rar archive and delete ) it , and copy new xampp from drive D to drive C
  7. Now start new xampp , going to phpmyadmin , create a user and password that i use in previous xampp and add all privileges that user.
  8. Now going to import tab on phpmyadmin and separately import sql files.
  9. Now i test xampp with all new features in drive C

NOTE
On Export database tab on phpmyadmin, select UTF-8 Character and check Disable foreign key checks checkbox
and on import tab uncheck Enable foreign key checks.

How to append text to an existing file in Java?

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

Java 7+

For a one-time task, the Files class makes this easy:

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:

private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        CREATE, APPEND
    );
}

However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Notes:

  • The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
  • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

Older Java

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Exception Handling

If you need robust exception handling for older Java, it gets very verbose:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

Using Docker-Compose, how to execute multiple commands

There are many great answers in this thread already, however, I found that a combination of a few of them seemed to work best, especially for Debian based users.

services:
  db:
    . . . 
  web:
    . . .
    depends_on:
       - "db"
    command: >      
      bash -c "./wait-for-it.sh db:5432 -- python manage.py makemigrations
      && python manage.py migrate
      && python manage.py runserver 0.0.0.0:8000"

Prerequisites: add wait-for-it.sh to your project directory.

Warning from the docs: "(When using wait-for-it.sh) in production, your database could become unavailable or move hosts at any time ... (This solution is for people that) don’t need this level of resilience."

Export a graph to .eps file with R

If you are using ggplot2 to generate a figure, then a ggsave(file="name.eps") will also work.

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

How to import a csv file into MySQL workbench?

In the navigator under SCHEMAS, right click your schema/database and select "Table Data Import Wizard"

Works for mac too.

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

In case the remote repository is not empty (this is the case if you are using IBM DevOps on hub.jazz.net) then you need to use the following sequence:

cd <localDir>
git init
git add -A .
git pull <url> master
git commit -m "message"
git remote add origin <url>
git push

EDIT 30th Jan 17: Please see comments below, make sure you are on the correct repo!

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

Split string with PowerShell and do something with each token

-split outputs an array, and you can save it to a variable like this:

$a = -split 'Once  upon    a     time'
$a[0]

Once

Another cute thing, you can have arrays on both sides of an assignment statement:

$a,$b,$c = -split 'Once  upon    a'
$c

a

Can I change the checkbox size using CSS?

Preview:
http://jsfiddle.net/h4qka9td/

_x000D_
_x000D_
*,*:after,*:before {_x000D_
  -webkit-box-sizing: border-box;_x000D_
  -moz-box-sizing: border-box;_x000D_
  box-sizing: border-box;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.switch {_x000D_
  margin: 50px auto;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.switch label {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  position: relative;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
.switch input {_x000D_
  top: 0; _x000D_
  right: 0; _x000D_
  bottom: 0; _x000D_
  left: 0;_x000D_
  opacity: 0;_x000D_
  z-index: 100;_x000D_
  position: absolute;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
/* DEMO 3 */_x000D_
_x000D_
.switch.demo3 {_x000D_
  width: 180px;_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.switch.demo3 label {_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: #a5a39d;_x000D_
  border-radius: 40px;_x000D_
  box-shadow:_x000D_
      inset 0 3px 8px 1px rgba(0,0,0,0.2),_x000D_
      0 1px 0 rgba(255,255,255,0.5);_x000D_
}_x000D_
_x000D_
.switch.demo3 label:after {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
  top: -8px; right: -8px; bottom: -8px; left: -8px;_x000D_
  border-radius: inherit;_x000D_
  background: #ababab;_x000D_
  background: -moz-linear-gradient(#f2f2f2, #ababab);_x000D_
  background: -ms-linear-gradient(#f2f2f2, #ababab);_x000D_
  background: -o-linear-gradient(#f2f2f2, #ababab);_x000D_
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#ababab));_x000D_
  background: -webkit-linear-gradient(#f2f2f2, #ababab);_x000D_
  background: linear-gradient(#f2f2f2, #ababab);_x000D_
  box-shadow: 0 0 10px rgba(0,0,0,0.3),_x000D_
        0 1px 1px rgba(0,0,0,0.25);_x000D_
}_x000D_
_x000D_
.switch.demo3 label:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
  top: -18px; right: -18px; bottom: -18px; left: -18px;_x000D_
  border-radius: inherit;_x000D_
  background: #eee;_x000D_
  background: -moz-linear-gradient(#e5e7e6, #eee);_x000D_
  background: -ms-linear-gradient(#e5e7e6, #eee);_x000D_
  background: -o-linear-gradient(#e5e7e6, #eee);_x000D_
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#e5e7e6), to(#eee));_x000D_
  background: -webkit-linear-gradient(#e5e7e6, #eee);_x000D_
  background: linear-gradient(#e5e7e6, #eee);_x000D_
  box-shadow:_x000D_
      0 1px 0 rgba(255,255,255,0.5);_x000D_
  -webkit-filter: blur(1px);_x000D_
  -moz-filter: blur(1px);_x000D_
  -ms-filter: blur(1px);_x000D_
  -o-filter: blur(1px);_x000D_
  filter: blur(1px);_x000D_
}_x000D_
_x000D_
.switch.demo3 label i {_x000D_
  display: block;_x000D_
  height: 100%;_x000D_
  width: 60%;_x000D_
  border-radius: inherit;_x000D_
  background: silver;_x000D_
  position: absolute;_x000D_
  z-index: 2;_x000D_
  right: 40%;_x000D_
  top: 0;_x000D_
  background: #b2ac9e;_x000D_
  background: -moz-linear-gradient(#f7f2f6, #b2ac9e);_x000D_
  background: -ms-linear-gradient(#f7f2f6, #b2ac9e);_x000D_
  background: -o-linear-gradient(#f7f2f6, #b2ac9e);_x000D_
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#f7f2f6), to(#b2ac9e));_x000D_
  background: -webkit-linear-gradient(#f7f2f6, #b2ac9e);_x000D_
  background: linear-gradient(#f7f2f6, #b2ac9e);_x000D_
  box-shadow:_x000D_
      inset 0 1px 0 white,_x000D_
      0 0 8px rgba(0,0,0,0.3),_x000D_
      0 5px 5px rgba(0,0,0,0.2);_x000D_
}_x000D_
_x000D_
.switch.demo3 label i:after {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  left: 15%;_x000D_
  top: 25%;_x000D_
  width: 70%;_x000D_
  height: 50%;_x000D_
  background: #d2cbc3;_x000D_
  background: -moz-linear-gradient(#cbc7bc, #d2cbc3);_x000D_
  background: -ms-linear-gradient(#cbc7bc, #d2cbc3);_x000D_
  background: -o-linear-gradient(#cbc7bc, #d2cbc3);_x000D_
  background: -webkit-gradient(linear, 0 0, 0 100%, from(#cbc7bc), to(#d2cbc3));_x000D_
  background: -webkit-linear-gradient(#cbc7bc, #d2cbc3);_x000D_
  background: linear-gradient(#cbc7bc, #d2cbc3);_x000D_
  border-radius: inherit;_x000D_
}_x000D_
_x000D_
.switch.demo3 label i:before {_x000D_
  content: "off";_x000D_
  text-transform: uppercase;_x000D_
  font-style: normal;_x000D_
  font-weight: bold;_x000D_
  color: rgba(0,0,0,0.4);_x000D_
  text-shadow: 0 1px 0 #bcb8ae, 0 -1px 0 #97958e;_x000D_
  font-family: Helvetica, Arial, sans-serif;_x000D_
  font-size: 24px;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  margin-top: -12px;_x000D_
  right: -50%;_x000D_
}_x000D_
_x000D_
.switch.demo3 input:checked ~ label {_x000D_
  background: #9abb82;_x000D_
}_x000D_
_x000D_
.switch.demo3 input:checked ~ label i {_x000D_
  right: -1%;_x000D_
}_x000D_
_x000D_
.switch.demo3 input:checked ~ label i:before {_x000D_
  content: "on";_x000D_
  right: 115%;_x000D_
  color: #82a06a;_x000D_
  text-shadow: _x000D_
    0 1px 0 #afcb9b,_x000D_
    0 -1px 0 #6b8659;_x000D_
}
_x000D_
<div class="switch demo3">_x000D_
  <input type="checkbox">_x000D_
  <label><i></i>_x000D_
  </label>_x000D_
</div>_x000D_
_x000D_
<div class="switch demo3">_x000D_
  <input type="checkbox" checked>_x000D_
  <label><i></i>_x000D_
  </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

set height of imageview as matchparent programmatically

You can try this incase you would like to match parent. The dimensions arrangement is width and height inorder

web = new WebView(this);
        web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

How to send an email with Python?

As far your code is concerned, there doesn't seem to be anything fundamentally wrong with it except that, it is unclear how you're actually calling that function. All I can think of is that when your server is not responding then you will get this SMTPServerDisconnected error. If you lookup the getreply() function in smtplib (excerpt below), you will get an idea.

def getreply(self):
    """Get a reply from the server.

    Returns a tuple consisting of:

      - server response code (e.g. '250', or such, if all goes well)
        Note: returns -1 if it can't read response code.

      - server response string corresponding to response code (multiline
        responses are converted to a single, multiline string).

    Raises SMTPServerDisconnected if end-of-file is reached.
    """

check an example at https://github.com/rreddy80/sendEmails/blob/master/sendEmailAttachments.py that also uses a function call to send an email, if that's what you're trying to do (DRY approach).

How do I get a substring of a string in Python?

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

Python calls this concept "slicing" and it works on more than just strings. Take a look here for a comprehensive introduction.

Platform.runLater and Task in JavaFX

  • Platform.runLater: If you need to update a GUI component from a non-GUI thread, you can use that to put your update in a queue and it will be handled by the GUI thread as soon as possible.
  • Task implements the Worker interface which is used when you need to run a long task outside the GUI thread (to avoid freezing your application) but still need to interact with the GUI at some stage.

If you are familiar with Swing, the former is equivalent to SwingUtilities.invokeLater and the latter to the concept of SwingWorker.

The javadoc of Task gives many examples which should clarify how they can be used. You can also refer to the tutorial on concurrency.

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

TypeError: 'module' object is not callable

Short answer: You are calling a file/directory as a function instead of real function

Read on:

This kind of error happens when you import module thinking it as function and call it. So in python module is a .py file. Packages(directories) can also be considered as modules. Let's say I have a create.py file. In that file I have a function like this:

#inside create.py
def create():
  pass

Now, in another code file if I do like this:

#inside main.py file
import create
create() #here create refers to create.py , so create.create() would work here

It gives this error as am calling the create.py file as a function. so I gotta do this:

from create import create
create() #now it works.

Hope that helps! Happy Coding!

Access files stored on Amazon S3 through web browser

Filestash is the perfect tool for that:

  1. login to your bucket from https://www.filestash.app/s3-browser.html:

enter image description here

  1. create a shared link:

enter image description here

  1. Share it with the world

Also Filestash is open source. (Disclaimer: I am the author)

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

Check the level of collation that is mismatched (server, database,table,column,character).

If it is the server, these steps helped me once:

  1. Stop the server
  2. Find your sqlservr.exe tool
  3. Run this command:

    sqlservr -m -T4022 -T3659 -s"name_of_insance" -q "name_of_collation"

  4. Start your sql server:

    net start name_of_instance

  5. Check the collation of your server again.

Here is more info:

https://www.mssqltips.com/sqlservertip/3519/changing-sql-server-collation-after-installation/

Creating a JSON response using Django and Python

I usually use a dictionary, not a list to return JSON content.

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'

Pre-Django 1.7 you'd return it like this:

return HttpResponse(json.dumps(response_data), content_type="application/json")

For Django 1.7+, use JsonResponse as shown in this SO answer like so :

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

In JPA 2, using a CriteriaQuery, how to count results

With Spring Data Jpa, we can use this method:

    /*
     * (non-Javadoc)
     * @see org.springframework.data.jpa.repository.JpaSpecificationExecutor#count(org.springframework.data.jpa.domain.Specification)
     */
    @Override
    public long count(@Nullable Specification<T> spec) {
        return executeCountQuery(getCountQuery(spec, getDomainClass()));
    }

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer

Spring Data Rest - _links

DLL References in Visual C++

You need to do a couple of things to use the library:

  1. Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2

  2. Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.

  3. You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.

After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)

Cheers!

EDIT

Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.

Check if page gets reloaded or refreshed in JavaScript

?????? window.performance.navigation.type is deprecated, pls see ???? ????????'s answer


A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers.

It uses the Navigation Timing API.

_x000D_
_x000D_
//check for Navigation Timing API support
if (window.performance) {
  console.info("window.performance works fine on this browser");
}
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
  console.info( "This page is reloaded" );
} else {
  console.info( "This page is not reloaded");
}
_x000D_
_x000D_
_x000D_

source : https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API

Python - abs vs fabs

math.fabs() converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.

In addition to floats, abs() also works with integers and complex numbers. Its return type depends on the type of its argument.

In [7]: type(abs(-2))
Out[7]: int

In [8]: type(abs(-2.0))
Out[8]: float

In [9]: type(abs(3+4j))
Out[9]: float

In [10]: type(math.fabs(-2))
Out[10]: float

In [11]: type(math.fabs(-2.0))
Out[11]: float

In [12]: type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))

TypeError: can't convert complex to float

Remove title in Toolbar in appcompat-v7

The correct way to hide title/label of ToolBar the following codes:

  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(null);

How to add/update child entities when updating a parent entity in EF

There are a few projects out there that make the interaction between the client and the server easier as far as it concerns saving an entire object graph.

Here are two you'd want to look at:

Both the projects above take recognize the disconnected entities when it's returned to the server, detect and save the changes, and return to the client affected data.

ERROR: Error 1005: Can't create table (errno: 121)

I searched quickly for you, and it brought me here. I quote:

You will get this message if you're trying to add a constraint with a name that's already used somewhere else

To check constraints use the following SQL query:

SELECT
    constraint_name,
    table_name
FROM
    information_schema.table_constraints
WHERE
    constraint_type = 'FOREIGN KEY'
AND table_schema = DATABASE()
ORDER BY
    constraint_name;

Look for more information there, or try to see where the error occurs. Looks like a problem with a foreign key to me.

How to detect the screen resolution with JavaScript?

original answer

Yes.

window.screen.availHeight
window.screen.availWidth

update 2017-11-10

From Tsunamis in the comments:

To get the native resolution of i.e. a mobile device you have to multiply with the device pixel ratio: window.screen.width * window.devicePixelRatio and window.screen.height * window.devicePixelRatio. This will also work on desktops, which will have a ratio of 1.

And from Ben in another answer:

In vanilla JavaScript, this will give you the AVAILABLE width/height:

window.screen.availHeight
window.screen.availWidth

For the absolute width/height, use:

window.screen.height
window.screen.width

AWS ssh access 'Permission denied (publickey)' issue

There are 2 steps to be connected:

Chmod 400 on your private key, like this the others cannot access to your key:

chmod 400 toto.pem

To connect to your instance in SSH, you need to know the public IP address of your instance :

ssh -i toto.pem [email protected]

Hope it helps !

Change font color and background in html on mouseover

You'd better use CSS for this:

td{
    background-color:black;
    color:white;
}
td:hover{
    background-color:white;
    color:black;
}

If you want to use these styles for only a specific set of elements, you should give your td a class (or an ID, if it's the only element which'll have that style).

Example :

HTML

<td class="whiteHover"></td>

CSS

.whiteHover{
    /* Same style as above */
}

Here's a reference on MDN for :hover pseudo class.

Deserialize a json string to an object in python

I prefer to add some checking of the fields, e.g. so you can catch errors like when you get invalid json, or not the json you were expecting, so I used namedtuples:

from collections import namedtuple
payload = namedtuple('payload', ['action', 'method', 'data'])
def deserialize_payload(json):
    kwargs =  dict([(field, json[field]) for field in payload._fields]) 
    return payload(**kwargs)

this will let give you nice errors when the json you are parsing does not match the thing you want it to parse

>>> json = {"action":"print","method":"onData","data":"Madan Mohan"}
>>> deserialize_payload(json)
payload(action='print', method='onData', data='Madan Mohan')
>>> badjson = {"error":"404","info":"page not found"}
>>> deserialize_payload(badjson)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in deserialize_payload
KeyError: 'action'

if you want to parse nested relations, e.g. '{"parent":{"child":{"name":"henry"}}}' you can still use the namedtuples, and even a more reusable function

Person = namedtuple("Person", ['parent'])
Parent = namedtuple("Parent", ['child'])
Child = namedtuple('Child', ['name'])
def deserialize_json_to_namedtuple(json, namedtuple):
    return namedtuple(**dict([(field, json[field]) for field in namedtuple._fields]))

def deserialize_person(json):
     json['parent']['child']  = deserialize_json_to_namedtuple(json['parent']['child'], Child)
     json['parent'] =  deserialize_json_to_namedtuple(json['parent'], Parent) 
     person = deserialize_json_to_namedtuple(json, Person)
     return person

giving you

>>> deserialize_person({"parent":{"child":{"name":"henry"}}})
Person(parent=Parent(child=Child(name='henry')))
>>> deserialize_person({"error":"404","info":"page not found"})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in deserialize_person
KeyError: 'parent'

How to detect current state within directive

If you are using ui-router, try $state.is();

You can use it like so:

$state.is('stateName');

Per the documentation:

$state.is ... similar to $state.includes, but only checks for the full state name.

Remove a file from a Git repository without deleting it from the local filesystem

Also, if you have commited sensitive data (e.g. a file containing passwords), you should completely delete it from the history of the repository. Here's a guide explaining how to do that: http://help.github.com/remove-sensitive-data/

Count how many rows have the same value

Try this Query

select NUM, count(1) as count 
from tbl 
where num = 1
group by NUM
--having count(1) (You condition)

SQL FIDDLE

Groovy executing shell commands

command = "ls *"

def execute_state=sh(returnStdout: true, script: command)

but if the command failure the process will terminate

What is ":-!!" in C code?

This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.

The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO, rather than ...ON_ZERO. (There have been occasional discussions about whether this is a confusing name.)

You should read the expression like this:

sizeof(struct { int: -!!(e); }))
  1. (e): Compute expression e.

  2. !!(e): Logically negate twice: 0 if e == 0; otherwise 1.

  3. -!!(e): Numerically negate the expression from step 2: 0 if it was 0; otherwise -1.

  4. struct{int: -!!(0);} --> struct{int: 0;}: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.

  5. struct{int: -!!(1);} --> struct{int: -1;}: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.

So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof that field, so we get a size_t with the appropriate width (which will be zero in the case where e is zero).


Some people have asked: Why not just use an assert?

keithmo's answer here has a good response:

These macros implement a compile-time test, while assert() is a run-time test.

Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.

Understanding generators in Python

I believe the first appearance of iterators and generators were in the Icon programming language, about 20 years ago.

You may enjoy the Icon overview, which lets you wrap your head around them without concentrating on the syntax (since Icon is a language you probably don't know, and Griswold was explaining the benefits of his language to people coming from other languages).

After reading just a few paragraphs there, the utility of generators and iterators might become more apparent.

how to display a div triggered by onclick event

Here you go:

div{
    display: none;
}

document.querySelector("button").addEventListener("click", function(){
    document.querySelector("div").style.display = "block";
});

<div>blah blah blah</div>
<button>Show</button>

LIVE DEMO: http://jsfiddle.net/DerekL/p78Qq/

Set specific precision of a BigDecimal

Try this code ...

    Integer perc = 5;
    BigDecimal spread = BigDecimal.ZERO; 
    BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
    System.out.println(perc);

Result: 0.00000

Get property value from C# dynamic object by string (reflection?)

you can use "dynamicObject.PropertyName.Value" to get value of dynamic property directly.

Example :

d.property11.Value

How do I use the built in password reset/change views with my own templates

You just need to wrap the existing functions and pass in the template you want. For example:

from django.contrib.auth.views import password_reset

def my_password_reset(request, template_name='path/to/my/template'):
    return password_reset(request, template_name)

To see this just have a look at the function declartion of the built in views:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L74

Best way to store a key=>value array in JavaScript?

Objects inside an array:

var cars = [
        { "id": 1, brand: "Ferrari" }
        , { "id": 2, brand: "Lotus" }
        , { "id": 3, brand: "Lamborghini" }
    ];

Center text output from Graphics.DrawString()

Here's some code. This assumes you are doing this on a form, or a UserControl.

Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");

int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));

From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.

Get first date of current month in java

tl;dr

How to get the first date of the current month correctly?

LocalDate.now()
         .with( TemporalAdjusters.firstDayOfMonth() )

Or…

YearMonth.now().atDay( 1 )

Or…

LocalDate.now().with ( ChronoField.DAY_OF_MONTH , 1 )

java.time

The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.

The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.

LocalDate

For a date-only value, without time-of-day, use the LocalDate class. While LocalDate has no assigned time zone, we must specify a time zone in order to determine a date such as “today”. For example, a new day dawns earlier in Paris than in Montréal.

Time zone is crucial in determining today's date. For any given moment, the date varies around the world by zone. Omitting the time zone means the JVM’s current time zone is automatically applied in determining the current date. Any code in the JVM can change the default at runtime, so you are walking on shifting sands. Better to specify your desired/expected time zone explicitly than rely implicitly on the current default.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
LocalDate today = LocalDate.now ( zoneId );
LocalDate firstOfCurrentMonth = today.with ( ChronoField.DAY_OF_MONTH , 1 );

Dump to console.

System.out.println ( "For zoneId: " + zoneId + " today is: " + today + " and first of this month is " + firstOfCurrentMonth );

For zoneId: America/Montreal today is: 2015-11-08 and first of this month is 2015-11-01

Alternatively, use a TemporalAdjuster. For your purpose, you will find handy implementations in the TemporalAdjusters class (note plural s), specifically firstDayOfMonth.

LocalDate firstOfCurrentMonth = today.with( TemporalAdjusters.firstDayOfMonth() ) ;

ZonedDateTime

If you need a time of day, remember that 00:00:00.000 is not always the first moment of the day because of Daylight Saving Time (DST) and perhaps other anomalies. So let java.time determine the correct time of the first moment of the day.

ZonedDateTime zdt = firstOfCurrentMonth.atStartOfDay ( zoneId );

2015-11-01T00:00-04:00[America/Montreal]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Android java.lang.NoClassDefFoundError

After Checking Java Build Path, Then add lines of code in manifest file.

<meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

How can I filter a date of a DateTimeField in Django?

Such lookups are implemented in django.views.generic.date_based as follows:

{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min),
                            datetime.datetime.combine(date, datetime.time.max))} 

Because it is quite verbose there are plans to improve the syntax using __date operator. Check "#9596 Comparing a DateTimeField to a date is too hard" for more details.

Is there a way to access the "previous row" value in a SELECT statement?

The selected answer will only work if there are no gaps in the sequence. However if you are using an autogenerated id, there are likely to be gaps in the sequence due to inserts that were rolled back.

This method should work if you have gaps

declare @temp (value int, primaryKey int, tempid int identity)
insert value, primarykey from mytable order by  primarykey

select t1.value - t2.value from @temp  t1
join @temp  t2 
on t1.tempid = t2.tempid - 1

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

How to display my location on Google Maps for Android API v2

Call GoogleMap.setMyLocationEnabled(true) in your Activity, and add this 2 lines code in the Manifest:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

How do I get the web page contents from a WebView?

This is an answer based on jluckyiv's, but I think it is better and simpler to change Javascript as follows.

browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

What is the best (idiomatic) way to check the type of a Python variable?

That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:

{type(str()): do_something_with_a_string,
 type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()

A bit more concise and pythonic wouldn't you say?


Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer:

{str: do_something_with_a_string,
 dict: do_something_with_a_dict}.get(type(x), errorhandler)()

Delete all data rows from an Excel table (apart from the first)

I wanted to keep the formulas in place, which the above code did not do.

Here's what I've been doing, note that this leaves one empty row in the table.

Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)

On Error Resume Next

if not KeepFormulas then
    Table.DataBodyRange.clearcontents
end if

Table.DataBodyRange.Rows.Delete

On Error GoTo 0

End Sub

(PS don't ask me why!)

How to add an image in Tkinter?

This code works for me, also you should consider if you have any other button or labels in that window and you not use .place() it will not work properly.

from Tkinter import*
from PIL import Image, ImageTk

img  = Image.open("path/x.png") 
photo=ImageTk.PhotoImage(img)
lab=Label(image=photo).place(x=50,y=50)

How do you extract a column from a multi-dimensional array?

Just use transpose(), then you can get the colummns as easy as you get rows

matrix=np.array(originalMatrix).transpose()
print matrix[NumberOfColum]

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

Add object to ArrayList at specified index

I think the solution from medopal is what you are looking for.

But just another alternative solution is to use a HashMap and use the key (Integer) to store positions.

This way you won't need to populate it with nulls etc initially, just stick the position and the object in the map as you go along. You can write a couple of lines at the end to convert it to a List if you need it that way.

Base table or view not found: 1146 Table Laravel 5

I also had this problem when doing migration => after performing php artisan migrate:refresh --seed command

"Base table or view not found: 1146 Table posts do not exist" and I solved it, I was using "soft deletes" in a separate migration file, and my original migration for "posts" table which was responsible for creating the "posts" table was performing after the "soft deletes" migration in the database\migration folder, I simply needed to rename the "posts" migration file name and put it before "softdeletes" migration to perform sooner. the do the migration again => php artisan migrate:refresh --seed it's done.

How to send email in ASP.NET C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Globalization;
    using System.Text.RegularExpressions;
    
    /// <summary>
    /// Summary description for RegexUtilities
    /// </summary>
    public class RegexUtilities
    {
        bool InValid = false;
    
        public bool IsValidEmail(string strIn)
        {
            InValid = false;
            if (String.IsNullOrEmpty(strIn))
                return false;
    
            // Use IdnMapping class to convert Unicode domain names.
            strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
            if (InValid)
                return false;
    
            // Return true if strIn is in valid e-mail format. 
            return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                   RegexOptions.IgnoreCase);
        }
    
        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();
    
            string domainName = match.Groups[2].Value;
            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                InValid = true;
            }
            return match.Groups[1].Value + domainName;
        }
    
    }



 private void GetSendEmInfo()
    {
        #region For Get All Type Email Informations..!!
        IPL.DoId = ddlName.SelectedValue;
        DataTable dt = IdBL.GetEmailS(IPL);
        if (dt.Rows.Count > 0)
        {
            hid_MailId.Value = dt.Rows[0]["MailId"].ToString();
            hid_UsedPName.Value = dt.Rows[0]["UName"].ToString();
            hid_EmailSubject.Value = dt.Rows[0]["EmailSubject"].ToString();
            hid_EmailBody.Value = dt.Rows[0]["EmailBody"].ToString();
            hid_EmailIdName.Value = dt.Rows[0]["EmailIdName"].ToString();
            hid_EmPass.Value = dt.Rows[0]["EPass"].ToString();
            hid_SeName.Value = dt.Rows[0]["SenName"].ToString();
            hid_TNo.Value = dt.Rows[0]["TeNo"].ToString();
            hid_EmaLimit.Value = dt.Rows[0]["EmailLimit"].ToString();
            hidlink.Value = dt.Rows[0][link"].ToString();
        }
        #endregion

        #region For Set Some Local Variables..!!
        int StartLmt, FinalLmt, SendCurrentMail;
        StartLmt = FinalLmt = SendCurrentMail = 0;
        bool Valid_LimitMail;
        Valid_LimitMail = true;
        /**For Get Finalize Limit For Send Mail**/
        FinalLmt = Convert.ToInt32(hid_EmailmaxLimit.Value);
        #region For Check Email Valid Limits..!!
        if (FinalLmt > 0)
        {
            Valid_LimitMail = true;
        }
        else
        {
            Valid_LimitMail = false;
        }
        #endregion
        /**For Get Finalize Limit For Send Mail**/
        #endregion

        if (Valid_LimitMail == true)
        {
            #region For Send Current Email Status..!!
            bool EmaiValid;
            string CreateFileName;
            string retmailflg = null;
            EmaiValid = false;
            #endregion

            #region For Set Start Limit And FinalLimit Send No Of Email..!!
            mPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
            DataTable dtsendEmail = m1BL.GetEmailSendLog(mPL);
            if (dtsendEmail.Rows.Count > 0)
            {
                StartLmt = Convert.ToInt32(dtsendEmail.Rows[0]["SendNo_Of_Email"].ToString());
            }
            else
            {
                StartLmt = 0;
            }
            #endregion

            #region For Find Grid View Controls..!!
            for (int i = 0; i < GrdEm.Rows.Count; i++)
            {
                #region For Find Grid view Controls..!!
                CheckBox Chk_SelectOne = (CheckBox)GrdEmp.Rows[i].FindControl("chkSingle");
                Label lbl_No = (Label)GrdEmAtt.Rows[i].FindControl("lblGrdCode");
                lblCode.Value = lbl_InNo.Text;

                Label lbl_EmailId = (Label)GrdEomAtt.Rows[i].FindControl("lblGrdEmpEmail");

                #endregion

                /**Region For If Check Box Checked Then**/
                if (Chk_SelectOne.Checked == true)
                {
                    if (!string.IsNullOrEmpty(lbl_EmailId.Text))
                    {
                        #region For When Check Box Checked..!!
                        /**If Start Limit Less Or Equal To Then Condition Performs**/
                        if (StartLmt < FinalLmt)
                        {
                            StartLmt = StartLmt + 1;
                        }
                        else
                        {
                            Valid_LimitMail = false;
                            EmaiValid = false;
                        }
                        /**End Region**/
                        string[] SplitClients_Email = lbl_EmailId.Text.Split(',');
                        string Send_Email, Hold_Email;
                        Send_Email = Hold_Email = "";

                        int CountEmail;/**Region For Count Total Email**/
                        CountEmail = 0;/**First Time Email Counts Zero**/

                        Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
                        /**Region For If Clients Have One Email**/
                        #region For First Emails Send On Client..!!
                        if (SplitClients_Email[0].ToString() != "")
                        {
                            if (EmailRegex.IsValidEmail(Hold_Email))
                            {
                                Send_Email = Hold_Email;
                                CountEmail = 1;
                                EmaiValid = true;
                            }
                            else
                            {
                                EmaiValid = false;
                            }
                        }
                        #endregion
                        /**Region For If Clients Have One Email**/
                        /**Region For If Clients Have Two Email**/

                        /**Region For If Clients Have Two Email**/
                        if (EmaiValid == true)
                        {
                            #region For Create Email Body And Create File Name..!!
                            //fofile = Server.MapPath("PDFs");
                            fofile = Server.MapPath("~/vvv/vvvv/") + "/";
                            CreateFileName = lbl_INo.Text.ToString() + "_1" + ".Pdf";/**Create File Name**/
                            string[] orimail = Send_Email.Split(',');
                            string Billbody, TempInvoiceId;
                            // DateTime dtLstdate = new DateTime(Convert.ToInt32(txtYear.Text), Convert.ToInt32(ddlMonth.SelectedValue), 16);

                            //  DateTime IndtLmt = dtLstdate.AddMonths(1);
                            TempInvoiceId = "";

                            //byte[] Buffer = Encrypt.Encryptiondata(lbl_InvoiceNo.Text.ToString());
                            //TempInvoiceId = Convert.ToBase64String(Buffer);


                            #region Create Encrypted Path


                            byte[] EncCode = Encrypt.Encryptiondata(lbl_INo.Text);
                            hidEncrypteCode.Value = Convert.ToBase64String(EncECode);
                            #endregion

                        

                            //#region Create Email Body !!
                            //body = hid_EmailBody.Value.Replace("@greeting", lbl_CoName.Text).Replace("@free", hid_ToNo.Value).Replace("@llnk", "<a style='font-family: Tahoma; font-size: 10pt; color: #800000; font-weight: bold' href='http://1ccccc/ccc/ccc/ccc.aspx?EC=" + hidEncryptedCode.Value+ "' > C cccccccc </a>");
                          

                            body = hid_EmailBody.Value.Replace("@greeting", "Hii").Replace("@No", hid_No.Value);/*For Mail*/
                            //#endregion



                            #region For Email Sender Informations..!!
                            for (int j = 0; j < CountEmail; j++)
                            {
                                //if (File.Exists(fofile + "\\" + CreateFileName))
                                //{
                                #region
                                lbl_EmailId.Text = orimail[j];
                                retmailflg = "";

                                /**Region For Send Email For Clients**/
                                //retmailflg = SendPreMail("Wp From " + lbl_CName.Text + "", body, lbl_EmailId.Text, lbl_IeNo.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                retmailflg = SendPreMail(hid_EmailSubject.Value, Body, lbl_EmailId.Text, lbl_No.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                /**End Region**/

                                /**Region For Create Send Email Log  When Email Send Successfully**/
                                if (retmailflg == "True")
                                {
                                    SendCurrentMail = Convert.ToInt32(SendCurrentMail) + 1;
                                    StartLmt = Convert.ToInt32(StartLmt) + 1;

                                    if (SendCurrentMail > 0)
                                    {
                                        CreateEmailLog(lbl_InNo.Text, StartLmt, hid_EmailIdName.Value, lbl_EmailId.Text);
                                        
                                    }
                                }
                                

                                /**End Region**/
                                #endregion
                                //}
                            }
                            #endregion
                        }
                        #endregion
                    }
                }
                /**End Region**/
            }
            #endregion

        }
       
    }
    private void CreateEmailLog(string UniqueId, int StartLmt, string FromEmailId, string TotxtEmailId)
    {
        FPL.EmailId_From = FromEmailId;
        FPL.To_EmailId = TotxtEmailId;
        FPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
        FPL.EmailUniqueId = UniqueId;
        FPL.SendNo_Of_Email = StartLmt.ToString();
        FPL.LoginUserId = Session["LoginUserId"].ToString();
        int i = FBL.InsertEmaDoc(FPL);
    }

    public string SendPreMail(string emsub, string embody, string EmailId, string FileId, string EmailFromId, string Password)
    {
        string retval = "False";
        try
        {
            string emailBody, emailSubject, emailToList, emailFrom,
            accountPassword, smtpServer;
            bool enableSSL;
            int port;

            emailBody = embody;
            emailSubject = emsub;
            emailToList = EmailId;
            emailFrom = EmailFromId;
            accountPassword = Password;
            smtpServer = "smtp.gmail.com";
            enableSSL = true;
            port = 587;

            string crefilename;
            string fofile;
            fofile = Server.MapPath("PDF");
            crefilename = FileId + ".Pdf";

            string[] att = { crefilename };

            string retemail, insertqry;
            retemail = "";

            retemail = SendEmail(emailBody, emailSubject, emailFrom, emailToList, att, smtpServer, enableSSL, accountPassword, port);

            if (retemail == "True")
            {

                retval = retemail;
            }
        }
        catch
        {
            retval = "False";
        }
        finally
        {

        }
        return retval;
    }

    public string SendEmail(string emailBody, string emailSubject, string emailFrom, string emailToList, string[] attachedFiles, string smtpIPAddress, bool enableSSL, string accountPassword, int port)
    {
        MailMessage mail = new MailMessage();
        string retflg;
        retflg = "False";
        try
        {
            mail.From = new MailAddress(emailFrom);
            if (emailToList.Contains(";"))
            {
                emailToList = emailToList.Replace(";", ",");
            }
            mail.To.Add(emailToList);

            mail.Subject = emailSubject;
            mail.IsBodyHtml = true;
            mail.Body = emailBody;


            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            NetworkCredential NetworkCred = new NetworkCredential(emailFrom, accountPassword);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mail);
            retflg = "True";

        }
        catch
        {
            retflg = "False";
        }
        finally
        {
            mail.Dispose();
        }
        return retflg;
    }

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

Javascript format date / time

For the date part:(month is 0-indexed while days are 1-indexed)

var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' +  date.getFullYear());

for the time you'll want to create a function to test different situations and convert.

jquery data selector

You can set a data-* attribute on an elm using attr(), and then select using that attribute:

var elm = $('a').attr('data-test',123); //assign 123 using attr()
elm = $("a[data-test=123]"); //select elm using attribute

and now for that elm, both attr() and data() will yield 123:

console.log(elm.attr('data-test')); //123
console.log(elm.data('test')); //123

However, if you modify the value to be 456 using attr(), data() will still be 123:

elm.attr('data-test',456); //modify to 456
elm = $("a[data-test=456]"); //reselect elm using new 456 attribute

console.log(elm.attr('data-test')); //456
console.log(elm.data('test')); //123

So as I understand it, seems like you probably should steer clear of intermingling attr() and data() commands in your code if you don't have to. Because attr() seems to correspond directly with the DOM whereas data() interacts with the 'memory', though its initial value can be from the DOM. But the key point is that the two are not necessarily in sync at all.

So just be careful.

At any rate, if you aren't changing the data-* attribute in the DOM or in the memory, then you won't have a problem. Soon as you start modifying values is when potential problems can arise.

Thanks to @Clarence Liu to @Ash's answer, as well as this post.

proper way to sudo over ssh

Depending on your usage, I had success with the following:

ssh root@server "script"

This will prompt for the root password and then execute the command correctly.

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I had the same problem and for me it was because the vc2010 redist x86 was too recent.

Check your temp folder (C:\Users\\AppData\Local\Temp) for the most recent file named

Microsoft Visual C++ 2010 x64 Redistributable Setup_20110608_xxx.html ##

and check if you have the following error

Installation Blockers:

A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine.

Final Result: Installation failed with error code: (0x000013EC), "A StopBlock was hit or a System >Requirement was not met." (Elapsed time: 0 00:00:00).

then go to Control Panel>Program & Features and uninstall all the

Microsoft Visual C++ 2010 x86/x64 redistributable - 10.0.(number over 30319)

After successful installation of DXSDK, simply run Windows Update and it will update the redistributables back to the latest version.

Calculating moving average

In order to complement the answer of cantdutchthis and Rodrigo Remedio;

moving_fun <- function(x, w, FUN, ...) {
  # x: a double vector
  # w: the length of the window, i.e., the section of the vector selected to apply FUN
  # FUN: a function that takes a vector and return a summarize value, e.g., mean, sum, etc.
  # Given a double type vector apply a FUN over a moving window from left to the right, 
  #    when a window boundary is not a legal section, i.e. lower_bound and i (upper bound) 
  #    are not contained in the length of the vector, return a NA_real_
  if (w < 1) {
    stop("The length of the window 'w' must be greater than 0")
  }
  output <- x
  for (i in 1:length(x)) {
     # plus 1 because the index is inclusive with the upper_bound 'i'
    lower_bound <- i - w + 1
    if (lower_bound < 1) {
      output[i] <- NA_real_
    } else {
      output[i] <- FUN(x[lower_bound:i, ...])
    }
  }
  output
}

# example
v <- seq(1:10)

# compute a MA(2)
moving_fun(v, 2, mean)

# compute moving sum of two periods
moving_fun(v, 2, sum)

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

How to save a dictionary to a file?

I would suggest saving your data using the JSON format instead of pickle format as JSON's files are human-readable which makes your debugging easier since your data is small. JSON files are also used by other programs to read and write data. You can read more about it here

You'll need to install the JSON module, you can do so with pip:

pip install json


# To save the dictionary into a file:
json.dump( data, open( "myfile.json", 'w' ) )

This creates a json file with the name myfile.

# To read data from file:
data = json.load( open( "myfile.json" ) )

This reads and stores the myfile.json data in a data object.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I have that problem and my solution is going source folder and run command line: mvn clean install -DskipTests eclipse:eclipse then return eclipse workspace and refresh project. Hope that help!

How to combine paths in Java?

This also works in Java 8 :

Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");

What is a word boundary in regex, does \b match hyphen '-'?

A word boundary, in most regex dialects, is a position between \w and \W (non-word char), or at the beginning or end of a string if it begins or ends (respectively) with a word character ([0-9A-Za-z_]).

So, in the string "-12", it would match before the 1 or after the 2. The dash is not a word character.

Cycles in family tree software

You should have set up the Atreides family (either modern, Dune, or ancient, Oedipus Rex) as a testing case. You don't find bugs by using sanitized data as a test case.

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Consider this snippet of code. Modify as you see fit, or to fit your requirements. You'll need to have Imports statements for System.IO and System.Data.OleDb.

Dim fi As New FileInfo("c:\foo.csv")
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" & fi.DirectoryName

Dim conn As New OleDbConnection(connectionString)
conn.Open()

'the SELECT statement is important here, 
'and requires some formatting to pull dates and deal with headers with spaces.
Dim cmdSelect As New OleDbCommand("SELECT Foo, Bar, FORMAT(""SomeDate"",'YYYY/MM/DD') AS SomeDate, ""SOME MULTI WORD COL"", FROM " & fi.Name, conn)

Dim adapter1 As New OleDbDataAdapter
adapter1.SelectCommand = cmdSelect

Dim ds As New DataSet
adapter1.Fill(ds, "DATA")

myDataGridView.DataSource = ds.Tables(0).DefaultView 
myDataGridView.DataBind
conn.Close()

WebSockets vs. Server-Sent events/EventSource

Here is a talk about the differences between web sockets and server sent events. Since Java EE 7 a WebSocket API is already part of the specification and it seems that server sent events will be released in the next version of the enterprise edition.

What is reflection and why is it useful?

Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

For example, all objects in Java have the method getClass(), which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an Object) - this might seem trivial, but such reflection is not possible in less dynamic languages such as C++. More advanced uses lets you list and call methods, constructors, etc.

Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.

calculating the difference in months between two dates

I would do it like this:

static int TotelMonthDifference(this DateTime dtThis, DateTime dtOther)
{
    int intReturn = 0;

    dtThis = dtThis.Date.AddDays(-(dtThis.Day-1));
    dtOther = dtOther.Date.AddDays(-(dtOther.Day-1));

    while (dtOther.Date > dtThis.Date)
    {
        intReturn++;     
        dtThis = dtThis.AddMonths(1);
    }

    return intReturn;
}

Get querystring from URL using jQuery

Have a look at this Stack Overflow answer.

 function getParameterByName(name, url) {
     if (!url) url = window.location.href;
     name = name.replace(/[\[\]]/g, "\\$&");
     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
         results = regex.exec(url);
     if (!results) return null;
     if (!results[2]) return '';
     return decodeURIComponent(results[2].replace(/\+/g, " "));
 }

You can use the method to animate:

I.e.:

var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

Encoding URL query parameters in Java

if you have only space problem in url. I have used below code and it work fine

String url;
URL myUrl = new URL(url.replace(" ","%20"));

example : url is

www.xyz.com?para=hello sir

then output of muUrl is

www.xyz.com?para=hello%20sir