Programs & Examples On #Clos

Common Lisp Object System

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

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.

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Got a NumberFormatException while trying to parse a text file for objects

The problem might be your split() call. Try just split(" ") without the square brackets.

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.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

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

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

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

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

I disabled Chrome extension "Coupons at Checkout" and this problem was solved.

What is the meaning of "Failed building wheel for X" in pip install?

This may Help you ! ....

Uninstalling pycparser:

pip uninstall pycparser

Reinstall pycparser:

pip install pycparser

I got same error while installing termcolor and I fixed it by reinstalling it .

Flutter: RenderBox was not laid out

i

I used this code to fix the issue of displaying items in the horizontal list.

new Container(
      height: 20,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemCount: array.length,
            itemBuilder: (context, index){
              return array[index];
            },
          ),
        ],
      ),
    );

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

You should just install python 3.6. I tried it and it worked. Just install that version of python and just do the normal download process (pip install pyaudio).

git clone: Authentication failed for <URL>

I'm facing exactly same error when I'm trying to clone a repository on a brand new machine. I'm using Git bash as my Git client. When I ran Git's command to clone a repository it was not prompting me for user id and password which will be used for authentication. It was a fresh machine where not a single credential was cached by Windows credential manager.

As a last resort, I manually added my credentials in credentials manager.

Go to > Control Panel\User Accounts\Credential Manager > Windows Credentials

Click Add a Windows credential link and then Supply the details as shown in the form below and you're done:

enter image description here

I had put the details as below:

Internet or network address: <gitRepoServerNameOrIPAddress>
User Name: MyCompanysDomainName\MyUserName
Password: MyPassword

Next time you run any Git command targeting a repository set up on above address this manually created credential will be used.

It is also important if you have a git command line you close it and reopen it for changes to be applied.

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

More simply in one line:

proxy=192.168.2.1:8080;curl -v example.com

eg. $proxy=192.168.2.1:8080;curl -v example.com

xxxxxxxxx-ASUS:~$ proxy=192.168.2.1:8080;curl -v https://google.com|head -c 15 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0

  • Trying 172.217.163.46:443...
  • TCP_NODELAY set
  • Connected to google.com (172.217.163.46) port 443 (#0)
  • ALPN, offering h2
  • ALPN, offering http/1.1
  • successfully set certificate verify locations:
  • CAfile: /etc/ssl/certs/ca-certificates.crt CApath: /etc/ssl/certs } [5 bytes data]
  • TLSv1.3 (OUT), TLS handshake, Client hello (1): } [512 bytes data]

Authentication plugin 'caching_sha2_password' is not supported

Using MySql 8 I got the same error when connecting my code to the DB, using the pip install mysql-connector-python did solve this error.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

If the mongoDB server is already installed and if you are unable to connect from a remote host then follow the below steps,

Login to your machine, open mongodb configuration file located at /etc/mongod.conf and change the bindIp field to specific ip / 0.0.0.0 , after that restart mongodb server.

    sudo vi /etc/mongod.conf
  • The file should contain the following kind of content:

      systemLog:
          destination: file
          path: "/var/log/mongodb/mongod.log"
          logAppend: true
      storage:
          journal:
              enabled: true
      processManagement:
          fork: true
      net:
          bindIp: 127.0.0.1  // change here to 0.0.0.0
          port: 27017
      setParameter:
          enableLocalhostAuthBypass: false
    
  • Once you change the bindIp, then you have to restart the mongodb, using the following command

      sudo service mongod restart
    
  • Now you'll be able to connect to the mongodb server, from remote server.

Extract Google Drive zip from Google colab notebook

After mounting on drive, use shutil.unpack_archive. It works with almost all archive formats (e.g., “zip”, “tar”, “gztar”, “bztar”, “xztar”) and it's simple:

import shutil
shutil.unpack_archive("filename", "path_to_extract")

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?

It might be related to corruption in Angular Packages or incompatibility of packages.

Please follow the below steps to solve the issue.

Update

ASP.NET Boilerplate suggests here to use yarn because npm has some problems. It is slow and can not consistently resolve dependencies, yarn solves those problems and it is compatible to npm as well.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

Many people have given a fix, so I'll talk about the source of the problem.

According to the exception log:

Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
    at android.app.Activity.onCreate(Activity.java:1081)
    at android.support.v4.app.SupportActivity.onCreate(SupportActivity.java:66)
    at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:297)
    at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84)
    at com.nut.blehunter.ui.DialogContainerActivity.onCreate(DialogContainerActivity.java:43)
    at android.app.Activity.performCreate(Activity.java:7372)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302) 
    at android.app.ActivityThread.-wrap12(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891) 
    at android.os.Handler.dispatchMessage(Handler.java:108) 
    at android.os.Looper.loop(Looper.java:166)

The code that triggered the exception in Activity.java

    //Need to pay attention mActivityInfo.isFixedOrientation() and ActivityInfo.isTranslucentOrFloating(ta)
    if (getApplicationInfo().targetSdkVersion >= O_MR1 && mActivityInfo.isFixedOrientation()) {
        final TypedArray ta = obtainStyledAttributes(com.android.internal.R.styleable.Window);
        final boolean isTranslucentOrFloating = ActivityInfo.isTranslucentOrFloating(ta);
        ta.recycle();

        //Exception occurred
        if (isTranslucentOrFloating) {
            throw new IllegalStateException(
                    "Only fullscreen opaque activities can request orientation");
        }
    }

mActivityInfo.isFixedOrientation():

        /**
        * Returns true if the activity's orientation is fixed.
        * @hide
        */
        public boolean isFixedOrientation() {
            return isFixedOrientationLandscape() || isFixedOrientationPortrait()
                    || screenOrientation == SCREEN_ORIENTATION_LOCKED;
        }
        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        boolean isFixedOrientationPortrait() {
            return isFixedOrientationPortrait(screenOrientation);
        }

        /**
        * Returns true if the activity's orientation is fixed to portrait.
        * @hide
        */
        public static boolean isFixedOrientationPortrait(@ScreenOrientation int orientation) {
            return orientation == SCREEN_ORIENTATION_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_SENSOR_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_REVERSE_PORTRAIT
                    || orientation == SCREEN_ORIENTATION_USER_PORTRAIT;
        }

        /**
        * Determines whether the {@link Activity} is considered translucent or floating.
        * @hide
        */
        public static boolean isTranslucentOrFloating(TypedArray attributes) {
            final boolean isTranslucent = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsTranslucent, false);
            final boolean isSwipeToDismiss = !attributes.hasValue(com.android.internal.R.styleable.Window_windowIsTranslucent)
                                            && attributes.getBoolean(com.android.internal.R.styleable.Window_windowSwipeToDismiss, false);
            final boolean isFloating = attributes.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false);
            return isFloating || isTranslucent || isSwipeToDismiss;
        }

According to the above code analysis, when TargetSdkVersion>=27, when using SCREEN_ORIENTATION_LANDSCAPE, SCREEN_ORIENTATION_PORTRAIT, and other related attributes, the use of windowIsTranslucent, windowIsFloating, and windowSwipeToDismiss topic attributes will trigger an exception.

After the problem is found, you can change the TargetSdkVersion or remove the related attributes of the theme according to your needs.

db.collection is not a function when using MongoClient v3.0

If someone is still trying how to resolve this error, I have done this like below.

const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'mytestingdb';

const retrieveCustomers = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const retrieveCustomer = (db, callback)=>{
    // Get the customers collection
    const collection = db.collection('customers');
    // Find some customers
    collection.find({'name': 'mahendra'}).toArray((err, customers) =>{
        if(err) throw err;
      console.log("Found the following records");
      console.log(customers)
      callback(customers);
    });
}

const insertCustomers = (db, callback)=> {
    // Get the customers collection
    const collection = db.collection('customers');
    const dataArray = [{name : 'mahendra'}, {name :'divit'}, {name : 'aryan'} ];
    // Insert some customers
    collection.insertMany(dataArray, (err, result)=> {
        if(err) throw err;
        console.log("Inserted 3 customers into the collection");
        callback(result);
    });
}

// Use connect method to connect to the server
MongoClient.connect(url,{ useUnifiedTopology: true }, (err, client) => {
  console.log("Connected successfully to server");
  const db = client.db(dbName);
  insertCustomers(db, ()=> {
    retrieveCustomers(db, ()=> {
        retrieveCustomer(db, ()=> {
            client.close();
        });
    });
  });
});

VS 2017 Git Local Commit DB.lock error on every commit

Try to copy the file in to your directory manually (C:\Users\Admin\AppData\Local\Temp\WebSitePublish\digisol--1147805695\obj\Debug\Package\PackageTmp.vs\digisol\v15\Server\sqlite3 )

Failed to run sdkmanager --list with Java 9

Apparently if you use "commandlinetools" version greater than 3.6.0 you may use JDK11+ to install Android SDK components.

They are available here: https://developer.android.com/studio#command-tools

Official issue tracker saying it is fixed: https://issuetracker.google.com/issues/122210344#comment11

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Try using anaconda. I had the same error. One lone option was to build tensorflow from source which took long time. I tried using conda and it worked.

  1. Create a new environment in anaconda.
  2. conda -c conda-forge tensorflow

Then, it worked.

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {
        this.dialog.open(DialogComponent, { disableClose: true });
      }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;
      }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

Angular + Material - How to refresh a data source (mat-table)

Trigger a change detection by using ChangeDetectorRef in the refresh() method just after receiving the new data, inject ChangeDetectorRef in the constructor and use detectChanges like this:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { LanguageModel, LANGUAGE_DATA } from '../../../../models/language.model';
import { LanguageAddComponent } from './language-add/language-add.component';
import { AuthService } from '../../../../services/auth.service';
import { LanguageDataSource } from './language-data-source';
import { LevelbarComponent } from '../../../../directives/levelbar/levelbar.component';
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { MatSnackBar, MatDialog } from '@angular/material';

@Component({
  selector: 'app-language',
  templateUrl: './language.component.html',
  styleUrls: ['./language.component.scss']
})
export class LanguageComponent implements OnInit {
  displayedColumns = ['name', 'native', 'code', 'level'];
  teachDS: any;

  user: any;

  constructor(private authService: AuthService, private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.refresh();
  }

  add() {
    this.dialog.open(LanguageAddComponent, {
      data: { user: this.user },
    }).afterClosed().subscribe(result => {
      this.refresh();
    });
  }

  refresh() {
    this.authService.getAuthenticatedUser().subscribe((res) => {
      this.user = res;
      this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);
      this.changeDetectorRefs.detectChanges();
    });
  }
}

MongoError: connect ECONNREFUSED 127.0.0.1:27017

If you already installed "MongoDB", if you accidentally exit from the MongoDB server, then "restart your system".

This method solved me...

[On Windows only]

And also another method is there:

press:

Windows + R

type:

services.msc

and click "ok", it opens "services" window, and then search for "MongoDB Server" in the list. After you find "MongoDB Server", right-click and choose "start" from the pop-up menu.

The MongoDb Server will start running.

Hope it works!!

Extract a page from a pdf as a jpeg

The pdf2image library can be used.

You can install it simply using,

pip install pdf2image

Once installed you can use following code to get images.

from pdf2image import convert_from_path
pages = convert_from_path('pdf_file', 500)

Saving pages in jpeg format

for page in pages:
    page.save('out.jpg', 'JPEG')

Edit: the Github repo pdf2image also mentions that it uses pdftoppm and that it requires other installations:

pdftoppm is the piece of software that does the actual magic. It is distributed as part of a greater package called poppler. Windows users will have to install poppler for Windows. Mac users will have to install poppler for Mac. Linux users will have pdftoppm pre-installed with the distro (Tested on Ubuntu and Archlinux) if it's not, run sudo apt install poppler-utils.

You can install the latest version under Windows using anaconda by doing:

conda install -c conda-forge poppler

note: Windows versions upto 0.67 are available at http://blog.alivate.com.au/poppler-windows/ but note that 0.68 was released in Aug 2018 so you'll not be getting the latest features or bug fixes.

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

Just to add another piece of info to this for anyone like me who happens along that just has a single application.

I had my application set up with the main app.module.ts and I had routing with the routing module in it's own folder under the main application. I went through and did some 'cleaning up' since I had a few other things that needed to be organized better. One thing I did was move the routing.module.ts to the root folder; since it was the only file in the folder I figured it didn't need it's own folder.

This worked fine at first but next time I tried to generate a new component (some time later, through the WebStorm IDE) it failed with this message. After reading through this I tried putting the routing module back into a separate folder and it worked again.

So note of warning to others, don't move the routing module into your root folder! I'm sure there are other ways to deal with this too but I'm happy with it in it's own folder for now and using the IDE generator like I was previously.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Well, what I do on every project is a mix of the options above.

First, add the jsr310 dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Important detail: put this dependency on the top of your depedencies list. I already see a project where the Localdate error persists even with this dependency on the pom.xml. But changing the order of the depedency the error was gone.

On your /src/main/resources/application.yml file, setup the write-dates-as-timestamps property:

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: false

And create a ObjectMapper bean as this:

@Configuration
public class WebConfigurer {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return objectMapper;
    }

}

Following this configuration, the conversion always work on Spring Boot 1.5.x without any error.

Bonus: Spring AMQP Queue configuration

Working with Spring AMQP, pay attention if you have a new instance of Jackson2JsonMessageConverter (common thing when creating a SimpleRabbitListenerContainerFactory). You need to pass the ObjectMapper bean to it, like:

Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);

Otherwise, you will receive the same error.

laravel Unable to prepare route ... for serialization. Uses Closure

Check your routes/web.php and routes/api.php

Laravel comes with default route closure in routes/web.php:

Route::get('/', function () {
    return view('welcome');
});

and routes/api.php

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

if you remove that then try again to clear route cache.

Pip error: Microsoft Visual C++ 14.0 is required

I faced the same problem. Found the fix here.

Basically just install this.

shasum output:

3e0de8af516c15547602977db939d8c2e44fcc0b  visualcppbuildtools_full.exe

md5sum output:

MD5 (visualcppbuildtools_full.exe) = 8d4afd3b226babecaa4effb10d69eb2e

Run your pip installation command again. If everything works fine, its good. Or you might face the following error like me:

Finished generating code
    LINK : fatal error LNK1158: cannot run 'rc.exe'
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158

Found the fix for the above problem here: Visual Studio can't build due to rc.exe

That basically says

Add this to your PATH environment variables:

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

Copy these files:

rc.exe
rcdll.dll

From

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

To

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin

It works like a charm

Python error message io.UnsupportedOperation: not readable

This will let you read, write and create the file if it don't exist:

f = open('filename.txt','a+')
f = open('filename.txt','r+')

Often used commands:

f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file

Get Path from another app (WhatsApp)

You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path. Using the code below

 public static String getFilePathFromURI(Context context, Uri contentUri) {
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(TEMP_DIR_PATH  + fileName+".jpg");
        copy(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public static void copy(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Then IOUtils class is like below

public class IOUtils {



private static final int BUFFER_SIZE = 1024 * 2;

private IOUtils() {
    // Utility class.
}

public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
    byte[] buffer = new byte[BUFFER_SIZE];

    BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
    BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
    int count = 0, n = 0;
    try {
        while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, n);
            count += n;
        }
        out.flush();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
        try {
            in.close();
        } catch (IOException e) {
            Log.e(e.getMessage(), e.toString());
        }
    }
    return count;
}


}

What are my options for storing data when using React Native? (iOS and Android)

We dont need redux-persist we can simply use redux for persistance.

react-redux + AsyncStorage = redux-persist

so inside createsotre file simply add these lines

store.subscribe(async()=> await AsyncStorage.setItem("store", JSON.stringify(store.getState())))

this will update the AsyncStorage whenever there are some changes in the redux store.

Then load the json converted store. when ever the app loads. and set the store again.

Because redux-persist creates issues when using wix react-native-navigation. If that's the case then I prefer to use simple redux with above subscriber function

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Accessing webpages issues

I added yellow highlighted package and now my view page is accessible. in eclipse when we deploy our war it only deploy those stuff mention in the deployment assessment.

We set Deployment Assessment from right click on project --> Properties --> Apply and Close....

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

How to print a Groovy variable in Jenkins?

You shouldn't use ${varName} when you're outside of strings, you should just use varName. Inside strings you use it like this; echo "this is a string ${someVariable}";. Infact you can place an general java expression inside of ${...}; echo "this is a string ${func(arg1, arg2)}.

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I had the same error, but in my case, it was because I had too many containers running (about 220).

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Check Java versions That was a problem for me. IDE (Intellij in my case) could launch without the problem, but when I tried to run war inside tomcat docker image app didn't work. The reason was docker image had a different (lower) version compare to the development environment. There were no errors messages indicating any of this.

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

According to @Shovalt's answer, but in short:

Alternatively you could use the following lines of code

    from sklearn.metrics import f1_score
    metrics.f1_score(y_test, y_pred, labels=np.unique(y_pred))

This should remove your warning and give you the result you wanted, because it no longer considers the difference between the sets, by using the unique mode.

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

Unit Tests not discovered in Visual Studio 2017

In my case, I target the test project to x64 Architecture and the test setting Architecture (test > Default Processor Architecture) changed was set to x86. They didn't match.

After setting the test setting Architecture back to x64 and rebuilding, all tests were discovered again.

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

You can change the send line to this:

c.send(b'Thank you for connecting')

The b makes it bytes instead.

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

On a Mac, I had to do the following:

sudo chown -R $USER /data/db
sudo chown -R $USER /tmp/

because there was also a file inside /tmp which Mongo also needed access

How to hide collapsible Bootstrap 4 navbar on click

I am using ANGULAR and since it gave me problems the routerLink just add the data-toggle and target in the li tag.... or use jquery like "ZimSystem"

_x000D_
_x000D_
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
      <ul class="navbar-nav mr-auto">_x000D_
        <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">_x000D_
          <a class="nav-link" routerLink="/inicio" routerLinkActive="active" >Inicio</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to save a new sheet in an existing excel file, using Pandas?

A simple example for writing multiple data to excel at a time. And also when you want to append data to a sheet on a written excel file (closed excel file).

When it is your first time writing to an excel. (Writing "df1" and "df2" to "1st_sheet" and "2nd_sheet")

import pandas as pd 
from openpyxl import load_workbook

df1 = pd.DataFrame([[1],[1]], columns=['a'])
df2 = pd.DataFrame([[2],[2]], columns=['b'])
df3 = pd.DataFrame([[3],[3]], columns=['c'])

excel_dir = "my/excel/dir"

with pd.ExcelWriter(excel_dir, engine='xlsxwriter') as writer:    
    df1.to_excel(writer, '1st_sheet')   
    df2.to_excel(writer, '2nd_sheet')   
    writer.save()    

After you close your excel, but you wish to "append" data on the same excel file but another sheet, let's say "df3" to sheet name "3rd_sheet".

book = load_workbook(excel_dir)
with pd.ExcelWriter(excel_dir, engine='openpyxl') as writer:
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)    

    ## Your dataframe to append. 
    df3.to_excel(writer, '3rd_sheet')  

    writer.save()     

Be noted that excel format must not be xls, you may use xlsx one.

How to solve npm error "npm ERR! code ELIFECYCLE"

React Application: For me the issue was that after running npm install had some errors.

I've went with the recommendation npm audit fix. This operation broke my package.json and package-lock.json (changed version of packages and and structure of .json).

THE FIX WAS:

  • Delete node_modules
  • Run npm install
  • npm start

Hope this will be helpfull for someone.

React Router v4 - How to get current route?

There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.

import { useLocation } from 'react-router-dom';

const ExampleComponent: React.FC = () => {
  const location = useLocation();  

  return (
    <Router basename='/app'>
      <main>
        <AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
      </main>
    </Router>
  );
}

Laravel 5.4 redirection to custom url after login

in accord with Laravel documentation, I create in app/Http/Controllers/Auth/LoginController.php the following method :

protected function redirectTo()
{
    $user=Auth::user();

    if($user->account_type == 1){
        return '/admin';
    }else{
        return '/home';
    }

}

to get the user information from my db I used "Illuminate\Support\Facades\Auth;".

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Uncaught TypeError: (intermediate value)(...) is not a function

Error Case:

var userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

Output:

TypeError: (intermediate value)(intermediate value) is not a function

Fix: You are missing a semi-colon (;) to separate the expressions

userListQuery = {
    userId: {
        $in: result
    },
    "isCameraAdded": true
}; // Without a semi colon, the error is produced

( cameraInfo.findtext != "" ) ? searchQuery : userListQuery;

MultipartException: Current request is not a multipart request

That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.

I ended up solving it by going to the Body tab, change the param type from File to Text, then back to File and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?

Plotting images side by side using matplotlib

You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(...)
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(...)
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(...)
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(...)

For more info have a look here: http://matplotlib.org/examples/pylab_examples/subplots_demo.html

For complex layouts, you should consider using gridspec: http://matplotlib.org/users/gridspec.html

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

Pandas dataframe groupby plot

Simple plot,

you can use:

df.plot(x='Date',y='adj_close')

Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

df.set_index('Date', inplace=True)
df['adj_close'].plot()

If you want a chart with one series by ticker on it

You need to groupby before:

df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)

enter image description here


If you want a chart with individual subplots:

grouped = df.groupby('ticker')

ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)

for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
    grouped.get_group(key).plot(ax=ax)

ax.legend()
plt.show()

enter image description here

Nested routes with react router v4 / v5

Using Hooks

The latest update with hooks is to use useRouteMatch.

Main routing component


export default function NestingExample() {
  return (
    <Router>
      <Switch>
       <Route path="/topics">
         <Topics />
       </Route>
     </Switch>
    </Router>
  );
}

Child component

function Topics() {
  // The `path` lets us build <Route> paths 
  // while the `url` lets us build relative links.

  let { path, url } = useRouteMatch();

  return (
    <div>
      <h2>Topics</h2>
      <h5>
        <Link to={`${url}/otherpath`}>/topics/otherpath/</Link>
      </h5>
      <ul>
        <li>
          <Link to={`${url}/topic1`}>/topics/topic1/</Link>
        </li>
        <li>
          <Link to={`${url}/topic2`}>/topics/topic2</Link>
        </li>
      </ul>

      // You can then use nested routing inside the child itself
      <Switch>
        <Route exact path={path}>
          <h3>Please select a topic.</h3>
        </Route>
        <Route path={`${path}/:topicId`}>
          <Topic />
        </Route>
        <Route path={`${path}/otherpath`>
          <OtherPath/>
        </Route>
      </Switch>
    </div>
  );
}

Generate your own Error code in swift 3

You can create enums to deal with errors :)

enum RikhError: Error {
    case unknownError
    case connectionError
    case invalidCredentials
    case invalidRequest
    case notFound
    case invalidResponse
    case serverError
    case serverUnavailable
    case timeOut
    case unsuppotedURL
 }

and then create a method inside enum to receive the http response code and return the corresponding error in return :)

static func checkErrorCode(_ errorCode: Int) -> RikhError {
        switch errorCode {
        case 400:
            return .invalidRequest
        case 401:
            return .invalidCredentials
        case 404:
            return .notFound
        //bla bla bla
        default:
            return .unknownError
        }
    }

Finally update your failure block to accept single parameter of type RikhError :)

I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)

Hope it helps :)

How to send post request with x-www-form-urlencoded body

string urlParameters = "param1=value1&param2=value2";
string _endPointName = "your url post api";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                                                  (se, cert, chain, sslerror) =>
                                                  {
                                                      return true;
                                                  };


using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(urlParameters);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }

How can I mock an ES6 module import using Jest?

Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
  });
});

And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.

boto3 client NoRegionError: You must specify a region error only sometimes

For those using CloudFormation template. You can set AWS_DEFAULT_REGION environment variable using UserData and AWS::Region. For example,

MyInstance1:
    Type: AWS::EC2::Instance                
    Properties:                           
        ImageId: ami-04b9e92b5572fa0d1 #ubuntu
        InstanceType: t2.micro
        UserData: 
            Fn::Base64: !Sub |
                    #!/bin/bash -x

                    echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

You can use list open file command and then kill the process like below.

sudo lsof -t -i tcp:8181 | xargs kill -9

or

sudo lsof -i tcp:8181

kill -9 PID

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

In most of cases it is data log problem. Follow the steps.

i) Go to data folder of mysql. For xampp go to C:\xampp\mysql\data.

ii) Look for log file name like ib_logfile0 and ib_logfile1.

iii) Create backup and delete those files.

iv) Restart apache and mysql.

Postgres: check if array field contains value?

This worked for me:

select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'

Depending on your normalization needs, it might be better to implement a separate table with a FK reference as you may get better performance and manageability.

Jenkins fails when running "service start jenkins"

Similar problem on Ubuntu 16.04.

Setting up jenkins (2.72) ...
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
invoke-rc.d: initscript jenkins, action "start" failed.
? jenkins.service - LSB: Start Jenkins at boot time
Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-01 05:39:06 UTC; 7ms ago
Docs: man:systemd-sysv-generator(8)
Process: 3700 ExecStart=/etc/init.d/jenkins start (code=exited, status=1/FAILURE)

Aug 01 05:39:06 ip-0 systemd[1]: Starting LSB: Start Jenkins ....
Aug 01 05:39:06 ip-0 jenkins[3700]: ERROR: No Java executable ...
Aug 01 05:39:06 ip-0 jenkins[3700]: If you actually have java ...
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Control pro...1
Aug 01 05:39:06 ip-0 systemd[1]: Failed to start LSB: Start J....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Unit entere....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Failed with....

To fix the issue manually install Java Runtime Environment:

JDK version 9:

sudo apt install openjdk-9-jre

JDK version 8:

sudo apt install openjdk-8-jre

Open Jenkins configuration file:

sudo vi /etc/init.d/jenkins

Finally, append path to the new java executable (line 16):

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/lib/jvm/java-8-openjdk-amd64/bin/

Python/Json:Expecting property name enclosed in double quotes

In my case, double quotes was not a problem.

Last comma gave me same error message.

{'a':{'b':c,}}
           ^

To remove this comma, I wrote some simple code.

import json

with open('a.json','r') as f:
    s = f.read()
    s = s.replace('\t','')
    s = s.replace('\n','')
    s = s.replace(',}','}')
    s = s.replace(',]',']')
    data = json.loads(s)

And this worked for me.

'gulp' is not recognized as an internal or external command

Sorry that was a typo. You can either add node_modules to the end of your user's global path variable, or maybe check the permissions associated with that folder (node _modules). The error doesn't seem like the last case, but I've encountered problems similar to yours. I find the first solution enough for most cases. Just go to environment variables and add the path to node_modules to the last part of your user's path variable. Note I'm saying user and not system.

Just add a semicolon to the end of the variable declaration and add the static path to your node_module folder. ( Ex c:\path\to\node_module)

Alternatively you could:

In your CMD

PATH=%PATH%;C:\\path\to\node_module

EDIT

The last solution will work as long as you don't close your CMD. So, use the first solution for a permanent change.

how to end ng serve or firebase serve

I was able to stop via this on Windows for Angular 8:

Step 1: Find 4200 process

netstat -ano | findstr :4200

Step 2: Kill that process:

taskkill /PID <PID> /F

enter image description here

How to upload a file and JSON data in Postman?

I needed to pass both: a file and an integer. I did it this way:

  1. needed to pass a file to upload: did it as per Sumit's answer.

    Request type : POST

    Body -> form-data

    under the heading KEY, entered the name of the variable ('file' in my backend code).

    in the backend:

    file = request.files['file']

    Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.

2. needed to pass an integer:

went to:

Params

entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE

in the backend:

id = request.args.get('id')

Worked!

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

Verify host key with pysftp

I've implemented auto_add_key in my pysftp github fork.

auto_add_key will add the key to known_hosts if auto_add_key=True
Once a key is present for a host in known_hosts this key will be checked.

Please reffer Martin Prikryl -> answer about security concerns.

Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

import pysftp as sftp

def push_file_to_server():
    s = sftp.Connection(host='138.99.99.129', username='root', password='pass', auto_add_key=True)
    local_path = "testme.txt"
    remote_path = "/home/testme.txt"

    s.put(local_path, remote_path)
    s.close()

push_file_to_server()

Note: Why using context manager

import pysftp
with pysftp.Connection(host, username="whatever", password="whatever", auto_add_key=True) as sftp:
    #do your stuff here
#connection closed

How to fix error Base table or view not found: 1146 Table laravel relationship table?

You should change/add in your PostController: (and change PostsController to PostController)

public function create()
{
    $categories = Category::all();
    return view('create',compact('categories'));
}

public function store(Request $request)
{
    $post = new Posts;
    $post->title = $request->get('title'); // CHANGE THIS
    $post->body = $request->get('body'); // CHANGE THIS
    $post->save(); // ADD THIS
    $post->categories()->attach($request->get('categories_id')); // CHANGE THIS

    return redirect()->route('posts.index'); // PS ON THIS ONE
}

PS: using route() means you have named your route as such

Route::get('example', 'ExampleController@getExample')->name('getExample');

UPDATE

The comments above are also right, change your 'Posts' Model to 'Post'

Access HTTP response as string in Go

string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.

error: RPC failed; curl transfer closed with outstanding read data remaining

When I tried cloning from the remote, got the same issue repeatedly:

remote: Counting objects: 182, done.
remote: Compressing objects: 100% (149/149), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed

Finally this worked for me:

git clone https://[email protected]/repositoryName.git --depth 1

Run react-native on android emulator

Had a similar problem. I updated my Genymotion and my android SDK's/libraries/dependencies and all seemed to work. To update my SDK's I used android sdk manager {ANDROID_SDK_FOLDER}/tools/android sdk

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

  1. Open C:\Users\Username.gradle\wrapper\dists\

  2. Open latest gradle folder, e.g. gradle-4.1-rc-1-all

    You will find a random folder named 936kh1brdchce6fvd2c1o8t8x

  3. Download zip file of similar name

    eg: https://downloads.gradle.org/distributions/gradle-4.1-rc-1-all.zip

  4. Save it in this folder

  5. Restart Android studio

    It will automatically extract the zip folder and Error will clear

How to install and run Typescript locally in npm?

It took me a while to figure out the solution to this problem - it's in the original question. You need to have a script that calls tsc in your package.json file so that you can run:

npm run tsc 

Include -- before you pass in options (or just include them in the script):

npm run tsc -- -v

Here's an example package.json:

{
  "name": "foo",
  "scripts": {
    "tsc": "tsc"
  },
  "dependencies": {
    "typescript": "^1.8.10"
  }
}

How to dynamically add and remove form fields in Angular 2

This is a few months late but I thought I'd provide my solution based on this here tutorial. The gist of it is that it's a lot easier to manage once you change the way you approach forms.

First, use ReactiveFormsModule instead of or in addition to the normal FormsModule. With reactive forms you create your forms in your components/services and then plug them into your page instead of your page generating the form itself. It's a bit more code but it's a lot more testable, a lot more flexible, and as far as I can tell the best way to make a lot of non-trivial forms.

The end result will look a little like this, conceptually:

  • You have one base FormGroup with whatever FormControl instances you need for the entirety of the form. For example, as in the tutorial I linked to, lets say you want a form where a user can input their name once and then any number of addresses. All of the one-time field inputs would be in this base form group.

  • Inside that FormGroup instance there will be one or more FormArray instances. A FormArray is basically a way to group multiple controls together and iterate over them. You can also put multiple FormGroup instances in your array and use those as essentially "mini-forms" nested within your larger form.

  • By nesting multiple FormGroup and/or FormControl instances within a dynamic FormArray, you can control validity and manage the form as one, big, reactive piece made up of several dynamic parts. For example, if you want to check if every single input is valid before allowing the user to submit, the validity of one sub-form will "bubble up" to the top-level form and the entire form becomes invalid, making it easy to manage dynamic inputs.

  • As a FormArray is, essentially, a wrapper around an array interface but for form pieces, you can push, pop, insert, and remove controls at any time without recreating the form or doing complex interactions.

In case the tutorial I linked to goes down, here some sample code you can implement yourself (my examples use TypeScript) that illustrate the basic ideas:

Base Component code:

import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-form-component',
  templateUrl: './my-form.component.html'
})
export class MyFormComponent implements OnInit {
    @Input() inputArray: ArrayType[];
    myForm: FormGroup;

    constructor(private fb: FormBuilder) {}
    ngOnInit(): void {
        let newForm = this.fb.group({
            appearsOnce: ['InitialValue', [Validators.required, Validators.maxLength(25)]],
            formArray: this.fb.array([])
        });

        const arrayControl = <FormArray>newForm.controls['formArray'];
        this.inputArray.forEach(item => {
            let newGroup = this.fb.group({
                itemPropertyOne: ['InitialValue', [Validators.required]],
                itemPropertyTwo: ['InitialValue', [Validators.minLength(5), Validators.maxLength(20)]]
            });
            arrayControl.push(newGroup);
        });

        this.myForm = newForm;
    }
    addInput(): void {
        const arrayControl = <FormArray>this.myForm.controls['formArray'];
        let newGroup = this.fb.group({

            /* Fill this in identically to the one in ngOnInit */

        });
        arrayControl.push(newGroup);
    }
    delInput(index: number): void {
        const arrayControl = <FormArray>this.myForm.controls['formArray'];
        arrayControl.removeAt(index);
    }
    onSubmit(): void {
        console.log(this.myForm.value);
        // Your form value is outputted as a JavaScript object.
        // Parse it as JSON or take the values necessary to use as you like
    }
}

Sub-Component Code: (one for each new input field, to keep things clean)

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
    selector: 'my-form-sub-component',
    templateUrl: './my-form-sub-component.html'
})
export class MyFormSubComponent {
    @Input() myForm: FormGroup; // This component is passed a FormGroup from the base component template
}

Base Component HTML

<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
    <label>Appears Once:</label>
    <input type="text" formControlName="appearsOnce" />

    <div formArrayName="formArray">
        <div *ngFor="let control of myForm.controls['formArray'].controls; let i = index">
            <button type="button" (click)="delInput(i)">Delete</button>
            <my-form-sub-component [myForm]="myForm.controls.formArray.controls[i]"></my-form-sub-component>
        </div>
    </div>
    <button type="button" (click)="addInput()">Add</button>
    <button type="submit" [disabled]="!myForm.valid">Save</button>
</form>

Sub-Component HTML

<div [formGroup]="form">
    <label>Property One: </label>
    <input type="text" formControlName="propertyOne"/>

    <label >Property Two: </label>
    <input type="number" formControlName="propertyTwo"/>
</div>

In the above code I basically have a component that represents the base of the form and then each sub-component manages its own FormGroup instance within the FormArray situated inside the base FormGroup. The base template passes along the sub-group to the sub-component and then you can handle validation for the entire form dynamically.

Also, this makes it trivial to re-order component by strategically inserting and removing them from the form. It works with (seemingly) any number of inputs as they don't conflict with names (a big downside of template-driven forms as far as I'm aware) and you still retain pretty much automatic validation. The only "downside" of this approach is, besides writing a little more code, you do have to relearn how forms work. However, this will open up possibilities for much larger and more dynamic forms as you go on.

If you have any questions or want to point out some errors, go ahead. I just typed up the above code based on something I did myself this past week with the names changed and other misc. properties left out, but it should be straightforward. The only major difference between the above code and my own is that I moved all of the form-building to a separate service that's called from the component so it's a bit less messy.

The response content cannot be parsed because the Internet Explorer engine is not available, or

Yet another method to solve: updating registry. In my case I could not alter GPO, and -UseBasicParsing breaks parts of the access to the website. Also I had a service user without log in permissions, so I could not log in as the user and run the GUI.
To fix,

  1. log in as a normal user, run IE setup.
  2. Then export this registry key: HKEY_USERS\S-1-5-21-....\SOFTWARE\Microsoft\Internet Explorer
  3. In the .reg file that is saved, replace the user sid with the service account sid
  4. Import the .reg file

In the file

How do I detect if a user is already logged in Firebase?

One another way is to use the same thing what firebase uses.

For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.

enter image description here

ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)

FCM getting MismatchSenderId

You will have a server key something like this AIzaSyDiTEVq4Li1pj7IyraRlyRU9adc-49-KVY available in the Settings section of firebase console console.firebase.google.com/project/project-XXXXXXXXXXXXX/settings/cloudmessaging.

Specify the correct key with your code and try again.

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

Implement runtime permission for running your app on Android 6.0 Marshmallow (API 23) or later.

or you can manually enable the storage permission-

goto settings>apps> "your_app_name" >click on it >then click permissions> then enable the storage. Thats it.

But i suggest go the for first one which is, Implement runtime permissions in your code.

How to use the gecko executable with Selenium

Recently Selenium has launched Selenium 3 and if you are trying to use Firefox latest version then you have to use GeckoDriver:

System.setProperty("webdriver.gecko.driver","G:\\Selenium\\Firefox driver\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

You can check full documentation from here

How to return data from promise

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

Docker: Container keeps on restarting again on again

In my case nginx container was keep on restarting , I checked logs of nginx container and came to know .crt and .key file of a unrequired domain are having errors , so I removed respective .conf file , .crt and .key and then restarted nginx . That's it nginx is working fine without restarting .

Send push to Android by C# using FCM (Firebase Cloud Messaging)

I have posted this answer as this question was viewed most and this server side code was written in VS 2015 in C# for sending push notification either single device based on device id or subscribed topic to Xamarin Android app

public class FCMPushNotification
{
    public FCMPushNotification()
    {
        // TODO: Add constructor logic here
    }

    public bool Successful
    {
        get;
        set;
    }

    public string Response
    {
        get;
        set;
    }
    public Exception Error
    {
        get;
        set;
    }



    public FCMPushNotification SendNotification(string _title, string _message, string _topic)
    {
        FCMPushNotification result = new FCMPushNotification();
        try
        {
            result.Successful = true;
            result.Error = null;
           // var value = message;
            var requestUri = "https://fcm.googleapis.com/fcm/send";

            WebRequest webRequest = WebRequest.Create(requestUri);
            webRequest.Method = "POST";
            webRequest.Headers.Add(string.Format("Authorization: key={0}", YOUR_FCM_SERVER_API_KEY));
            webRequest.Headers.Add(string.Format("Sender: id={0}", YOUR_FCM_SENDER_ID));
            webRequest.ContentType = "application/json";

            var data = new
            {
               // to = YOUR_FCM_DEVICE_ID, // Uncoment this if you want to test for single device
               to="/topics/"+_topic, // this is for topic 
                notification=new
                {
                    title=_title,
                    body=_message,
                    //icon="myicon"
                }
            };
            var serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(data);

            Byte[] byteArray = Encoding.UTF8.GetBytes(json);

            webRequest.ContentLength = byteArray.Length;
            using (Stream dataStream = webRequest.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (WebResponse webResponse = webRequest.GetResponse())
                {
                    using (Stream dataStreamResponse = webResponse.GetResponseStream())
                    {
                        using (StreamReader tReader = new StreamReader(dataStreamResponse))
                        {
                            String sResponseFromServer = tReader.ReadToEnd();
                            result.Response = sResponseFromServer;
                        }
                    }
                }
            }

        }
        catch(Exception ex)
        {
            result.Successful = false;
            result.Response = null;
            result.Error = ex;
        }
        return result;
    }
}

and its uses

// start sending push notification to apps
                FCMPushNotification fcmPush = new FCMPushNotification();                    
                fcmPush.SendNotification("your notificatin title", "Your body message","news");
                // end push notification

This page didn't load Google Maps correctly. See the JavaScript console for technical details

You could also get the error if your Billing is not set up correctly.

Google hands out credit worth $300 or 12 months of free usage whichever runs out faster. After that you would need to enable billing.

enter image description here

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.

I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

It may come when the API(you are consuming) is not sending the corresponding JSON. You may experience the response as 404 page or something like HTML/XML response.

Could not find method android() for arguments

You are using the wrong build.gradle file.

In your top-level file you can't define an android block.

Just move this part inside the module/build.gradle file.

android {
    compileSdkVersion 17
    buildToolsVersion '23.0.0'
}
dependencies {
    compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

How do I filter an array with TypeScript in Angular 2?

You need to put your code into ngOnInit and use the this keyword:

ngOnInit() {
  this.booksByStoreID = this.books.filter(
          book => book.store_id === this.store.id);
}

You need ngOnInit because the input store wouldn't be set into the constructor:

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

(https://angular.io/docs/ts/latest/api/core/index/OnInit-interface.html)

In your code, the books filtering is directly defined into the class content...

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

Make sure "App Domain" and Facebook Login => Valid OAuth redirect URIs. There you must check www or without www. Its better if you use with www or without for all URLs in php,html,css files and Fb app settings.

Other thing is if you're using "/" end of the URLs you must add that URL to app settings of Valid OAuth redirect URIs. Example:- https://www.example.com/index.php/ if this url if youre using in the redirect url you must set that to app settings.

Hope this would be help.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

In most cases, it is enough just to hide the element, for example in this way:

export default class ErrorBoxComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isHidden: false
        }
    }

    dismiss() {
        this.setState({
            isHidden: true
        })
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Or you may render/rerender/not render via parent component like this

export default class ParentComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isErrorShown: true
        }
    }

    dismiss() {
        this.setState({
            isErrorShown: false
        })
    }

    showError() {
        if (this.state.isErrorShown) {
            return <ErrorBox 
                error={ this.state.error }
                dismiss={ this.dismiss.bind(this) }
            />
        }

        return null;
    }

    render() {

        return (
            <div>
                { this.showError() }
            </div>
        );
    }
}

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.props.dismiss();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box">
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.el.remove();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

How to configure CORS in a Spring Boot + Spring Security application?

If you use JDK 8+, there is a one line lambda solution:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}

ERROR Android emulator gets killed

If you use McAfee Antivirus and Windows 10 this might help you:

Uninstalling and reinstalling Android Emulator as snehatilak suggested initially helped in my case, though the next day the emulator was dead yet again.

I found that McAfee antivirus had quarantined the file AVD.conf that had been in C:\Users[username].android\avd[avdImage]\

After restoring AVD.conf and excluding it from scans it seems to be ok again.

This all started 02.02.2021 after what I guess was an McAfee update.

Here are the steps:

First go to 'Quarantined items' under Settings and restore the AVD.conf file enter image description here

Then go to 'Real-Time Scanning' under Settings and exclude AVD.conf in each emulator you have created. (Located under C:\Users[username].android\avd[avdImage])

enter image description here

When should I use curly braces for ES6 import?

In order to understand the use of curly braces in import statements, first, you have to understand the concept of destructuring introduced in ES6

  1. Object destructuring

    var bodyBuilder = {
      firstname: 'Kai',
      lastname: 'Greene',
      nickname: 'The Predator'
    };
    
    var {firstname, lastname} = bodyBuilder;
    console.log(firstname, lastname); // Kai Greene
    
    firstname = 'Morgan';
    lastname = 'Aste';
    
    console.log(firstname, lastname); // Morgan Aste
    
  2. Array destructuring

    var [firstGame] = ['Gran Turismo', 'Burnout', 'GTA'];
    
    console.log(firstGame); // Gran Turismo
    

    Using list matching

      var [,secondGame] = ['Gran Turismo', 'Burnout', 'GTA'];
      console.log(secondGame); // Burnout
    

    Using the spread operator

    var [firstGame, ...rest] = ['Gran Turismo', 'Burnout', 'GTA'];
    console.log(firstGame);// Gran Turismo
    console.log(rest);// ['Burnout', 'GTA'];
    

Now that we've got that out of our way, in ES6 you can export multiple modules. You can then make use of object destructuring like below.

Let's assume you have a module called module.js

    export const printFirstname(firstname) => console.log(firstname);
    export const printLastname(lastname) => console.log(lastname);

You would like to import the exported functions into index.js;

    import {printFirstname, printLastname} from './module.js'

    printFirstname('Taylor');
    printLastname('Swift');

You can also use different variable names like so

    import {printFirstname as pFname, printLastname as pLname} from './module.js'

    pFname('Taylor');
    pLanme('Swift');

curl: (35) SSL connect error

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.19.1 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2

You are using a very old version of curl. My guess is that you run into the bug described 6 years ago. Fix is to update your curl.

Bootstrap $('#myModal').modal('show') is not working

<div class="modal fade" id="myModal" aria-hidden="true">
   ...
   ...
</div>

Note: Remove fade class from the div and enjoy it should be worked

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

How to set a tkinter window to a constant size

You turn off pack_propagate by setting pack_propagate(0)

Turning off pack_propagate here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally

To turn off resizing the root window, you can set root.resizable(0, 0), where resizing is allowed in the x and y directions respectively.

To set a maxsize to window, as noted in the other answer you can set the maxsize attribute or minsize although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.

Whenever you set grid or pack on a widget it will return None. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid or pack on it. You should instead set the variable to be the widget Widget(master, ....) and then call pack or grid on the widget instead.

import tkinter as tk

def startgame():

    pass

mw = tk.Tk()

#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")

mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction

back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window

#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()

mw.mainloop()

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I ran into this issue as well and found this post. Ultimately none of these answers solved my problem, instead I had to put in a rewrite rule to strip out the location /rt as the backend my developers made was not expecting any additional paths:

+-(william@wkstn18)--(Thu, 05 Nov 20)-+
+-(~)--(16:13)->wscat -c ws://WebsocketServerHostname/rt
error: Unexpected server response: 502

Testing with wscat repeatedly gave a 502 response. Nginx error logs provided the same upstream error as above, but notice the upstream string shows the GET Request is attempting to access localhost:12775/rt and not localhost:12775:

 2020/11/05 22:13:32 [error] 10175#10175: *7 upstream prematurely closed
 connection while reading response header from upstream, client: WANIP,
 server: WebsocketServerHostname, request: "GET /rt/socket.io/?transport=websocket
 HTTP/1.1", upstream: "http://127.0.0.1:12775/rt/socket.io/?transport=websocket",
 host: "WebsocketServerHostname"

Since the devs had not coded their websocket (listening on 12775) to expect /rt/socket.io but instead just /socket.io/ (NOTE: /socket.io/ appears to just be a way to specify websocket transport discussed here). Because of this, rather than ask them to rewrite their socket code I just put in a rewrite rule to translate WebsocketServerHostname/rt to WebsocketServerHostname:12775 as below:

upstream websocket-rt {
        ip_hash;

        server 127.0.0.1:12775;
}

server {
        listen 80;
        server_name     WebsocketServerHostname;

        location /rt {
                proxy_http_version 1.1;

                #rewrite /rt/ out of all requests and proxy_pass to 12775
                rewrite /rt/(.*) /$1  break;

                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $host;

                proxy_pass http://websocket-rt;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $connection_upgrade;
        }

}

How to extend / inherit components?

Now that TypeScript 2.2 supports Mixins through Class expressions we have a much better way to express Mixins on Components. Mind you that you can also use Component inheritance since angular 2.3 (discussion) or a custom decorator as discussed in other answers here. However, I think Mixins have some properties that make them preferable for reusing behavior across components:

  • Mixins compose more flexibly, i.e. you can mix and match Mixins on existing components or combine Mixins to form new Components
  • Mixin composition remains easy to understand thanks to its obvious linearization to a class inheritance hierarchy
  • You can more easily avoid issues with decorators and annotations that plague component inheritance (discussion)

I strongly suggest you read the TypeScript 2.2 announcement above to understand how Mixins work. The linked discussions in angular GitHub issues provide additional detail.

You'll need these types:

export type Constructor<T> = new (...args: any[]) => T;

export class MixinRoot {
}

And then you can declare a Mixin like this Destroyable mixin that helps components keep track of subscriptions that need to be disposed in ngOnDestroy:

export function Destroyable<T extends Constructor<{}>>(Base: T) {
  return class Mixin extends Base implements OnDestroy {
    private readonly subscriptions: Subscription[] = [];

    protected registerSubscription(sub: Subscription) {
      this.subscriptions.push(sub);
    }

    public ngOnDestroy() {
      this.subscriptions.forEach(x => x.unsubscribe());
      this.subscriptions.length = 0; // release memory
    }
  };
}

To mixin Destroyable into a Component, you declare your component like this:

export class DashboardComponent extends Destroyable(MixinRoot) 
    implements OnInit, OnDestroy { ... }

Note that MixinRoot is only necessary when you want to extend a Mixin composition. You can easily extend multiple mixins e.g. A extends B(C(D)). This is the obvious linearization of mixins I was talking about above, e.g. you're effectively composing an inheritnace hierarchy A -> B -> C -> D.

In other cases, e.g. when you want to compose Mixins on an existing class, you can apply the Mixin like so:

const MyClassWithMixin = MyMixin(MyClass);

However, I found the first way works best for Components and Directives, as these also need to be decorated with @Component or @Directive anyway.

Solving sslv3 alert handshake failure when trying to use a client certificate

What SSL private key should be sent along with the client certificate?

None of them :)

One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.

Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.


Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

Use TLS 1.0 and above; and use Server Name Indication.

You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:

openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
    -cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem

You can also use -CAfile to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.

The request was rejected because no multipart boundary was found in springboot

I was having the same problem while making a POST request from Postman and later I could solve the problem by setting a custom Content-Type with a boundary value set along with it like this.

I thought people can run into similar problem and hence, I'm sharing my solution.

postman

How to write unit testing for Angular / TypeScript for private methods with Jasmine

call private method using square brackets

Ts file

class Calculate{
  private total;
  private add(a: number) {
      return a + total;
  }
}

spect.ts file

it('should return 5 if input 3 and 2', () => {
    component['total'] = 2;
    let result = component['add'](3);
    expect(result).toEqual(5);
});

How can I close a dropdown on click outside?

ELEGANT METHOD

I found this clickOut directive: https://github.com/chliebel/angular2-click-outside. I check it and it works well (i only copy clickOutside.directive.ts to my project). U can use it in this way:

<div (clickOutside)="close($event)"></div>

Where close is your function which will be call when user click outside div. It is very elegant way to handle problem described in question.

If you use above directive to close popUp window, remember first to add event.stopPropagation() to button click event handler which open popUp.

BONUS:

Below i copy oryginal directive code from file clickOutside.directive.ts (in case if link will stop working in future) - the author is Christian Liebel :

_x000D_
_x000D_
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';_x000D_
    _x000D_
@Directive({_x000D_
    selector: '[clickOutside]'_x000D_
})_x000D_
export class ClickOutsideDirective {_x000D_
    constructor(private _elementRef: ElementRef) {_x000D_
    }_x000D_
_x000D_
    @Output()_x000D_
    public clickOutside = new EventEmitter<MouseEvent>();_x000D_
_x000D_
    @HostListener('document:click', ['$event', '$event.target'])_x000D_
    public onClick(event: MouseEvent, targetElement: HTMLElement): void {_x000D_
        if (!targetElement) {_x000D_
            return;_x000D_
        }_x000D_
_x000D_
        const clickedInside = this._elementRef.nativeElement.contains(targetElement);_x000D_
        if (!clickedInside) {_x000D_
            this.clickOutside.emit(event);_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

In my case (using ASP.NET Core 3.1 and Visual Studio Professional 2019), I've seen this twice and in both cases fixing it was as simple as rebooting my PC.

I strongly suspect, but can't prove, that this could also be accomplished by restarting only a specific process (like in @Codenova's answer).

How to save a pandas DataFrame table as a png

Pandas allows you to plot tables using matplotlib (details here). Usually this plots the table directly onto a plot (with axes and everything) which is not what you want. However, these can be removed first:

import matplotlib.pyplot as plt
import pandas as pd
from pandas.table.plotting import table # EDIT: see deprecation warnings below

ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis

table(ax, df)  # where df is your data frame

plt.savefig('mytable.png')

The output might not be the prettiest but you can find additional arguments for the table() function here. Also thanks to this post for info on how to remove axes in matplotlib.


EDIT:

Here is a (admittedly quite hacky) way of simulating multi-indexes when plotting using the method above. If you have a multi-index data frame called df that looks like:

first  second
bar    one       1.991802
       two       0.403415
baz    one      -1.024986
       two      -0.522366
foo    one       0.350297
       two      -0.444106
qux    one      -0.472536
       two       0.999393
dtype: float64

First reset the indexes so they become normal columns

df = df.reset_index() 
df
    first second       0
0   bar    one  1.991802
1   bar    two  0.403415
2   baz    one -1.024986
3   baz    two -0.522366
4   foo    one  0.350297
5   foo    two -0.444106
6   qux    one -0.472536
7   qux    two  0.999393

Remove all duplicates from the higher order multi-index columns by setting them to an empty string (in my example I only have duplicate indexes in "first"):

df.ix[df.duplicated('first') , 'first'] = '' # see deprecation warnings below
df
  first second         0
0   bar    one  1.991802
1          two  0.403415
2   baz    one -1.024986
3          two -0.522366
4   foo    one  0.350297
5          two -0.444106
6   qux    one -0.472536
7          two  0.999393

Change the column names over your "indexes" to the empty string

new_cols = df.columns.values
new_cols[:2] = '',''  # since my index columns are the two left-most on the table
df.columns = new_cols 

Now call the table function but set all the row labels in the table to the empty string (this makes sure the actual indexes of your plot are not displayed):

table(ax, df, rowLabels=['']*df.shape[0], loc='center')

et voila:

enter image description here

Your not-so-pretty but totally functional multi-indexed table.

EDIT: DEPRECATION WARNINGS

As pointed out in the comments, the import statement for table:

from pandas.tools.plotting import table

is now deprecated in newer versions of pandas in favour of:

from pandas.plotting import table 

EDIT: DEPRECATION WARNINGS 2

The ix indexer has now been fully deprecated so we should use the loc indexer instead. Replace:

df.ix[df.duplicated('first') , 'first'] = ''

with

df.loc[df.duplicated('first') , 'first'] = ''

Moment.js - tomorrow, today and yesterday

You can customize the way that both the .fromNow and the .calendar methods display dates using moment.updateLocale. The following code will change the way that .calendar displays as per the question:

moment.updateLocale('en', {
    calendar : {
        lastDay : '[Yesterday]',
        sameDay : '[Today]',
        nextDay : '[Tomorrow]',
        lastWeek : '[Last] dddd',
        nextWeek : '[Next] dddd',
        sameElse : 'L'
    }
});

Based on the question, it seems like the .calendar method would be more appropriate -- .fromNow wants to have a past/present prefix/suffix, but if you'd like to find out more you can read the documentation at http://momentjs.com/docs/#/customization/relative-time/.

To use this in only one place instead of overwriting the locales, pass a string of your choice as the first argument when you define the moment.updateLocale and then invoke the calendar method using that locale (eg. moment.updateLocale('yesterday-today').calendar( /* moment() or whatever */ ))

EDIT: Moment ^2.12.0 now has the updateLocale method. updateLocale and locale appear to be functionally the same, and locale isn't yet deprecated, but updated the answer to use the newer method.

Angular pass callback function to child component as @Input similar to AngularJS way

An alternative to the answer SnareChops gave.

You can use .bind(this) in your template to have the same effect. It may not be as clean but it saves a couple of lines. I'm currently on angular 2.4.0

@Component({
  ...
  template: '<child [myCallback]="theCallback.bind(this)"></child>',
  directives: [ChildComponent]
})
export class ParentComponent {

  public theCallback(){
    ...
  }
}

@Component({...})
export class ChildComponent{
  //This will be bound to the ParentComponent.theCallback
  @Input()
  public myCallback: Function; 
  ...
}

How to load a model from an HDF5 file in Keras?

If you stored the complete model, not only the weights, in the HDF5 file, then it is as simple as

from keras.models import load_model
model = load_model('model.h5')

Is there a simple way to increment a datetime object one month in Python?

Check out from dateutil.relativedelta import * for adding a specific amount of time to a date, you can continue to use timedelta for the simple stuff i.e.

use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)

or you can start using relativedelta

use_date = use_date+relativedelta(months=+1)

use_date = use_date+relativedelta(years=+1)

for the last day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)

Right now this will provide 29/02/2016

for the penultimate day of next month:

use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)

last Friday of the next month:

use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))

2nd Tuesday of next month:

new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))

As @mrroot5 points out dateutil's rrule functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.

from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)

#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)

#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
    print(ld)

#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
    print(tuesday)

Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00

2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00

This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Webpack and Browserify

Webpack and Browserify do pretty much the same job, which is processing your code to be used in a target environment (mainly browser, though you can target other environments like Node). Result of such processing is one or more bundles - assembled scripts suitable for targeted environment.

For example, let's say you wrote ES6 code divided into modules and want to be able to run it in a browser. If those modules are Node modules, the browser won't understand them since they exist only in the Node environment. ES6 modules also won't work in older browsers like IE11. Moreover, you might have used experimental language features (ES next proposals) that browsers don't implement yet so running such script would just throw errors. Tools like Webpack and Browserify solve these problems by translating such code to a form a browser is able to execute. On top of that, they make it possible to apply a huge variety of optimisations on those bundles.

However, Webpack and Browserify differ in many ways, Webpack offers many tools by default (e.g. code splitting), while Browserify can do this only after downloading plugins but using both leads to very similar results. It comes down to personal preference (Webpack is trendier). Btw, Webpack is not a task runner, it is just processor of your files (it processes them by so called loaders and plugins) and it can be run (among other ways) by a task runner.


Webpack Dev Server

Webpack Dev Server provides a similar solution to Browsersync - a development server where you can deploy your app rapidly as you are working on it, and verify your development progress immediately, with the dev server automatically refreshing the browser on code changes or even propagating changed code to browser without reloading with so called hot module replacement.


Task runners vs NPM scripts

I've been using Gulp for its conciseness and easy task writing, but have later found out I need neither Gulp nor Grunt at all. Everything I have ever needed could have been done using NPM scripts to run 3rd-party tools through their API. Choosing between Gulp, Grunt or NPM scripts depends on taste and experience of your team.

While tasks in Gulp or Grunt are easy to read even for people not so familiar with JS, it is yet another tool to require and learn and I personally prefer to narrow my dependencies and make things simple. On the other hand, replacing these tasks with the combination of NPM scripts and (propably JS) scripts which run those 3rd party tools (eg. Node script configuring and running rimraf for cleaning purposes) might be more challenging. But in the majority of cases, those three are equal in terms of their results.


Examples

As for the examples, I suggest you have a look at this React starter project, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in package.json in the root folder, in a property named scripts. There you will mostly encounter commands like babel-node tools/run start. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 file tools/run (run.js file located in tools) - basically a runner utility. This runner takes a function as an argument and executes it, which in this case is start - another utility (start.js) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).

Speaking more precisely, start.js creates both client and server side bundles, starts an express server and after a successful launch initializes Browser-sync, which at the time of writing looked like this (please refer to react starter project for the newest code).

const bs = Browsersync.create();  
bs.init({
      ...(DEBUG ? {} : { notify: false, ui: false }),

      proxy: {
        target: host,
        middleware: [wpMiddleware, ...hotMiddlewares],
      },

      // no need to watch '*.js' here, webpack will take care of it for us,
      // including full page reloads if HMR won't work
      files: ['build/content/**/*.*'],
}, resolve)

The important part is proxy.target, where they set server address they want to proxy, which could be http://localhost:3000, and Browsersync starts a server listening on http://localhost:3001, where the generated assets are served with automatic change detection and hot module replacement. As you can see, there is another configuration property files with individual files or patterns Browser-sync watches for changes and reloads the browser if some occur, but as the comment says, Webpack takes care of watching js sources by itself with HMR, so they cooperate there.

Now I don't have any equivalent example of such Grunt or Gulp configuration, but with Gulp (and somewhat similarly with Grunt) you would write individual tasks in gulpfile.js like

gulp.task('bundle', function() {
  // bundling source files with some gulp plugins like gulp-webpack maybe
});

gulp.task('start', function() {
  // starting server and stuff
});

where you would be doing essentially pretty much the same things as in the starter-kit, this time with task runner, which solves some problems for you, but presents its own issues and some difficulties during learning the usage, and as I say, the more dependencies you have, the more can go wrong. And that is the reason I like to get rid of such tools.

How to get current route in react-router 2.0.0-rc5

You could use the 'isActive' prop like so:

const { router } = this.context;
if (router.isActive('/login')) {
    router.push('/');
}

isActive will return a true or false.

Tested with react-router 2.7

How to debug "ImagePullBackOff"?

On GKE, if the pod is dead, it's best to check for the events. It will show in more detail what the error is about.

In my case, I had :

Failed to pull image "gcr.io/project/imagename@sha256:c8e91af54fc17faa1c49e2a05def5cbabf8f0a67fc558eb6cbca138061a8400a":
 rpc error: code = Unknown desc = error pulling image configuration: unknown blob

It turned out the image was damaged somehow. After repushing it and deploying with the new hash, it worked again.

Can I use an HTML input type "date" to collect only a year?

You can do the following:

  1. Generate an Array of the years I'll be accepting,
  2. Use a select box.
  3. Use each item from your Array as an 'option' tag.

Example using PHP (you can do this in any language of your choice):

Server:

<?php $years = range(1900, strftime("%Y", time())); ?>

HTML

<select>
  <option>Select Year</option>
  <?php foreach($years as $year) : ?>
    <option value="<?php echo $year; ?>"><?php echo $year; ?></option>
  <?php endforeach; ?>
</select>

As an added benefit, this works has a browser compatibility of a 100% ;-)

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I also experienced this error.

I add into header Content-Type: application/json. Following the change, my submissions succeed!

ValueError: not enough values to unpack (expected 11, got 1)

Looks like something is wrong with your data, it isn't in the format you are expecting. It could be a new line character or a blank space in the data that is tinkering with your code.

Jquery to open Bootstrap v3 modal of remote url

So basically, in jquery what we can do is to load href attribute using the load function. This way we can use the url in <a> tag and load that in modal-body.

<a  href='/site/login' class='ls-modal'>Login</a>

//JS script
$('.ls-modal').on('click', function(e){
  e.preventDefault();
  $('#myModal').modal('show').find('.modal-body').load($(this).attr('href'));
});

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

From here:

Root Cause: Maximum connection has been exceeded on your SQL Server Instance.

How to fix it...!

  1. F8 or Object Explorer
  2. Right click on Instance --> Click Properties...
  3. Select "Connections" on "Select a page" area at left
  4. Chenge the value to 0 (Zero) for "Maximum number of concurrent connections(0 = Unlimited)"
  5. Restart the SQL Server Instance once.

Apart from that also ensure that below are enabled:

  • Shared Memory protocol is enabled
  • Named Pipes protocol is enabled
  • TCP/IP is enabled

Angular2 QuickStart npm start is not working correctly

Change the start field in package.json from:

"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" "

To:

"start": "concurrently \"npm run tsc:w\" \"npm run lite\" "

It really helped.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I experienced a similar error reply while using the openssl command line interface, while having the correct binary key (-K). The option "-nopad" resolved the issue:

Example generating the error:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 | od -t x1

Result:

bad decrypt
140181876450560:error:06065064:digital envelope 
routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c:535:
0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38

Example with correct result:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 -nopad | od -t x1

Result:

0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38
0000060 30 30 30 34 31 33 31 2f 2f 2f 2f 2f 2f 2f 2f 2f
0000100

Warning about SSL connection when connecting to MySQL database

Mention the url like:

jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&useSSL=false

But in xml configuration when you mention & sign, the IDE shows below error:

The reference to entity "useSSL" must end with the ';' delimiter.

And then you have to explicitly use the &amp; instead of & to be determined as & by xml thereafter in xml you have to give the url in xml configuration like this:

<property name="connection.url">jdbc:mysql://hostname:3306/hibernatedb?autoReconnect=true&amp;useSSL=false</property>

react-native - Fit Image in containing View, not the whole screen size

If you know the aspect ratio for example, if your image is square you can set either the height or the width to fill the container and get the other to be set by the aspectRatio property

Here is the style if you want the height be set automatically:

{
    width: '100%',
    height: undefined,
    aspectRatio: 1,
}

Note: height must be undefined

Bootstrap 4 - Responsive cards in card-columns

I have created a Cards Layout - 3 cards in a row using Bootstrap 4 / CSS3 (of course its responsive). The following example uses basic Bootstrap 4 classes such as container, row, col-x, list-group and list-group-item. Thought to share here if someone is interested in this sort of a layout.

enter image description here

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">        
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
  </div>
</div>

CSS / SCSS

$primary-color: #ccc;
$col-bg-color: #eee;
$col-footer-bg-color: #eee;
$col-header-bg-color: #007bff;
$col-content-bg-color: #fff;

body {
  background-color: $primary-color;
}  

.custom-column {  
  background-color: $col-bg-color;
  border: 5px solid $col-bg-color;    
  padding: 10px;
  box-sizing: border-box;  
}

.custom-column-header {
  font-size: 24px;
  background-color: #007bff;  
  color: white;
  padding: 15px;  
  text-align: center;
}

.custom-column-content {
  background-color: $col-content-bg-color;
  border: 2px solid white;  
  padding: 20px;  
}

.custom-column-footer {
  background-color: $col-footer-bg-color;   
  padding-top: 20px;
  text-align: center;
}

Link :- https://codepen.io/anjanasilva/pen/JmdOpb

Failed to authenticate on SMTP server error using gmail

Change the .env file as follow

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

And the go to the gmail security section ->Allow Less secure app access

Then run

php artisan config:clear

Refresh the site

Java: Local variable mi defined in an enclosing scope must be final or effectively final

The error means you cannot use the local variable mi inside an inner class.


To use a variable inside an inner class you must declare it final. As long as mi is the counter of the loop and final variables cannot be assigned, you must create a workaround to get mi value in a final variable that can be accessed inside inner class:

final Integer innerMi = new Integer(mi);

So your code will be like this:

for (int mi=0; mi<colors.length; mi++){

    String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);
    JMenuItem Jmi =new JMenuItem(pos);
    Jmi.setIcon(new IconA(colors[mi]));

    // workaround:
    final Integer innerMi = new Integer(mi);

    Jmi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem item = (JMenuItem) e.getSource();
                IconA icon = (IconA) item.getIcon();
                // HERE YOU USE THE FINAL innerMi variable and no errors!!!
                Color kolorIkony = getColour(colors[innerMi]); 
                textArea.setForeground(kolorIkony);
            }
        });

        mnForeground.add(Jmi);
    }
}

How to use Bootstrap modal using the anchor tag for Register?

Here is a link to W3Schools that answers your question https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp

Note: For anchor tag elements, omit data-target, and use href="#modalID" instead:

I hope that helps

In android how to set navigation drawer header image and name programmatically in class file?

EDIT : Works with design library upto 23.0.1 but doesn't work on 23.1.0

In main layout xml you will have NavigationView defined, in that use app:headerLayout to set the header view.

<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_drawer_header"
        app:menu="@menu/navigation_drawer_menu" />

And the @layout/nav_drawer_header will be the place holder of the image and texts.

nav_drawer_header.xml

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

<RelativeLayout
    android:id="@+id/headerRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:src="@drawable/background" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/action_bar_size"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#40000000"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="35dp"
            android:orientation="vertical"
            android:weightSum="2">


            <TextView
                android:id="@+id/navHeaderTitle"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@android:color/white" />

            <TextView
                android:id="@+id/navHeaderSubTitle"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@android:color/white" />

        </LinearLayout>

    </LinearLayout>
</RelativeLayout>
</LinearLayout>

And in your main class, you can take handle of Imageview and TextView as like normal other views.

TextView navHeaderTitle = (TextView) findViewById(R.id.navHeaderTitle);
navHeaderTitle.setText("Application Name");

TextView navHeaderSubTitle = (TextView) findViewById(R.id.navHeaderSubTitle);
navHeaderSubTitle.setText("Application Caption");

Hope this helps.

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Close Bootstrap modal on form submit

I am using rails and ajax too and I had the same problem. just run this code

 $('#modalName').modal('hide');

that worked for me but I am trying to also fix it without using jQuery.

Laravel 5.1 - Checking a Database Connection

You can use alexw's solution with the Artisan. Run following commands in the command line.

php artisan tinker
DB::connection()->getPdo();

If connection is OK, you should see

CONNECTION_STATUS: "Connection OK; waiting to send.",

near the end of the response.

Unable to install boto3

Do not run as sudo, just type:

pip3 install boto3==1.7.40 --user

Enjoy

Python - Extracting and Saving Video Frames

This is Function which will convert most of the video formats to number of frames there are in the video. It works on Python3 with OpenCV 3+

import cv2
import time
import os

def video_to_frames(input_loc, output_loc):
    """Function to extract frames from input video file
    and save them as separate frames in an output directory.
    Args:
        input_loc: Input video file.
        output_loc: Output directory to save the frames.
    Returns:
        None
    """
    try:
        os.mkdir(output_loc)
    except OSError:
        pass
    # Log the time
    time_start = time.time()
    # Start capturing the feed
    cap = cv2.VideoCapture(input_loc)
    # Find the number of frames
    video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
    print ("Number of frames: ", video_length)
    count = 0
    print ("Converting video..\n")
    # Start converting the video
    while cap.isOpened():
        # Extract the frame
        ret, frame = cap.read()
        # Write the results back to output location.
        cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
        count = count + 1
        # If there are no more frames left
        if (count > (video_length-1)):
            # Log the time again
            time_end = time.time()
            # Release the feed
            cap.release()
            # Print stats
            print ("Done extracting frames.\n%d frames extracted" % count)
            print ("It took %d seconds forconversion." % (time_end-time_start))
            break

if __name__=="__main__":

    input_loc = '/path/to/video/00009.MTS'
    output_loc = '/path/to/output/frames/'
    video_to_frames(input_loc, output_loc)

It supports .mts and normal files like .mp4 and .avi. Tried and Tested on .mts files. Works like a Charm.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

If you transferred these files through disk or other means, it is likely they were not saved properly.

TypeError: a bytes-like object is required, not 'str'

Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort)) to clientSocket.sendto(message.encode(),(serverName, serverPort)). Then you would successfully run in in python3

Laravel migration table field's type change

update: 31 Oct 2018, Still usable on laravel 5.7 https://laravel.com/docs/5.7/migrations#modifying-columns

To make some change to existing db, you can modify column type by using change() in migration.

This is what you could do

Schema::table('orders', function ($table) {
    $table->string('category_id')->change();
});

please note you need to add doctrine/dbal dependency to composer.json for more information you can find it here http://laravel.com/docs/5.1/migrations#modifying-columns

Error: Execution failed for task ':app:clean'. Unable to delete file

if you're still having issues then update to the latest version of Android Studio(its 2.1 as of now), might be it was a bug with older version of Android Studio. Its resolved for me now.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

I experienced this exception, and it was also related to ServicePointManager.SecurityProtocol.

For me, this was because ServicePointManager.SecurityProtocol had been set to Tls | Tls11 (because of certain websites the application visits with broken TLS 1.2) and upon visiting a TLS 1.2-only website (tested with SSLLabs' SSL Report), it failed.

An option for .NET 4.5 and higher is to enable all TLS versions:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                     | SecurityProtocolType.Tls11
                                     | SecurityProtocolType.Tls12;

Android M Permissions: onRequestPermissionsResult() not being called

Here i want to show my code how i managed this.

public class CheckPermission {

public Context context;

public static final int PERMISSION_REQUEST_CODE =  200;

public CheckPermission(Context context){
    this.context = context;
}

public boolean isPermissionGranted(){
    int read_contact = ContextCompat.checkSelfPermission(context.getApplicationContext() , READ_CONTACTS);
    int phone = ContextCompat.checkSelfPermission(context.getApplicationContext() , CALL_PHONE);

    return read_contact == PackageManager.PERMISSION_GRANTED && phone == PackageManager.PERMISSION_GRANTED;
   }
}

Here in this class i want to check permission granted or not. Is not then i will call permission from my MainActivity like

public void requestForPermission() {
       ActivityCompat.requestPermissions(MainActivity.this, new String[]    {READ_CONTACTS, CALL_PHONE}, PERMISSION_REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
                    showMessageOKCancel("You need to allow access to both the permissions",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE},
                                                PERMISSION_REQUEST_CODE);
                                    }
                                }
                            });
                    return;
                }
            }
    }
}

Now in the onCreate method you need to call requestForPermission() function.

That's it.Also you can request multiple permission at a time.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Download the android SDK http://developer.android.com/sdk/installing/index.html

You only export the path of SDK folder.

export ANDROID_HOME="YOUR_PATH/sdk/"

Detect click outside React component

I found this from the article below:

render() { return ( { this.node = node; }} > Toggle Popover {this.state.popupVisible && ( I'm a popover! )} ); } }

Here is a great article about this issue: "Handle clicks outside of React components" https://larsgraubner.com/handle-outside-clicks-react/

"psql: could not connect to server: Connection refused" Error when connecting to remote database

cd /etc/postgresql/9.x/main/

open file named postgresql.conf

sudo vi postgresql.conf

add this line to that file

listen_addresses = '*'

then open file named pg_hba.conf

sudo vi pg_hba.conf

and add this line to that file

host  all  all 0.0.0.0/0 md5

It allows access to all databases for all users with an encrypted password

restart your server

sudo /etc/init.d/postgresql restart

What is the right way to debug in iPython notebook?

Just type import pdb in jupyter notebook, and then use this cheatsheet to debug. It's very convenient.

c --> continue, s --> step, b 12 --> set break point at line 12 and so on.

Some useful links: Python Official Document on pdb, Python pdb debugger examples for better understanding how to use the debugger commands.

Some useful screenshots: enter image description hereenter image description here

Bootstrap : TypeError: $(...).modal is not a function

If you are using any layout page then, move script sections from bottom to head section in layout page. bcz, javascript files should be loaded first. This worked for me

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

I had to set

C:\ProgramData\MySQL\MySQL Server 8.0/my.ini  secure-file-priv=""

When I commented line with secure-file-priv, secure-file-priv was null and I couldn't download data.

Docker Compose wait for container X before starting Y

Quite recently they've added the depends_on feature.

Edit:

As of compose version 2.1+ till version 3 you can use depends_on in conjunction with healthcheck to achieve this:

From the docs:

version: '2.1'
services:
  web:
    build: .
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
  redis:
    image: redis
  db:
    image: redis
    healthcheck:
      test: "exit 0"

Before version 2.1

You can still use depends_on, but it only effects the order in which services are started - not if they are ready before the dependant service is started.

It seems to require at least version 1.6.0.

Usage would look something like this:

version: '2'
services:
  web:
    build: .
    depends_on:
      - db
      - redis
  redis:
    image: redis
  db:
    image: postgres 

From the docs:

Express dependency between services, which has two effects:

  • docker-compose up will start services in dependency order. In the following example, db and redis will be started before web.
  • docker-compose up SERVICE will automatically include SERVICE’s dependencies. In the following example, docker-compose up web will also create and start db and redis.

Note: As I understand it, although this does set the order in which containers are loaded. It does not guarantee that the service inside the container has actually loaded.

For example, you postgres container might be up. But the postgres service itself might still be initializing within the container.

Error: package or namespace load failed for ggplot2 and for data.table

I had this same problem, but when running in a jupyter R notebook in an Anaconda environment.

The problem presented in such a way that any R notebook opened would instantly die and would not allow cell execution. The error would show up with each failed automated attempt to start the kernel:

Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) : 
  there is no package called ‘Rcpp’

To solve this, I ran as admin/sudo: conda install -c r r-rcpp, restarted the kernel, and everything was back to normal.

Error 405 (Method Not Allowed) Laravel 5

In my case the route in my router was:

Route::post('/new-order', 'Api\OrderController@initiateOrder')->name('newOrder');

and from the client app I was posting the request to:

https://my-domain/api/new-order/

So, because of the trailing slash I got a 405. Hope it helps someone

How to select rows in a DataFrame between two values, in Python Pandas?

Consider also series between:

df = df[df['closing_price'].between(99, 101)]

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Simplest way to throw an error/exception with a custom message in Swift 2?

I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:

struct RuntimeError: LocalizedError
{
    let message: String

    init(_ message: String)
    {
        self.message = message
    }

    public var errorDescription: String?
    {
        return message
    }
}

See this answer for more details.

Node JS Promise.all and forEach

Just to add to the solution presented, in my case I wanted to fetch multiple data from Firebase for a list of products. Here is how I did it:

useEffect(() => {
  const fn = p => firebase.firestore().doc(`products/${p.id}`).get();
  const actions = data.occasion.products.map(fn);
  const results = Promise.all(actions);
  results.then(data => {
    const newProducts = [];
    data.forEach(p => {
      newProducts.push({ id: p.id, ...p.data() });
    });
    setProducts(newProducts);
  });
}, [data]);

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Simply remove "DEFINER=your user name@localhost" and run the SQL from phpmyadminwill works fine.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

You should put your component between an enclosing tag, Which means:

// WRONG!

return (  
    <Comp1 />
    <Comp2 />
)

Instead:

// Correct

return (
    <div>
       <Comp1 />
       <Comp2 />
    </div>
)

Edit: Per Joe Clay's comment about the Fragments API

// More Correct

return (
    <React.Fragment>
       <Comp1 />
       <Comp2 />
    </React.Fragment>
)

// Short syntax

return (
    <>
       <Comp1 />
       <Comp2 />
    </>
)

Python, Pandas : write content of DataFrame into text File

The current best way to do this is to use df.to_string() :

with open(writePath, 'a') as f:
    f.write(
        df.to_string(header = False, index = False)
    )

Will output the following

18 55 1 70   
18 55 2 67 
18 57 2 75     
18 58 1 35  
19 54 2 70 

This method also lets you easily choose which columns to print with the columns attribute, lets you keep the column, index labels if you wish, and has other attributes for spacing ect.

Navigation drawer: How do I set the selected item at startup?

on your activity(behind the drawer):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar,
               R.string.navigation_drawer_open,
               R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setCheckedItem(R.id.nav_portfolio);
    onNavigationItemSelected(navigationView.getMenu().getItem(0));
}

and

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    Fragment fragment = null;

    if (id == R.id.nav_test1) {
        fragment = new Test1Fragment();
        displaySelectedFragment(fragment);
    } else if (id == R.id.nav_test2) {
        fragment = new Test2Fragment();
        displaySelectedFragment(fragment);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

and in your menu:

<group android:checkableBehavior="single">

    <item
        android:id="@+id/nav_test1"
        android:title="@string/test1" />

    <item
        android:id="@+id/nav_test2"
        android:title="@string/test2" />

  </group>

so first menu is highlight and show as default menu.

PHP: Call to undefined function: simplexml_load_string()

Make sure that you have php-xml module installed and enabled in php.ini.

You can also change response format to json which is easier to handle. In that case you have to only add &format=json to url query string.

$rest_url = "http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls=".urlencode($source_url);

And then use json_decode() to retrieve data in your script:

$result = json_decode($content, true);
$fb_like_count = $result['like_count'];

ionic build Android | error: No installed build tools found. Please install the Android build tools

Go to D:Android sdk\Android SDK and click on SDK Manager and check whether Build Tools are installed or not if they are not installed then install those tools

How to use confirm using sweet alert?

I have been having this issue with SweetAlert2 as well. SA2 differs from 1 and puts everything inside the result object. The following above can be accomplished with the following code.

Swal.fire({
    title: 'A cool title',
    icon: 'info',
    confirmButtonText: 'Log in'
  }).then((result) => {
    if (result['isConfirmed']){
      // Put your function here
    }
  })

Everything placed inside the then result will run. Result holds a couple of parameters which can be used to do the trick. Pretty simple technique. Not sure if it works the same on SweetAlert1 but I really wouldn't know why you would choose that one above the newer version.

Saving response from Requests to file

I believe all the existing answers contain the relevant information, but I would like to summarize.

The response object that is returned by requests get and post operations contains two useful attributes:

Response attributes

  • response.text - Contains str with the response text.
  • response.content - Contains bytes with the raw response content.

You should choose one or other of these attributes depending on the type of response you expect.

  • For text-based responses (html, json, yaml, etc) you would use response.text
  • For binary-based responses (jpg, png, zip, xls, etc) you would use response.content.

Writing response to file

When writing responses to file you need to use the open function with the appropriate file write mode.

  • For text responses you need to use "w" - plain write mode.
  • For binary responses you need to use "wb" - binary write mode.

Examples

Text request and save

# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
    f.write(response.text)

Binary request and save

# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
    f.write(response.content)

Answering the original question

The original code should work by using wb and response.content:

import requests

files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()

But I would go further and use the with context manager for open.

import requests

with open('1.pdf', 'rb') as file:
    files = {'f': ('1.pdf', file)}
    response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)

response.raise_for_status() # ensure we notice bad responses

with open("out.xls", "wb") as file:
    file.write(response.content)

Not an enclosing class error Android Studio

you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....

Cordova - Error code 1 for command | Command failed for

Delete platforms/android folder and try to rebuild. That helped me a lot.

(Visual Studio Tools for Apache Cordova)

How to show Snackbar when Activity starts?

You can try this library. This is a wrapper for android default snackbar. https://github.com/ChathuraHettiarachchi/CSnackBar

Snackbar.with(this,null)
    .type(Type.SUCCESS)
    .message("Profile updated successfully!")
    .duration(Duration.SHORT)
    .show();

This contains multiple types of snackbar and even a customview intergrated snackbar

Expected corresponding JSX closing tag for input Reactjs

This error also happens if you have got the order of your components wrong.

Example: this wrong:

 <ComponentA> 
    <ComponentB> 

    </ComponentA> 
 </ComponentB> 

correct way:

  <ComponentA> 
    <ComponentB>

    </ComponentB>  
  </ComponentA> 

Swift do-try-catch syntax

I was also disappointed by the lack of type a function can throw, but I get it now thanks to @rickster and I'll summarize it like this: let's say we could specify the type a function throws, we would have something like this:

enum MyError: ErrorType { case ErrorA, ErrorB }

func myFunctionThatThrows() throws MyError { ...throw .ErrorA...throw .ErrorB... }

do {
    try myFunctionThatThrows()
}
case .ErrorA { ... }
case .ErrorB { ... }

The problem is that even if we don't change anything in myFunctionThatThrows, if we just add an error case to MyError:

enum MyError: ErrorType { case ErrorA, ErrorB, ErrorC }

we are screwed because our do/try/catch is no longer exhaustive, as well as any other place where we called functions that throw MyError

Authentication failed because remote party has closed the transport stream

I would advise against restricting the SecurityProtocol to TLS 1.1.

The recommended solution is to use

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls

Another option is add the following Registry key:

Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319 
Value: SchUseStrongCrypto 

It is worth noting that .NET 4.6 will use the correct protocol by default and does not require either solution.

Go doing a GET request and building the Querystring

Using NewRequest just to create an URL is an overkill. Use the net/url package:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    base, err := url.Parse("http://www.example.com")
    if err != nil {
        return
    }

    // Path params
    base.Path += "this will get automatically encoded"

    // Query params
    params := url.Values{}
    params.Add("q", "this will get encoded as well")
    base.RawQuery = params.Encode() 

    fmt.Printf("Encoded URL is %q\n", base.String())
}

Playground: https://play.golang.org/p/YCTvdluws-r

How to specify the JDK version in android studio?

In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:

Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

If using Nginx and getting a similar problem, then this might help:

Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.

If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

Simple InputBox function

The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.

$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString

This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))

If the info does not need to be secure at all you can convert it to plain text:

$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))

Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0

Android: keep Service running when app is killed

You can use android:stopWithTask="false"in manifest as bellow, This means even if user kills app by removing it from tasklist, your service won't stop.

 <service android:name=".service.StickyService"
                  android:stopWithTask="false"/>

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

For all the Windows users, try moving your codebase to a shorter windows path for eg: C:/myProj

Deeply nested Maven jar files can create a longer file path in windows. Since windows OS, by default, limits the file path length to 260 characters, it throws exception when trying to read a file located at a path that becomes more than 260 characters.

You can change this default to increase this limit to more than 260 chracters. Search around the web and you will find many posts on how to do that.

You can face similar problem while using npm packages also.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Make sure that while using : Button "varName" =findViewById("btID"); you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.

How do I edit $PATH (.bash_profile) on OSX?

For beginners: To create your .bash_profile file in your home directory on MacOS, run:

nano ~/.bash_profile

Then you can paste in the following:

https://gist.github.com/mocon/0baf15e62163a07cb957888559d1b054

As you can see, it includes some example aliases and an environment variable at the bottom.

One you're done making your changes, follow the instructions at the bottom of the Nano editor window to WriteOut (Ctrl-O) and Exit (Ctrl-X). Then quit your Terminal and reopen it, and you will be able to use your newly defined aliases and environment variables.

Correct way to set Bearer token with CURL

Guzzle example:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$token = 'your_token';

$httpClient = new Client();

$response = $httpClient->get(
    'https://httpbin.org/bearer',
    [
        RequestOptions::HEADERS => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $token,
        ]
    ]
);

print_r($response->getBody()->getContents());

See https://github.com/andriichuk/php-curl-cookbook#bearer-auth

Capture close event on Bootstrap Modal

I was having this same problem in a web app using Microsoft Visual Studio 2019, Asp.Net 3.1 and Bootstrap 4.5. I had a modal form open to add a new staff person (only a few input fields) and the Add Staff button would invoke an ajax call to create the staff records in the database. Upon successful return the code would refresh the partial razor page of staff (so the new staff person would appear in the list).

Just before the refresh I would close the Add Staff modal and display a Please Wait modal which only had a bootstrap spinner button on it. What happened is that the Please Wait modal would stay displayed and not close after the staff refresh and the modal('hide') function on this modal was called. Some times the modal would disappear but the modal backdrop would remain effectively locking the Staff List form.

Since Bootstrap has issues with multiple modals open at once, I thought maybe the Add Staff modal was still open when the Please Wait modal was displayed and this was causing problems. I made a function to display the Please Wait modal and do the refresh, and called it using the Javascript function setTimeout() to wait 1/2 second after closing/hiding the Add Staff modal:

//hide the modal form
$("#addNewStaffModal").modal('hide');
setTimeout(RefreshStaffListAfterAddingStaff, 500); //wait for 1/2 second

Here is the code for the refresh function:

function RefreshStaffListAfterAddingStaff() {
    // refresh the staff list in our partial view

    //show the please wait message
    $('#PleaseWaitModal').modal('show');

    //refresh the partial view
    $('#StaffAccountsPartialView').load('StaffAccounts?handler=StaffAccountsPartial',
        function (data, status, jqXGR) {

            //hide the wait modal
            $('#PleaseWaitModal').modal('hide');
            // enable all the fields on our form
            $("#StaffAccountsForm :input").prop("disabled", false);

            //scroll to the top of the staff list window
            window.scroll({
                top: 0,
                left: 0,
                behavior: 'smooth'
            });

        });
}

This seems to have totally solved my problem!

TLS 1.2 not working in cURL

TLS 1.1 and TLS 1.2 are supported since OpenSSL 1.0.1

Forcing TLS 1.1 and 1.2 are only supported since curl 7.34.0

You should consider an upgrade.

Cannot get a text value from a numeric cell “Poi”

CellType cell = row.getCell(j).getCellTypeEnum();

switch(cell) {
    case NUMERIC:
        intVal = row.getCell(j).getNumericCellValue();
        System.out.print(intVal);
        break;
    case STRING:
        stringVal = row.getCell(j).getStringCellValue();
        System.out.print(stringVal);
        break;
}

How do I jump to a closing bracket in Visual Studio Code?

Another Default Method:

Try pressing the ending bracket key ) again. It will move your cursor to the end of the brackets. I think it's a good practice to have the habit of typing both brackets.

laravel-5 passing variable to JavaScript

The best way for me was to put it in a hidden div in php blade

<div hidden id="token">{{$token}}</div>

then call it in javascript as a constant to avoid undefined var errors

const token = document.querySelector('div[id=token]').textContent

// console.log(token)
// eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiI5MjNlOTcyMi02N2NmLTQ4M2UtYTk4Mi01YmE5YTI0Y2M2MzMiLCJqdGkiOiI2Y2I1ZGRhNzRhZjNhYTkwNzA3ZjMzMDFiYjBiZDUzNTZjNjYxMGUyZWJlNmYzOTI5NzBmMjNjNDdiNjhjY2FiYjI0ZWVmMzYwZmNiZDBmNyIsImlhdCI6IjE2MDgwODMyNTYuNTE2NjE4IiwibmJmIjoiMTYwODA4MzI1Ni41MTY2MjUiLCJleHAiOiIxNjIzODA4MDU2LjMxMTg5NSIsInN1YiI6IjUiLCJzY29wZXMiOlsiYWRtaW4iXX0.GbKZ8CIjt3otzFyE5aZEkNBCtn75ApIfS6QbnD6z0nxDjycknQaQYz2EGems9Z3Qjabe5PA9zL1mVnycCieeQfpLvWL9xDu9hKkIMs006Sznrp8gWy6JK8qX4Xx3GkzWEx8Z7ZZmhsKUgEyRkqnKJ-1BqC2tTiTBqBAO6pK_Pz7H74gV95dsMiys9afPKP5ztW93kwaC-pj4h-vv-GftXXc6XDnUhTppT4qxn1r2Hf7k-NXE_IHq4ZPb20LRXboH0RnbJgq2JA1E3WFX5_a6FeWJvLlLnGGNOT0ocdNZq7nTGWwfocHlv6pH0NFaKa3hLoRh79d5KO_nysPVCDt7jYOMnpiq8ybIbe3oYjlWyk_rdQ9067bnsfxyexQwLC3IJpAH27Az8FQuOQMZg2HJhK8WtWUph5bsYUU0O2uPG8HY9922yTGYwzeMEdAqBss85jdpMNuECtlIFM1Pc4S-0nrCtBE_tNXn8ATDrm6FecdSK8KnnrCOSsZhR04MvTyznqCMAnKtN_vMDpmIAmPd181UanjO_kxR7QIlsEmT_UhM1MBmyfdIEvHkgLgUdUouonjQNvOKwCrrgDkP0hkZQff-iuHPwpL-CUjw7GPa70lp-TIDhfei8T90RkAXte1XKv7ku3sgENHTwPrL9QSrNtdc5MfB9AbUV-tFMJn9T7k

Java - Writing strings to a CSV file

    String filepath="/tmp/employee.csv";
    FileWriter sw = new FileWriter(new File(filepath));
    CSVWriter writer = new CSVWriter(sw);
    writer.writeAll(allRows);

    String[] header= new String[]{"ErrorMessage"};
    writer.writeNext(header);

    List<String[]> errorData = new ArrayList<String[]>();
    for(int i=0;i<1;i++){
        String[] data = new String[]{"ErrorMessage"+i};
        errorData.add(data);
    }
    writer.writeAll(errorData);

    writer.close();

RSA encryption and decryption in Python

Here is my implementation for python 3 and pycrypto

from Crypto.PublicKey import RSA
key = RSA.generate(4096)
f = open('/home/john/Desktop/my_rsa_public.pem', 'wb')
f.write(key.publickey().exportKey('PEM'))
f.close()
f = open('/home/john/Desktop/my_rsa_private.pem', 'wb')
f.write(key.exportKey('PEM'))
f.close()

f = open('/home/john/Desktop/my_rsa_public.pem', 'rb')
f1 = open('/home/john/Desktop/my_rsa_private.pem', 'rb')
key = RSA.importKey(f.read())
key1 = RSA.importKey(f1.read())

x = key.encrypt(b"dddddd",32)

print(x)
z = key1.decrypt(x)
print(z)

How to use Visual Studio Code as Default Editor for Git

I set up Visual Studio Code as a default to open .txt file. And next I did use simple command: git config --global core.editor "'C:\Users\UserName\AppData\Local\Code\app-0.7.10\Code.exe\'". And everything works pretty well.

AngularJS open modal on button click

I am not sure,how you are opening popup or say model in your code. But you can try something like this..

<html ng-app="MyApp">
<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css" />

<script type="text/javascript">
    var myApp = angular.module("MyApp", []);
    myApp.controller('MyController', function ($scope) {
      $scope.open = function(){
        var modalInstance = $modal.open({
                        templateUrl: '/assets/yourOpupTemplatename.html',
                        backdrop:'static',
                        keyboard:false,
                        controller: function($scope, $modalInstance) {
                            $scope.cancel = function() {
                                $modalInstance.dismiss('cancel');
                            };
                            $scope.ok = function () {
                              $modalInstance.close();
                            };
                        }
                    });
      }
    });
</script>
</head>
<body ng-controller="MyController">

    <button class="btn btn-primary" ng-click="open()">Test Modal</button>

    <!-- Confirmation Dialog -->
    <div class="modal">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            <h4 class="modal-title">Delete confirmation</h4>
          </div>
          <div class="modal-body">
            <p>Are you sure?</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" ng-click="cancel()">No</button>
            <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
          </div>
        </div>
      </div>
    </div>
    <!-- End of Confirmation Dialog -->

 </body>
 </html>

Change user-agent for Selenium web-driver

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

Setting the User Agent in Firefox

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

Both methods above were tested and found to work. I don't know about other browsers.

Getting the User Agent

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

The agent variable will contain the user agent.

How can I pipe stderr, and not stdout?

First redirect stderr to stdout — the pipe; then redirect stdout to /dev/null (without changing where stderr is going):

command 2>&1 >/dev/null | grep 'something'

For the details of I/O redirection in all its variety, see the chapter on Redirections in the Bash reference manual.

Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation 2>&1 makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see dup2() and open()). The operation >/dev/null then changes file descriptor 1 so that it refers to an open file description for /dev/null, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How to remove from a map while iterating it?

The standard associative-container erase idiom:

for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it++);    // or "it = m.erase(it)" since C++11
  }
  else
  {
    ++it;
  }
}

Note that we really want an ordinary for loop here, since we are modifying the container itself. The range-based loop should be strictly reserved for situations where we only care about the elements. The syntax for the RBFL makes this clear by not even exposing the container inside the loop body.

Edit. Pre-C++11, you could not erase const-iterators. There you would have to say:

for (std::map<K,V>::iterator it = m.begin(); it != m.end(); ) { /* ... */ }

Erasing an element from a container is not at odds with constness of the element. By analogy, it has always been perfectly legitimate to delete p where p is a pointer-to-constant. Constness does not constrain lifetime; const values in C++ can still stop existing.

TypeError: 'NoneType' object has no attribute '__getitem__'

The function move.CompleteMove(events) that you use within your class probably doesn't contain a return statement. So nothing is returned to self.values (==> None). Use return in move.CompleteMove(events) to return whatever you want to store in self.values and it should work. Hope this helps.

How to wait for async method to complete?

Here is a workaround using a flag:

//outside your event or method, but inside your class
private bool IsExecuted = false;

private async Task MethodA()
{

//Do Stuff Here

IsExecuted = true;
}

.
.
.

//Inside your event or method

{
await MethodA();

while (!isExecuted) Thread.Sleep(200); // <-------

await MethodB();
}

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Have a look at the GROUP_CONCAT project on Github, I think I does exactly what you are searching for:

This project contains a set of SQLCLR User-defined Aggregate functions (SQLCLR UDAs) that collectively offer similar functionality to the MySQL GROUP_CONCAT function. There are multiple functions to ensure the best performance based on the functionality required...

Conditionally ignoring tests in JUnit 4

A quick note: Assume.assumeTrue(condition) ignores rest of the steps but passes the test. To fail the test, use org.junit.Assert.fail() inside the conditional statement. Works same like Assume.assumeTrue() but fails the test.

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

how to add or embed CKEditor in php page

Alternately, it could also be done as:

<?php
    include("ckeditor/ckeditor.php");
    $CKeditor = new CKeditor();
    $CKeditor->BasePath = 'ckeditor/';
    $CKeditor->editor('editor1');
?>

Note that the last line is having 'editor1' as name, it could be changed as per your requirement.

Using Sockets to send and receive data

    //Client

    import java.io.*;
    import java.net.*;

    public class Client {
        public static void main(String[] args) {

        String hostname = "localhost";
        int port = 6789;

        // declaration section:
        // clientSocket: our client socket
        // os: output stream
        // is: input stream

            Socket clientSocket = null;  
            DataOutputStream os = null;
            BufferedReader is = null;

        // Initialization section:
        // Try to open a socket on the given port
        // Try to open input and output streams

            try {
                clientSocket = new Socket(hostname, port);
                os = new DataOutputStream(clientSocket.getOutputStream());
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: " + hostname);
            }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on the given port

        if (clientSocket == null || os == null || is == null) {
            System.err.println( "Something is wrong. One variable is null." );
            return;
        }

        try {
            while ( true ) {
            System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String keyboardInput = br.readLine();
            os.writeBytes( keyboardInput + "\n" );

            int n = Integer.parseInt( keyboardInput );
            if ( n == 0 || n == -1 ) {
                break;
            }

            String responseLine = is.readLine();
            System.out.println("Server returns its square as: " + responseLine);
            }

            // clean up:
            // close the output stream
            // close the input stream
            // close the socket

            os.close();
            is.close();
            clientSocket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
        }           
    }





//Server




import java.io.*;
import java.net.*;

public class Server1 {
    public static void main(String args[]) {
    int port = 6789;
    Server1 server = new Server1( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int port;

    public Server1( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)

        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }   

    System.out.println( "Waiting for connections. Only one connection is allowed." );

    // Create a socket object from the ServerSocket to listen and accept connections.
    // Use Server1Connection to process the connection.

    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        Server1Connection oneconnection = new Server1Connection(clientSocket, this);
        oneconnection.run();
        }   
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server1Connection {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    Server1 server;

    public Server1Connection(Socket clientSocket, Server1 server) {
    this.clientSocket = clientSocket;
    this.server = server;
    System.out.println( "Connection established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n ); 
            }

        System.out.println( "Connection closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.

Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.

Finding first blank row, then writing to it

ActiveSheet.Range("A10000").End(xlup).offset(1,0).Select

How to watch for array changes?

I used the following code to listen to changes to an array.

/* @arr array you want to listen to
   @callback function that will be called on any change inside array
 */
function listenChangesinArray(arr,callback){
     // Add more methods here if you want to listen to them
    ['pop','push','reverse','shift','unshift','splice','sort'].forEach((m)=>{
        arr[m] = function(){
                     var res = Array.prototype[m].apply(arr, arguments);  // call normal behaviour
                     callback.apply(arr, arguments);  // finally call the callback supplied
                     return res;
                 }
    });
}

Hope this was useful :)

Centering brand logo in Bootstrap Navbar

Try this:

.navbar {
    position: relative;
}
.brand {
    position: absolute;
    left: 50%;
    margin-left: -50px !important;  /* 50% of your logo width */
    display: block;
}

Centering your logo by 50% and minus half of your logo width so that it won't have problem when zooming in and out.

See fiddle

What's the difference between ASCII and Unicode?

java provides support for Unicode i.e it supports all world wide alphabets. Hence the size of char in java is 2 bytes. And range is 0 to 65535.

enter image description here

@synthesize vs @dynamic, what are the differences?

@synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass or will be provided at runtime).

Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet.

@dynamic also can be used to delegate the responsibility of implementing the accessors. If you implement the accessors yourself within the class then you normally do not use @dynamic.

Super class:

@property (nonatomic, retain) NSButton *someButton;
...
@synthesize someButton;

Subclass:

@property (nonatomic, retain) IBOutlet NSButton *someButton;
...
@dynamic someButton;

How to create standard Borderless buttons (like in the design guideline mentioned)?

This is how you create a borderless (flat) button programmatically without using XML

ContextThemeWrapper myContext = new ContextThemeWrapper(this.getActivity(), 
   R.style.Widget_AppCompat_Button_Borderless_Colored);

Button myButton = new Button(myContext, null, 
   R.style.Widget_AppCompat_Button_Borderless_Colored);

Accessing the logged-in user in a template

For symfony 2.6 and above we can use

{{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

JFrame background image

I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:

BufferedImage img = null;
try {
    img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
    e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));

Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.

What is Express.js?

  1. What is Express.js?

Express.js is a Node.js web application server framework, designed for building single-page, multi-page, and hybrid web applications. It is the de facto standard server framework for node.js.

Frameworks built on Express.

Several popular Node.js frameworks are built on Express:

LoopBack: Highly-extensible, open-source Node.js framework for quickly creating dynamic end-to-end REST APIs.

Sails: MVC framework for Node.js for building practical, production-ready apps.

Kraken: Secure and scalable layer that extends Express by providing structure and convention.

MEAN: Opinionated fullstack JavaScript framework that simplifies and accelerates web application development.

  1. What is the purpose of it with Node.js?
  2. Why do we actually need Express.js? How it is useful for us to use with Node.js?

Express adds dead simple routing and support for Connect middleware, allowing many extensions and useful features.

For example,

  • Want sessions? It's there
  • Want POST body / query string parsing? It's there
  • Want easy templating through jade, mustache, ejs, etc? It's there
  • Want graceful error handling that won't cause the entire server to crash?

Regular expression for extracting tag attributes

have a look at this Regex & PHP - isolate src attribute from img tag

perhaps you can walk through the DOM and get the desired attributes. It works fine for me, getting attributes from the body-tag

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

I was getting this error on Vue 3. It was because defineComponent must be imported like this:

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "HelloWorld",
    props: {
        msg: String,
    },
    created() {
        this.testF();
    },
    methods: {
        testF() {
            console.log("testF");
        },
    },
});
</script>

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:

<startup>
  <supportedRuntime version="v2.0.50727"/>
</startup>

So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.

Java - How to access an ArrayList of another class?

You can do this by providing in class numbers:

  • A method that returns the ArrayList object itself.
  • A method that returns a non-modifiable wrapper of the ArrayList. This prevents modification to the list without the knowledge of the class numbers.
  • Methods that provide the set of operations you want to support from class numbers. This allows class numbers to control the set of operations supported.

By the way, there is a strong convention that Java class names are uppercased.

Case 1 (simple getter):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return list; }
      ...
}

Case 2 (non-modifiable wrapper):

public class Numbers {
      private List<Integer> list;
      public List<Integer> getList() { return Collections.unmodifiableList( list ); }
      ...
}

Case 3 (specific methods):

public class Numbers {
      private List<Integer> list;
      public void addToList( int i ) { list.add(i); }
      public int getValueAtIndex( int index ) { return list.get( index ); }
      ...
}

How can I check if a View exists in a Database?

You can check the availability of the view in various ways

FOR SQL SERVER

use sys.objects

IF EXISTS(
   SELECT 1
   FROM   sys.objects
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
          AND Type_Desc = 'VIEW'
)
BEGIN
    PRINT 'View Exists'
END

use sysobjects

IF NOT EXISTS (
   SELECT 1
   FROM   sysobjects
   WHERE  NAME = '[schemaName].[ViewName]'
          AND xtype = 'V'
)
BEGIN
    PRINT 'View Exists'
END

use sys.views

IF EXISTS (
   SELECT 1
   FROM sys.views
   WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
)
BEGIN
    PRINT 'View Exists'
END

use INFORMATION_SCHEMA.VIEWS

IF EXISTS (
   SELECT 1
   FROM   INFORMATION_SCHEMA.VIEWS
   WHERE  table_name = 'ViewName'
          AND table_schema = 'schemaName'
)
BEGIN
    PRINT 'View Exists'
END

use OBJECT_ID

IF EXISTS(
   SELECT OBJECT_ID('ViewName', 'V')
)
BEGIN
    PRINT 'View Exists'
END

use sys.sql_modules

IF EXISTS (
   SELECT 1
   FROM   sys.sql_modules
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
)
BEGIN
   PRINT 'View Exists'
END

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

The best solution would be to go to http://projects.eclipse.org/projects/tools.pdt/downloads where you will find the URL to the most updated PDT, as most of the URLS listed above are hitting a 404. Then pasting the URL to eclipse.

Check if item is in an array / list

Assuming you mean "list" where you say "array", you can do

if item in my_list:
    # whatever

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.

How to make flexbox items the same size?

You need to add width: 0 to make columns equal if contents of the items make it grow bigger.

.item {
  flex: 1 1 0;
  width: 0;
}

Outputting data from unit test in Python

Use logging:

import unittest
import logging
import inspect
import os

logging_level = logging.INFO

try:
    log_file = os.environ["LOG_FILE"]
except KeyError:
    log_file = None

def logger(stack=None):
    if not hasattr(logger, "initialized"):
        logging.basicConfig(filename=log_file, level=logging_level)
        logger.initialized = True
    if not stack:
        stack = inspect.stack()
    name = stack[1][3]
    try:
        name = stack[1][0].f_locals["self"].__class__.__name__ + "." + name
    except KeyError:
        pass
    return logging.getLogger(name)

def todo(msg):
    logger(inspect.stack()).warning("TODO: {}".format(msg))

def get_pi():
    logger().info("sorry, I know only three digits")
    return 3.14

class Test(unittest.TestCase):

    def testName(self):
        todo("use a better get_pi")
        pi = get_pi()
        logger().info("pi = {}".format(pi))
        todo("check more digits in pi")
        self.assertAlmostEqual(pi, 3.14)
        logger().debug("end of this test")
        pass

Usage:

# LOG_FILE=/tmp/log python3 -m unittest LoggerDemo
.
----------------------------------------------------------------------
Ran 1 test in 0.047s

OK
# cat /tmp/log
WARNING:Test.testName:TODO: use a better get_pi
INFO:get_pi:sorry, I know only three digits
INFO:Test.testName:pi = 3.14
WARNING:Test.testName:TODO: check more digits in pi

If you do not set LOG_FILE, logging will got to stderr.

Fully change package name including company domain

current package : com.company.name

New package : com.mycomapny.name

Steps: 1) Suppose you are at this screen which is shown below.

enter image description here

2) Open project pane and click on settings icon.

3) Deselect Compact Empty Middle Packages.

4) Then your package is now broken into individual parts as shown below .

5) right click on "company" select Refactor -> select rename ->rename directory.

enter image description here

6) Now your "company" has been changed to new "mycomapny" and changes were reflected as shown in below figure.

enter image description here

7) Now change the package name in AndroidManifest.xml file .

enter image description here

8) Open app level build.gradle and change package name .

enter image description here

9) you will get errors as Cannot resolve symbol "R" .

10) Remove line which gives this error and studio will import new R file automatically.

11) If you have multiple files then use find and replace option by pressing " Cntrl+Shift+R "

Or " Select Edit->Find->Replace in path.."

enter image description here

12) select Replace All.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You could try using Insight a graphical front-end for gdb written by Red Hat Or if you use GNOME desktop environment, you can also try Nemiver.

Java random number with given length

If you need to specify the exact charactor length, we have to avoid values with 0 in-front.

Final String representation must have that exact character length.

String GenerateRandomNumber(int charLength) {
        return String.valueOf(charLength < 1 ? 0 : new Random()
                .nextInt((9 * (int) Math.pow(10, charLength - 1)) - 1)
                + (int) Math.pow(10, charLength - 1));
    }

How to initialize a List<T> to a given size (as opposed to capacity)?

Create an array with the number of items you want first and then convert the array in to a List.

int[] fakeArray = new int[10];

List<int> list = fakeArray.ToList();

error opening trace file: No such file or directory (2)

It happens because you have not installed the minSdkVersion or targetSdkVersion in you’re computer. I've tested it right now.

For example, if you have those lines in your Manifest.xml:

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />

And you have installed only the API17 in your computer, it will report you an error. If you want to test it, try installing the other API version (in this case, API 8).

Even so, it's not an important error. It doesn't mean that your app is wrong.

Sorry about my expression. English is not my language. Bye!

Interface/enum listing standard mime-type constants

I solved this with a static class:

@SuppressWarnings("serial")
public class MimeTypes {

    private static final HashMap<String, String> mimeTypes;

    static {
        mimeTypes = new HashMap<String, String>() {
            {
                put(".323", "text/h323");
                put(".3g2", "video/3gpp2");
                put(".3gp", "video/3gpp");
                put(".3gp2", "video/3gpp2");
                put(".3gpp", "video/3gpp");
                put(".7z", "application/x-7z-compressed");
                put(".aa", "audio/audible");
                put(".AAC", "audio/aac");
                put(".aaf", "application/octet-stream");
                put(".aax", "audio/vnd.audible.aax");
                put(".ac3", "audio/ac3");
                put(".aca", "application/octet-stream");
                put(".accda", "application/msaccess.addin");
                put(".accdb", "application/msaccess");
                put(".accdc", "application/msaccess.cab");
                put(".accde", "application/msaccess");
                put(".accdr", "application/msaccess.runtime");
                put(".accdt", "application/msaccess");
                put(".accdw", "application/msaccess.webapplication");
                put(".accft", "application/msaccess.ftemplate");
                put(".acx", "application/internet-property-stream");
                put(".AddIn", "text/xml");
                put(".ade", "application/msaccess");
                put(".adobebridge", "application/x-bridge-url");
                put(".adp", "application/msaccess");
                put(".ADT", "audio/vnd.dlna.adts");
                put(".ADTS", "audio/aac");
                put(".afm", "application/octet-stream");
                put(".ai", "application/postscript");
                put(".aif", "audio/x-aiff");
                put(".aifc", "audio/aiff");
                put(".aiff", "audio/aiff");
                put(".air", "application/vnd.adobe.air-application-installer-package+zip");
                put(".amc", "application/x-mpeg");
                put(".application", "application/x-ms-application");
                put(".art", "image/x-jg");
                put(".asa", "application/xml");
                put(".asax", "application/xml");
                put(".ascx", "application/xml");
                put(".asd", "application/octet-stream");
                put(".asf", "video/x-ms-asf");
                put(".ashx", "application/xml");
                put(".asi", "application/octet-stream");
                put(".asm", "text/plain");
                put(".asmx", "application/xml");
                put(".aspx", "application/xml");
                put(".asr", "video/x-ms-asf");
                put(".asx", "video/x-ms-asf");
                put(".atom", "application/atom+xml");
                put(".au", "audio/basic");
                put(".avi", "video/x-msvideo");
                put(".axs", "application/olescript");
                put(".bas", "text/plain");
                put(".bcpio", "application/x-bcpio");
                put(".bin", "application/octet-stream");
                put(".bmp", "image/bmp");
                put(".c", "text/plain");
                put(".cab", "application/octet-stream");
                put(".caf", "audio/x-caf");
                put(".calx", "application/vnd.ms-office.calx");
                put(".cat", "application/vnd.ms-pki.seccat");
                put(".cc", "text/plain");
                put(".cd", "text/plain");
                put(".cdda", "audio/aiff");
                put(".cdf", "application/x-cdf");
                put(".cer", "application/x-x509-ca-cert");
                put(".chm", "application/octet-stream");
                put(".class", "application/x-java-applet");
                put(".clp", "application/x-msclip");
                put(".cmx", "image/x-cmx");
                put(".cnf", "text/plain");
                put(".cod", "image/cis-cod");
                put(".config", "application/xml");
                put(".contact", "text/x-ms-contact");
                put(".coverage", "application/xml");
                put(".cpio", "application/x-cpio");
                put(".cpp", "text/plain");
                put(".crd", "application/x-mscardfile");
                put(".crl", "application/pkix-crl");
                put(".crt", "application/x-x509-ca-cert");
                put(".cs", "text/plain");
                put(".csdproj", "text/plain");
                put(".csh", "application/x-csh");
                put(".csproj", "text/plain");
                put(".css", "text/css");
                put(".csv", "text/csv");
                put(".cur", "application/octet-stream");
                put(".cxx", "text/plain");
                put(".dat", "application/octet-stream");
                put(".datasource", "application/xml");
                put(".dbproj", "text/plain");
                put(".dcr", "application/x-director");
                put(".def", "text/plain");
                put(".deploy", "application/octet-stream");
                put(".der", "application/x-x509-ca-cert");
                put(".dgml", "application/xml");
                put(".dib", "image/bmp");
                put(".dif", "video/x-dv");
                put(".dir", "application/x-director");
                put(".disco", "text/xml");
                put(".dll", "application/x-msdownload");
                put(".dll.config", "text/xml");
                put(".dlm", "text/dlm");
                put(".doc", "application/msword");
                put(".docm", "application/vnd.ms-word.document.macroEnabled.12");
                put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
                put(".dot", "application/msword");
                put(".dotm", "application/vnd.ms-word.template.macroEnabled.12");
                put(".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template");
                put(".dsp", "application/octet-stream");
                put(".dsw", "text/plain");
                put(".dtd", "text/xml");
                put(".dtsConfig", "text/xml");
                put(".dv", "video/x-dv");
                put(".dvi", "application/x-dvi");
                put(".dwf", "drawing/x-dwf");
                put(".dwp", "application/octet-stream");
                put(".dxr", "application/x-director");
                put(".eml", "message/rfc822");
                put(".emz", "application/octet-stream");
                put(".eot", "application/octet-stream");
                put(".eps", "application/postscript");
                put(".etl", "application/etl");
                put(".etx", "text/x-setext");
                put(".evy", "application/envoy");
                put(".exe", "application/octet-stream");
                put(".exe.config", "text/xml");
                put(".fdf", "application/vnd.fdf");
                put(".fif", "application/fractals");
                put(".filters", "Application/xml");
                put(".fla", "application/octet-stream");
                put(".flr", "x-world/x-vrml");
                put(".flv", "video/x-flv");
                put(".fsscript", "application/fsharp-script");
                put(".fsx", "application/fsharp-script");
                put(".generictest", "application/xml");
                put(".gif", "image/gif");
                put(".group", "text/x-ms-group");
                put(".gsm", "audio/x-gsm");
                put(".gtar", "application/x-gtar");
                put(".gz", "application/x-gzip");
                put(".h", "text/plain");
                put(".hdf", "application/x-hdf");
                put(".hdml", "text/x-hdml");
                put(".hhc", "application/x-oleobject");
                put(".hhk", "application/octet-stream");
                put(".hhp", "application/octet-stream");
                put(".hlp", "application/winhlp");
                put(".hpp", "text/plain");
                put(".hqx", "application/mac-binhex40");
                put(".hta", "application/hta");
                put(".htc", "text/x-component");
                put(".htm", "text/html");
                put(".html", "text/html");
                put(".htt", "text/webviewhtml");
                put(".hxa", "application/xml");
                put(".hxc", "application/xml");
                put(".hxd", "application/octet-stream");
                put(".hxe", "application/xml");
                put(".hxf", "application/xml");
                put(".hxh", "application/octet-stream");
                put(".hxi", "application/octet-stream");
                put(".hxk", "application/xml");
                put(".hxq", "application/octet-stream");
                put(".hxr", "application/octet-stream");
                put(".hxs", "application/octet-stream");
                put(".hxt", "text/html");
                put(".hxv", "application/xml");
                put(".hxw", "application/octet-stream");
                put(".hxx", "text/plain");
                put(".i", "text/plain");
                put(".ico", "image/x-icon");
                put(".ics", "application/octet-stream");
                put(".idl", "text/plain");
                put(".ief", "image/ief");
                put(".iii", "application/x-iphone");
                put(".inc", "text/plain");
                put(".inf", "application/octet-stream");
                put(".inl", "text/plain");
                put(".ins", "application/x-internet-signup");
                put(".ipa", "application/x-itunes-ipa");
                put(".ipg", "application/x-itunes-ipg");
                put(".ipproj", "text/plain");
                put(".ipsw", "application/x-itunes-ipsw");
                put(".iqy", "text/x-ms-iqy");
                put(".isp", "application/x-internet-signup");
                put(".ite", "application/x-itunes-ite");
                put(".itlp", "application/x-itunes-itlp");
                put(".itms", "application/x-itunes-itms");
                put(".itpc", "application/x-itunes-itpc");
                put(".IVF", "video/x-ivf");
                put(".jar", "application/java-archive");
                put(".java", "application/octet-stream");
                put(".jck", "application/liquidmotion");
                put(".jcz", "application/liquidmotion");
                put(".jfif", "image/pjpeg");
                put(".jnlp", "application/x-java-jnlp-file");
                put(".jpb", "application/octet-stream");
                put(".jpe", "image/jpeg");
                put(".jpeg", "image/jpeg");
                put(".jpg", "image/jpeg");
                put(".js", "application/x-javascript");
                put(".json", "application/json");
                put(".jsx", "text/jscript");
                put(".jsxbin", "text/plain");
                put(".latex", "application/x-latex");
                put(".library-ms", "application/windows-library+xml");
                put(".lit", "application/x-ms-reader");
                put(".loadtest", "application/xml");
                put(".lpk", "application/octet-stream");
                put(".lsf", "video/x-la-asf");
                put(".lst", "text/plain");
                put(".lsx", "video/x-la-asf");
                put(".lzh", "application/octet-stream");
                put(".m13", "application/x-msmediaview");
                put(".m14", "application/x-msmediaview");
                put(".m1v", "video/mpeg");
                put(".m2t", "video/vnd.dlna.mpeg-tts");
                put(".m2ts", "video/vnd.dlna.mpeg-tts");
                put(".m2v", "video/mpeg");
                put(".m3u", "audio/x-mpegurl");
                put(".m3u8", "audio/x-mpegurl");
                put(".m4a", "audio/m4a");
                put(".m4b", "audio/m4b");
                put(".m4p", "audio/m4p");
                put(".m4r", "audio/x-m4r");
                put(".m4v", "video/x-m4v");
                put(".mac", "image/x-macpaint");
                put(".mak", "text/plain");
                put(".man", "application/x-troff-man");
                put(".manifest", "application/x-ms-manifest");
                put(".map", "text/plain");
                put(".master", "application/xml");
                put(".mda", "application/msaccess");
                put(".mdb", "application/x-msaccess");
                put(".mde", "application/msaccess");
                put(".mdp", "application/octet-stream");
                put(".me", "application/x-troff-me");
                put(".mfp", "application/x-shockwave-flash");
                put(".mht", "message/rfc822");
                put(".mhtml", "message/rfc822");
                put(".mid", "audio/mid");
                put(".midi", "audio/mid");
                put(".mix", "application/octet-stream");
                put(".mk", "text/plain");
                put(".mmf", "application/x-smaf");
                put(".mno", "text/xml");
                put(".mny", "application/x-msmoney");
                put(".mod", "video/mpeg");
                put(".mov", "video/quicktime");
                put(".movie", "video/x-sgi-movie");
                put(".mp2", "video/mpeg");
                put(".mp2v", "video/mpeg");
                put(".mp3", "audio/mpeg");
                put(".mp4", "video/mp4");
                put(".mp4v", "video/mp4");
                put(".mpa", "video/mpeg");
                put(".mpe", "video/mpeg");
                put(".mpeg", "video/mpeg");
                put(".mpf", "application/vnd.ms-mediapackage");
                put(".mpg", "video/mpeg");
                put(".mpp", "application/vnd.ms-project");
                put(".mpv2", "video/mpeg");
                put(".mqv", "video/quicktime");
                put(".ms", "application/x-troff-ms");
                put(".msi", "application/octet-stream");
                put(".mso", "application/octet-stream");
                put(".mts", "video/vnd.dlna.mpeg-tts");
                put(".mtx", "application/xml");
                put(".mvb", "application/x-msmediaview");
                put(".mvc", "application/x-miva-compiled");
                put(".mxp", "application/x-mmxp");
                put(".nc", "application/x-netcdf");
                put(".nsc", "video/x-ms-asf");
                put(".nws", "message/rfc822");
                put(".ocx", "application/octet-stream");
                put(".oda", "application/oda");
                put(".odc", "text/x-ms-odc");
                put(".odh", "text/plain");
                put(".odl", "text/plain");
                put(".odp", "application/vnd.oasis.opendocument.presentation");
                put(".ods", "application/oleobject");
                put(".odt", "application/vnd.oasis.opendocument.text");
                put(".one", "application/onenote");
                put(".onea", "application/onenote");
                put(".onepkg", "application/onenote");
                put(".onetmp", "application/onenote");
                put(".onetoc", "application/onenote");
                put(".onetoc2", "application/onenote");
                put(".orderedtest", "application/xml");
                put(".osdx", "application/opensearchdescription+xml");
                put(".p10", "application/pkcs10");
                put(".p12", "application/x-pkcs12");
                put(".p7b", "application/x-pkcs7-certificates");
                put(".p7c", "application/pkcs7-mime");
                put(".p7m", "application/pkcs7-mime");
                put(".p7r", "application/x-pkcs7-certreqresp");
                put(".p7s", "application/pkcs7-signature");
                put(".pbm", "image/x-portable-bitmap");
                put(".pcast", "application/x-podcast");
                put(".pct", "image/pict");
                put(".pcx", "application/octet-stream");
                put(".pcz", "application/octet-stream");
                put(".pdf", "application/pdf");
                put(".pfb", "application/octet-stream");
                put(".pfm", "application/octet-stream");
                put(".pfx", "application/x-pkcs12");
                put(".pgm", "image/x-portable-graymap");
                put(".pic", "image/pict");
                put(".pict", "image/pict");
                put(".pkgdef", "text/plain");
                put(".pkgundef", "text/plain");
                put(".pko", "application/vnd.ms-pki.pko");
                put(".pls", "audio/scpls");
                put(".pma", "application/x-perfmon");
                put(".pmc", "application/x-perfmon");
                put(".pml", "application/x-perfmon");
                put(".pmr", "application/x-perfmon");
                put(".pmw", "application/x-perfmon");
                put(".png", "image/png");
                put(".pnm", "image/x-portable-anymap");
                put(".pnt", "image/x-macpaint");
                put(".pntg", "image/x-macpaint");
                put(".pnz", "image/png");
                put(".pot", "application/vnd.ms-powerpoint");
                put(".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12");
                put(".potx", "application/vnd.openxmlformats-officedocument.presentationml.template");
                put(".ppa", "application/vnd.ms-powerpoint");
                put(".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12");
                put(".ppm", "image/x-portable-pixmap");
                put(".pps", "application/vnd.ms-powerpoint");
                put(".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12");
                put(".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
                put(".ppt", "application/vnd.ms-powerpoint");
                put(".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12");
                put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
                put(".prf", "application/pics-rules");
                put(".prm", "application/octet-stream");
                put(".prx", "application/octet-stream");
                put(".ps", "application/postscript");
                put(".psc1", "application/PowerShell");
                put(".psd", "application/octet-stream");
                put(".psess", "application/xml");
                put(".psm", "application/octet-stream");
                put(".psp", "application/octet-stream");
                put(".pub", "application/x-mspublisher");
                put(".pwz", "application/vnd.ms-powerpoint");
                put(".qht", "text/x-html-insertion");
                put(".qhtm", "text/x-html-insertion");
                put(".qt", "video/quicktime");
                put(".qti", "image/x-quicktime");
                put(".qtif", "image/x-quicktime");
                put(".qtl", "application/x-quicktimeplayer");
                put(".qxd", "application/octet-stream");
                put(".ra", "audio/x-pn-realaudio");
                put(".ram", "audio/x-pn-realaudio");
                put(".rar", "application/octet-stream");
                put(".ras", "image/x-cmu-raster");
                put(".rat", "application/rat-file");
                put(".rc", "text/plain");
                put(".rc2", "text/plain");
                put(".rct", "text/plain");
                put(".rdlc", "application/xml");
                put(".resx", "application/xml");
                put(".rf", "image/vnd.rn-realflash");
                put(".rgb", "image/x-rgb");
                put(".rgs", "text/plain");
                put(".rm", "application/vnd.rn-realmedia");
                put(".rmi", "audio/mid");
                put(".rmp", "application/vnd.rn-rn_music_package");
                put(".roff", "application/x-troff");
                put(".rpm", "audio/x-pn-realaudio-plugin");
                put(".rqy", "text/x-ms-rqy");
                put(".rtf", "application/rtf");
                put(".rtx", "text/richtext");
                put(".ruleset", "application/xml");
                put(".s", "text/plain");
                put(".safariextz", "application/x-safari-safariextz");
                put(".scd", "application/x-msschedule");
                put(".sct", "text/scriptlet");
                put(".sd2", "audio/x-sd2");
                put(".sdp", "application/sdp");
                put(".sea", "application/octet-stream");
                put(".searchConnector-ms", "application/windows-search-connector+xml");
                put(".setpay", "application/set-payment-initiation");
                put(".setreg", "application/set-registration-initiation");
                put(".settings", "application/xml");
                put(".sgimb", "application/x-sgimb");
                put(".sgml", "text/sgml");
                put(".sh", "application/x-sh");
                put(".shar", "application/x-shar");
                put(".shtml", "text/html");
                put(".sit", "application/x-stuffit");
                put(".sitemap", "application/xml");
                put(".skin", "application/xml");
                put(".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12");
                put(".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide");
                put(".slk", "application/vnd.ms-excel");
                put(".sln", "text/plain");
                put(".slupkg-ms", "application/x-ms-license");
                put(".smd", "audio/x-smd");
                put(".smi", "application/octet-stream");
                put(".smx", "audio/x-smd");
                put(".smz", "audio/x-smd");
                put(".snd", "audio/basic");
                put(".snippet", "application/xml");
                put(".snp", "application/octet-stream");
                put(".sol", "text/plain");
                put(".sor", "text/plain");
                put(".spc", "application/x-pkcs7-certificates");
                put(".spl", "application/futuresplash");
                put(".src", "application/x-wais-source");
                put(".srf", "text/plain");
                put(".SSISDeploymentManifest", "text/xml");
                put(".ssm", "application/streamingmedia");
                put(".sst", "application/vnd.ms-pki.certstore");
                put(".stl", "application/vnd.ms-pki.stl");
                put(".sv4cpio", "application/x-sv4cpio");
                put(".sv4crc", "application/x-sv4crc");
                put(".svc", "application/xml");
                put(".swf", "application/x-shockwave-flash");
                put(".t", "application/x-troff");
                put(".tar", "application/x-tar");
                put(".tcl", "application/x-tcl");
                put(".testrunconfig", "application/xml");
                put(".testsettings", "application/xml");
                put(".tex", "application/x-tex");
                put(".texi", "application/x-texinfo");
                put(".texinfo", "application/x-texinfo");
                put(".tgz", "application/x-compressed");
                put(".thmx", "application/vnd.ms-officetheme");
                put(".thn", "application/octet-stream");
                put(".tif", "image/tiff");
                put(".tiff", "image/tiff");
                put(".tlh", "text/plain");
                put(".tli", "text/plain");
                put(".toc", "application/octet-stream");
                put(".tr", "application/x-troff");
                put(".trm", "application/x-msterminal");
                put(".trx", "application/xml");
                put(".ts", "video/vnd.dlna.mpeg-tts");
                put(".tsv", "text/tab-separated-values");
                put(".ttf", "application/octet-stream");
                put(".tts", "video/vnd.dlna.mpeg-tts");
                put(".txt", "text/plain");
                put(".u32", "application/octet-stream");
                put(".uls", "text/iuls");
                put(".user", "text/plain");
                put(".ustar", "application/x-ustar");
                put(".vb", "text/plain");
                put(".vbdproj", "text/plain");
                put(".vbk", "video/mpeg");
                put(".vbproj", "text/plain");
                put(".vbs", "text/vbscript");
                put(".vcf", "text/x-vcard");
                put(".vcproj", "Application/xml");
                put(".vcs", "text/plain");
                put(".vcxproj", "Application/xml");
                put(".vddproj", "text/plain");
                put(".vdp", "text/plain");
                put(".vdproj", "text/plain");
                put(".vdx", "application/vnd.ms-visio.viewer");
                put(".vml", "text/xml");
                put(".vscontent", "application/xml");
                put(".vsct", "text/xml");
                put(".vsd", "application/vnd.visio");
                put(".vsi", "application/ms-vsi");
                put(".vsix", "application/vsix");
                put(".vsixlangpack", "text/xml");
                put(".vsixmanifest", "text/xml");
                put(".vsmdi", "application/xml");
                put(".vspscc", "text/plain");
                put(".vss", "application/vnd.visio");
                put(".vsscc", "text/plain");
                put(".vssettings", "text/xml");
                put(".vssscc", "text/plain");
                put(".vst", "application/vnd.visio");
                put(".vstemplate", "text/xml");
                put(".vsto", "application/x-ms-vsto");
                put(".vsw", "application/vnd.visio");
                put(".vsx", "application/vnd.visio");
                put(".vtx", "application/vnd.visio");
                put(".wav", "audio/wav");
                put(".wave", "audio/wav");
                put(".wax", "audio/x-ms-wax");
                put(".wbk", "application/msword");
                put(".wbmp", "image/vnd.wap.wbmp");
                put(".wcm", "application/vnd.ms-works");
                put(".wdb", "application/vnd.ms-works");
                put(".wdp", "image/vnd.ms-photo");
                put(".webarchive", "application/x-safari-webarchive");
                put(".webtest", "application/xml");
                put(".wiq", "application/xml");
                put(".wiz", "application/msword");
                put(".wks", "application/vnd.ms-works");
                put(".WLMP", "application/wlmoviemaker");
                put(".wlpginstall", "application/x-wlpg-detect");
                put(".wlpginstall3", "application/x-wlpg3-detect");
                put(".wm", "video/x-ms-wm");
                put(".wma", "audio/x-ms-wma");
                put(".wmd", "application/x-ms-wmd");
                put(".wmf", "application/x-msmetafile");
                put(".wml", "text/vnd.wap.wml");
                put(".wmlc", "application/vnd.wap.wmlc");
                put(".wmls", "text/vnd.wap.wmlscript");
                put(".wmlsc", "application/vnd.wap.wmlscriptc");
                put(".wmp", "video/x-ms-wmp");
                put(".wmv", "video/x-ms-wmv");
                put(".wmx", "video/x-ms-wmx");
                put(".wmz", "application/x-ms-wmz");
                put(".wpl", "application/vnd.ms-wpl");
                put(".wps", "application/vnd.ms-works");
                put(".wri", "application/x-mswrite");
                put(".wrl", "x-world/x-vrml");
                put(".wrz", "x-world/x-vrml");
                put(".wsc", "text/scriptlet");
                put(".wsdl", "text/xml");
                put(".wvx", "video/x-ms-wvx");
                put(".x", "application/directx");
                put(".xaf", "x-world/x-vrml");
                put(".xaml", "application/xaml+xml");
                put(".xap", "application/x-silverlight-app");
                put(".xbap", "application/x-ms-xbap");
                put(".xbm", "image/x-xbitmap");
                put(".xdr", "text/plain");
                put(".xht", "application/xhtml+xml");
                put(".xhtml", "application/xhtml+xml");
                put(".xla", "application/vnd.ms-excel");
                put(".xlam", "application/vnd.ms-excel.addin.macroEnabled.12");
                put(".xlc", "application/vnd.ms-excel");
                put(".xld", "application/vnd.ms-excel");
                put(".xlk", "application/vnd.ms-excel");
                put(".xll", "application/vnd.ms-excel");
                put(".xlm", "application/vnd.ms-excel");
                put(".xls", "application/vnd.ms-excel");
                put(".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12");
                put(".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12");
                put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                put(".xlt", "application/vnd.ms-excel");
                put(".xltm", "application/vnd.ms-excel.template.macroEnabled.12");
                put(".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template");
                put(".xlw", "application/vnd.ms-excel");
                put(".xml", "text/xml");
                put(".xmta", "application/xml");
                put(".xof", "x-world/x-vrml");
                put(".XOML", "text/plain");
                put(".xpm", "image/x-xpixmap");
                put(".xps", "application/vnd.ms-xpsdocument");
                put(".xrm-ms", "text/xml");
                put(".xsc", "application/xml");
                put(".xsd", "text/xml");
                put(".xsf", "text/xml");
                put(".xsl", "text/xml");
                put(".xslt", "text/xml");
                put(".xsn", "application/octet-stream");
                put(".xss", "application/xml");
                put(".xtp", "application/octet-stream");
                put(".xwd", "image/x-xwindowdump");
                put(".z", "application/x-compress");
                put(".zip", "application/x-zip-compressed");
            }
        };
    }

    public static String getMimeType(String extension) {
        if (extension == null) {
            return null;
        }

        if (!extension.startsWith(".")) {
            extension = "." + extension.toLowerCase(Locale.getDefault());
        }

        String mime = mimeTypes.get(extension);

        return mime != null ? mime : "application/octet-stream";
    }
}

Accessing inventory host variable in Ansible playbook

I've found also a nice and simple way to address hostsvars right on one of Ansible's Github issues

Looks like you can do this as well:

 - debug:
    msg: "{{ ansible_ssh_host }}"

Compiling problems: cannot find crt1.o

This is a BUG reported in launchpad, but there is a workaround :

Run this to see where these files are located

$ find /usr/ -name crti*
/usr/lib/x86_64-linux-gnu/crti.o

then add this path to LIBRARY_PATH variable

$ export LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LIBRARY_PATH

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='') 
BEGIN
   SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
   INSERT INTO TABLE(FieldValue) VALUES('')
   SELECT SCOPE_IDENTITY() AS TableID
END

See here for more information on IF ELSE

Note: written without a SQL Server install handy to double check this but I think it is correct

Also, I've changed the EXISTS bit to do SELECT 1 rather than SELECT * as you don't care what is returned within an EXISTS, as long as something is I've also changed the SCOPE_IDENTITY() bit to return just the identity assuming that TableID is the identity column

Declaring variable workbook / Worksheet vba

Dim ws as Object

Set ws = Worksheets("name")

when declaring the worksheet as worksheet instead of an ojbect I had issues working with OptionButtons (Active X) in this worksheet (I guess the same will be with any Active-X element. When declared as object everything works fine.

Getting values from query string in an url using AngularJS $location

If your $location.search() is not working, then make sure you have the following:

1) html5Mode(true) is configured in app's module config

appModule.config(['$locationProvider', function($locationProvider) {
   $locationProvider.html5Mode(true);
}]);

2) <base href="/"> is present in your HTML

<head>
  <base href="/">
  ...
</head>

References:

  1. base href="/"
  2. html5Mode

Getting only response header from HTTP POST using curl

While the other answers have not worked for me in all situations, the best solution I could find (working with POST as well), taken from here:

curl -vs 'https://some-site.com' 1> /dev/null

Does WGET timeout?

Prior to version 1.14, wget timeout arguments were not adhered to if downloading over https due to a bug.

How to validate phone number using PHP?

Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.

php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.

An example

$phone = '000-0000-0000';

if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
  // $phone is valid
}

CSS centred header image

I think this is what you need if I'm understanding you correctly:

<div id="wrapperHeader">
 <div id="header">
  <img src="images/logo.png" alt="logo" />
 </div> 
</div>



div#wrapperHeader {
 width:100%;
 height;200px; /* height of the background image? */
 background:url(images/header.png) repeat-x 0 0;
 text-align:center;
}

div#wrapperHeader div#header {
 width:1000px;
 height:200px;
 margin:0 auto;
}

div#wrapperHeader div#header img {
 width:; /* the width of the logo image */
 height:; /* the height of the logo image */
 margin:0 auto;
}

Creating a generic method in C#

Convert.ChangeType() doesn't correctly handle nullable types or enumerations in .NET 2.0 BCL (I think it's fixed for BCL 4.0 though). Rather than make the outer implementation more complex, make the converter do more work for you. Here's an implementation I use:

public static class Converter
{
  public static T ConvertTo<T>(object value)
  {
    return ConvertTo(value, default(T));
  }

  public static T ConvertTo<T>(object value, T defaultValue)
  {
    if (value == DBNull.Value)
    {
      return defaultValue;
    }
    return (T) ChangeType(value, typeof(T));
  }

  public static object ChangeType(object value, Type conversionType)
  {
    if (conversionType == null)
    {
      throw new ArgumentNullException("conversionType");
    }

    // if it's not a nullable type, just pass through the parameters to Convert.ChangeType
    if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
    {
      // null input returns null output regardless of base type
      if (value == null)
      {
        return null;
      }

      // it's a nullable type, and not null, which means it can be converted to its underlying type,
      // so overwrite the passed-in conversion type with this underlying type
      conversionType = Nullable.GetUnderlyingType(conversionType);
    }
    else if (conversionType.IsEnum)
    {
      // strings require Parse method
      if (value is string)
      {
        return Enum.Parse(conversionType, (string) value);          
      }
      // primitive types can be instantiated using ToObject
      else if (value is int || value is uint || value is short || value is ushort || 
           value is byte || value is sbyte || value is long || value is ulong)
      {
        return Enum.ToObject(conversionType, value);
      }
      else
      {
        throw new ArgumentException(String.Format("Value cannot be converted to {0} - current type is " +
                              "not supported for enum conversions.", conversionType.FullName));
      }
    }

    return Convert.ChangeType(value, conversionType);
  }
}

Then your implementation of GetQueryString<T> can be:

public static T GetQueryString<T>(string key)
{
    T result = default(T);
    string value = HttpContext.Current.Request.QueryString[key];

    if (!String.IsNullOrEmpty(value))
    {
        try
        {
            result = Converter.ConvertTo<T>(value);  
        }
        catch
        {
            //Could not convert.  Pass back default value...
            result = default(T);
        }
    }

    return result;
}

Android: Align button to bottom-right of screen using FrameLayout?

Setting android:layout_gravity="bottom|right" worked for me

How do you attach and detach from Docker's process?

when nothing else works, open a new terminal then:

$ ps aux | grep attach
username  <pid_here>    ..............  0:00 docker attach <CONTAINER_HASH_HERE>
username  <another_pid> ..............  0:00 grep --color=auto attach
$ kill -9 <pid_here>

C++ callback using class member

Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function and std::bind:

#include <functional>
class EventHandler
{
    public:
        void addHandler(std::function<void(int)> callback)
        {
            cout << "Handler added..." << endl;
            // Let's pretend an event just occured
            callback(1);
        }
};

The addHandler method now accepts a std::function argument, and this "function object" have no return value and takes an integer as argument.

To bind it to a specific function, you use std::bind:

class MyClass
{
    public:
        MyClass();

        // Note: No longer marked `static`, and only takes the actual argument
        void Callback(int x);
    private:
        int private_x;
};

MyClass::MyClass()
{
    using namespace std::placeholders; // for `_1`

    private_x = 5;
    handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}

void MyClass::Callback(int x)
{
    // No longer needs an explicit `instance` argument,
    // as `this` is set up properly
    cout << x + private_x << endl;
}

You need to use std::bind when adding the handler, as you explicitly needs to specify the otherwise implicit this pointer as an argument. If you have a free-standing function, you don't have to use std::bind:

void freeStandingCallback(int x)
{
    // ...
}

int main()
{
    // ...
    handler->addHandler(freeStandingCallback);
}

Having the event handler use std::function objects, also makes it possible to use the new C++11 lambda functions:

handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });

Android: Quit application when press back button

try this

Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);

How to replace url parameter with javascript/jquery?

2020 answer since I was missing the functionality to automatically delete a parameter, so:

Based on my favorite answer https://stackoverflow.com/a/20420424/6284674 : I combined it with the ability to:

  • automatically delete an URL param if the value if null or '' based on answer https://stackoverflow.com/a/25214672/6284674

  • optionally push the updated URL directly in the window.location bar

  • IE support since it's only using regex and no URLSearchParams

JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/


function replaceUrlParam(url, paramName, paramValue){
    if(paramValue == null || paramValue == "")
        return url
        .replace(new RegExp('[?&]' + paramValue + '=[^&#]*(#.*)?$'), '$1')
        .replace(new RegExp('([?&])' + paramValue + '=[^&]*&'), '$1');   
    url = url.replace(/\?$/,'');
    var pattern = new RegExp('\\b('+paramName+'=).*?(&|$)')
    if(url.search(pattern)>=0){
        return url.replace(pattern,'$1' + paramValue + '$2');
    }
    return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
}

// Orginal URL (default jsfiddle console URL)
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

console.log(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

console.log(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

console.log(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

//Optionally also update the replaced URL in the window location bar
//Note: This does not work in JSfiddle, but it does in a normal browser
function pushUrl(url){
    window.history.pushState("", "", replaceUrlParam(window.location.href,'a','2'));   
}


pushUrl(replaceUrlParam(window.location.href,'a','2'));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=2

pushUrl(replaceUrlParam(window.location.href,'a',''));   
//https://fiddle.jshell.net/_display/?editor_console=true

pushUrl(replaceUrlParam(window.location.href,'a',3));   
//https://fiddle.jshell.net/_display/?editor_console=true&a=3

pushUrl(replaceUrlParam(window.location.href,'a', null));   
//https://fiddle.jshell.net/_display/?editor_console=true&

Setting device orientation in Swift iOS

If someone wants the answer, I think I just got it. Try this:

  • Go to your .plist file and check all the orientations.
  • In the view controller you want to force orientation, add the following code:
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.Portrait.toRaw().hashValue | UIInterfaceOrientationMask.PortraitUpsideDown.toRaw().hashValue
}

Hope it helps !

EDIT :

To force rotation, use the following code :

let value = UIInterfaceOrientation.LandscapeRight.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")

It works for iOS 7 & 8 !

Download pdf file using jquery ajax

You can do this with html5 very easily:

var link = document.createElement('a');
link.href = "/WWW/test.pdf";
link.download = "file_" + new Date() + ".pdf";
link.click();
link.remove()

How to split a comma-separated value to columns

ALTER function get_occurance_index(@delimiter varchar(1),@occurence int,@String varchar(100))
returns int
AS Begin
--Declare @delimiter varchar(1)=',',@occurence int=2,@String varchar(100)='a,b,c'
Declare @result int
 ;with T as (
    select 1 Rno,0 as row, charindex(@delimiter, @String) pos,@String st
    union all
    select Rno+1,pos + 1, charindex(@delimiter, @String, pos + 1), @String
    from T
    where pos > 0
)
select  @result=pos 
from T 
where pos > 0   and rno = @occurence 
return isnull(@result,0)
ENd


declare @data as table (data varchar(100))
insert into @data values('1,2,3') 
insert into @data values('aaa,bbbbb,cccc') 
select top  3 Substring (data,0,dbo.get_occurance_index( ',',1,data)) ,--First Record always starts with 0
Substring (data,dbo.get_occurance_index( ',',1,data)+1,dbo.get_occurance_index( ',',2,data)-dbo.get_occurance_index( ',',1,data)-1) ,
Substring (data,dbo.get_occurance_index( ',',2,data)+1,len(data)) , -- Last record cant be more than len of actual data
data 
From @data 

Create HTTP post request and receive response using C# console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

The project cannot be built until the build path errors are resolved.

In Eclipse this worked for me: right click project. -> Properties -> Library Section; Add (any library at all) -> select library and click remove -> press okay.

adding directory to sys.path /PYTHONPATH

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

Go to setting option which is on upper strip of android studio and follow the below steps to solve the problem.

setting > Appearance&behavior > HTTP and proxy > click on Auto detect Enable option.(The option with radio box)select this one...

How the single threaded non blocking IO model works in Node.js

Node.js uses libuv behind the scenes. libuv has a thread pool (of size 4 by default). Therefore Node.js does use threads to achieve concurrency.

However, your code runs on a single thread (i.e., all of the callbacks of Node.js functions will be called on the same thread, the so called loop-thread or event-loop). When people say "Node.js runs on a single thread" they are really saying "the callbacks of Node.js run on a single thread".

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Redirecting from HTTP to HTTPS with PHP

This is a good way to do it:

<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || 
   $_SERVER['HTTPS'] == 1) ||  
   isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&   
   $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
   $redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
   header('HTTP/1.1 301 Moved Permanently');
   header('Location: ' . $redirect);
   exit();
}
?>

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

How do I extract Month and Year in a MySQL date and compare them?

There should also be a YEAR().

As for comparing, you could compare dates that are the first days of those years and months, or you could convert the year/month pair into a number suitable for comparison (i.e. bigger = later). (Exercise left to the reader. For hints, read about the ISO date format.)

Or you could use multiple comparisons (i.e. years first, then months).

Pandas: rolling mean by time interval

To keep it basic, I used a loop and something like this to get you started (my index are datetimes):

import pandas as pd
import datetime as dt

#populate your dataframe: "df"
#...

df[df.index<(df.index[0]+dt.timedelta(hours=1))] #gives you a slice. you can then take .sum() .mean(), whatever

and then you can run functions on that slice. You can see how adding an iterator to make the start of the window something other than the first value in your dataframes index would then roll the window (you could use a > rule for the start as well for example).

Note, this may be less efficient for SUPER large data or very small increments as your slicing may become more strenuous (works for me well enough for hundreds of thousands of rows of data and several columns though for hourly windows across a few weeks)

How do I install Python 3 on an AWS EC2 instance?

Adding to all the answers already available for this question, I would like to add the steps I followed to install Python3 on AWS EC2 instance running CentOS 7. You can find the entire details at this link.

https://aws-labs.com/install-python-3-centos-7-2/

First, we need to enable SCL. SCL is a community project that allows you to build, install, and use multiple versions of software on the same system, without affecting system default packages.

sudo yum install centos-release-scl

Now that we have SCL repository, we can install the python3

sudo yum install rh-python36

To access Python 3.6 you need to launch a new shell instance using the Software Collection scl tool:

scl enable rh-python36 bash

If you check the Python version now you’ll notice that Python 3.6 is the default version

python --version

It is important to point out that Python 3.6 is the default Python version only in this shell session. If you exit the session or open a new session from another terminal Python 2.7 will be the default Python version.

Now, Install the python development tools by typing:

sudo yum groupinstall ‘Development Tools’

Now create a virtual environment so that the default python packages don't get messed up.

mkdir ~/my_new_project
cd ~/my_new_project
python -m venv my_project_venv

To use this virtual environment,

source my_project_venv/bin/activate

Now, you have your virtual environment set up with python3.

Where is the default log location for SharePoint/MOSS?

In Sharepoint Server 2010 they are stored here:

"c:\Program Files\Common Files\Microsoft Shared\web server extensions\14\LOGS"

To view them you can use ULS Viewer by Microsoft (unsupported). http://ulsviewer.codeplex.com/

Bootstrap control with multiple "data-toggle"

When you opening modal on a tag and want show tooltip and if you implement tooltip inside tag it will show tooltip nearby tag. like this

enter image description here

I will suggest that use div outside a tag and use "display: inline-block;"

<div data-toggle="tooltip" title="" data-original-title="Add" style=" display inline-block;">
    <a class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="setSelectedRoleId(6)">
     <span class="fa fa-plus"></span>
    </a>
</div>

enter image description here

Write lines of text to a file in R

To round out the possibilities, you can use writeLines() with sink(), if you want:

> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World

To me, it always seems most intuitive to use print(), but if you do that the output won't be what you want:

...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"

message box in jquery

Try this plugin JQuery UI Message box. He uses jQuery UI Dialog.

Convert char to int in C#

This worked for me:

int bar = int.Parse("" + foo);

Getting last day of the month in a given string date

You can use the following code to get last day of the month

public static String getLastDayOfTheMonth(String date) {
        String lastDayOfTheMonth = "";

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        try{
        java.util.Date dt= formatter.parse(date);
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(dt);  

        calendar.add(Calendar.MONTH, 1);  
        calendar.set(Calendar.DAY_OF_MONTH, 1);  
        calendar.add(Calendar.DATE, -1);  

        java.util.Date lastDay = calendar.getTime();  

        lastDayOfTheMonth = formatter.format(lastDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return lastDayOfTheMonth;
    }

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

What is TypeScript and why would I use it in place of JavaScript?

TypeScript's relation to JavaScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript - typescriptlang.org.

JavaScript is a programming language that is developed by EMCA's Technical Committee 39, which is a group of people composed of many different stakeholders. TC39 is a committee hosted by ECMA: an internal standards organization. JavaScript has many different implementations by many different vendors (e.g. Google, Microsoft, Oracle, etc.). The goal of JavaScript is to be the lingua franca of the web.

TypeScript is a superset of the JavaScript language that has a single open-source compiler and is developed mainly by a single vendor: Microsoft. The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient.

Essentially TypeScript achieves its goals in three ways:

  1. Support for modern JavaScript features - The JavaScript language (not the runtime) is standardized through the ECMAScript standards. Not all browsers and JavaScript runtimes support all features of all ECMAScript standards (see this overview). TypeScript allows for the use of many of the latest ECMAScript features and translates them to older ECMAScript targets of your choosing (see the list of compile targets under the --target compiler option). This means that you can safely use new features, like modules, lambda functions, classes, the spread operator and destructuring, while remaining backwards compatible with older browsers and JavaScript runtimes.

  2. Advanced type system - The type support is not part of the ECMAScript standard and will likely never be due to the interpreted nature instead of compiled nature of JavaScript. The type system of TypeScript is incredibly rich and includes: interfaces, enums, hybrid types, generics, union/intersection types, access modifiers and much more. The official website of TypeScript gives an overview of these features. Typescript's type system is on-par with most other typed languages and in some cases arguably more powerful.

  3. Developer tooling support - TypeScript's compiler can run as a background process to support both incremental compilation and IDE integration such that you can more easily navigate, identify problems, inspect possibilities and refactor your codebase.

TypeScript's relation to other JavaScript targeting languages

TypeScript has a unique philosophy compared to other languages that compile to JavaScript. JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can almost rename your .js files to .ts files and start using TypeScript (see "JavaScript interoperability" below). TypeScript files are compiled to readable JavaScript, so that migration back is possible and understanding the compiled TypeScript is not hard at all. TypeScript builds on the successes of JavaScript while improving on its weaknesses.

On the one hand, you have future proof tools that take modern ECMAScript standards and compile it down to older JavaScript versions with Babel being the most popular one. On the other hand, you have languages that may totally differ from JavaScript which target JavaScript, like CoffeeScript, Clojure, Dart, Elm, Haxe, Scala.js, and a whole host more (see this list). These languages, though they might be better than where JavaScript's future might ever lead, run a greater risk of not finding enough adoption for their futures to be guaranteed. You might also have more trouble finding experienced developers for some of these languages, though the ones you will find can often be more enthusiastic. Interop with JavaScript can also be a bit more involved, since they are farther removed from what JavaScript actually is.

TypeScript sits in between these two extremes, thus balancing the risk. TypeScript is not a risky choice by any standard. It takes very little effort to get used to if you are familiar with JavaScript, since it is not a completely different language, has excellent JavaScript interoperability support and it has seen a lot of adoption recently.

Optionally static typing and type inference

JavaScript is dynamically typed. This means JavaScript does not know what type a variable is until it is actually instantiated at run-time. This also means that it may be too late. TypeScript adds type support to JavaScript and catches type errors during compilation to JavaScript. Bugs that are caused by false assumptions of some variable being of a certain type can be completely eradicated if you play your cards right (how strict you type your code or if you type your code at all is up to you).

TypeScript makes typing a bit easier and a lot less explicit by the usage of type inference. For example: var x = "hello" in TypeScript is the same as var x : string = "hello". The type is simply inferred from its use. Even it you don't explicitly type the types, they are still there to save you from doing something which otherwise would result in a run-time error.

TypeScript is optionally typed by default. For example function divideByTwo(x) { return x / 2 } is a valid function in TypeScript which can be called with any kind of parameter, even though calling it with a string will obviously result in a runtime error. Just like you are used to in JavaScript. This works, because when no type was explicitly assigned and the type could not be inferred, like in the divideByTwo example, TypeScript will implicitly assign the type any. This means the divideByTwo function's type signature automatically becomes function divideByTwo(x : any) : any. There is a compiler flag to disallow this behavior: --noImplicitAny. Enabling this flag gives you a greater degree of safety, but also means you will have to do more typing.

Types have a cost associated with them. First of all, there is a learning curve, and second of all, of course, it will cost you a bit more time to set up a codebase using proper strict typing too. In my experience, these costs are totally worth it on any serious codebase you are sharing with others. A Large Scale Study of Programming Languages and Code Quality in Github suggests that "statically typed languages, in general, are less defect prone than the dynamic types, and that strong typing is better than weak typing in the same regard".

It is interesting to note that this very same paper finds that TypeScript is less error-prone than JavaScript:

For those with positive coefficients we can expect that the language is associated with, ceteris paribus, a greater number of defect fixes. These languages include C, C++, JavaScript, Objective-C, Php, and Python. The languages Clojure, Haskell, Ruby, Scala, and TypeScript, all have negative coefficients implying that these languages are less likely than the average to result in defect fixing commits.

Enhanced IDE support

The development experience with TypeScript is a great improvement over JavaScript. The IDE is informed in real-time by the TypeScript compiler on its rich type information. This gives a couple of major advantages. For example, with TypeScript, you can safely do refactorings like renames across your entire codebase. Through code completion, you can get inline help on whatever functions a library might offer. No more need to remember them or look them up in online references. Compilation errors are reported directly in the IDE with a red squiggly line while you are busy coding. All in all, this allows for a significant gain in productivity compared to working with JavaScript. One can spend more time coding and less time debugging.

There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio Code, WebStorm, Atom and Sublime.

Strict null checks

Runtime errors of the form cannot read property 'x' of undefined or undefined is not a function are very commonly caused by bugs in JavaScript code. Out of the box TypeScript already reduces the probability of these kinds of errors occurring, since one cannot use a variable that is not known to the TypeScript compiler (with the exception of properties of any typed variables). It is still possible though to mistakenly utilize a variable that is set to undefined. However, with the 2.0 version of TypeScript you can eliminate these kinds of errors all together through the usage of non-nullable types. This works as follows:

With strict null checks enabled (--strictNullChecks compiler flag) the TypeScript compiler will not allow undefined to be assigned to a variable unless you explicitly declare it to be of nullable type. For example, let x : number = undefined will result in a compile error. This fits perfectly with type theory since undefined is not a number. One can define x to be a sum type of number and undefined to correct this: let x : number | undefined = undefined.

Once a type is known to be nullable, meaning it is of a type that can also be of the value null or undefined, the TypeScript compiler can determine through control flow based type analysis whether or not your code can safely use a variable or not. In other words when you check a variable is undefined through for example an if statement the TypeScript compiler will infer that the type in that branch of your code's control flow is not anymore nullable and therefore can safely be used. Here is a simple example:

let x: number | undefined;
if (x !== undefined) x += 1; // this line will compile, because x is checked.
x += 1; // this line will fail compilation, because x might be undefined.

During the build, 2016 conference co-designer of TypeScript Anders Hejlsberg gave a detailed explanation and demonstration of this feature: video (from 44:30 to 56:30).

Compilation

To use TypeScript you need a build process to compile to JavaScript code. The build process generally takes only a couple of seconds depending of course on the size of your project. The TypeScript compiler supports incremental compilation (--watch compiler flag) so that all subsequent changes can be compiled at greater speed.

The TypeScript compiler can inline source map information in the generated .js files or create separate .map files. Source map information can be used by debugging utilities like the Chrome DevTools and other IDE's to relate the lines in the JavaScript to the ones that generated them in the TypeScript. This makes it possible for you to set breakpoints and inspect variables during runtime directly on your TypeScript code. Source map information works pretty well, it was around long before TypeScript, but debugging TypeScript is generally not as great as when using JavaScript directly. Take the this keyword for example. Due to the changed semantics of the this keyword around closures since ES2015, this may actually exists during runtime as a variable called _this (see this answer). This may confuse you during debugging but generally is not a problem if you know about it or inspect the JavaScript code. It should be noted that Babel suffers the exact same kind of issue.

There are a few other tricks the TypeScript compiler can do, like generating intercepting code based on decorators, generating module loading code for different module systems and parsing JSX. However, you will likely require a build tool besides the Typescript compiler. For example, if you want to compress your code you will have to add other tools to your build process to do so.

There are TypeScript compilation plugins available for Webpack, Gulp, Grunt and pretty much any other JavaScript build tool out there. The TypeScript documentation has a section on integrating with build tools covering them all. A linter is also available in case you would like even more build time checking. There are also a great number of seed projects out there that will get you started with TypeScript in combination with a bunch of other technologies like Angular 2, React, Ember, SystemJS, Webpack, Gulp, etc.

JavaScript interoperability

Since TypeScript is so closely related to JavaScript it has great interoperability capabilities, but some extra work is required to work with JavaScript libraries in TypeScript. TypeScript definitions are needed so that the TypeScript compiler understands that function calls like _.groupBy or angular.copy or $.fadeOut are not in fact illegal statements. The definitions for these functions are placed in .d.ts files.

The simplest form a definition can take is to allow an identifier to be used in any way. For example, when using Lodash, a single line definition file declare var _ : any will allow you to call any function you want on _, but then, of course, you are also still able to make mistakes: _.foobar() would be a legal TypeScript call, but is, of course, an illegal call at run-time. If you want proper type support and code completion your definition file needs to to be more exact (see lodash definitions for an example).

Npm modules that come pre-packaged with their own type definitions are automatically understood by the TypeScript compiler (see documentation). For pretty much any other semi-popular JavaScript library that does not include its own definitions somebody out there has already made type definitions available through another npm module. These modules are prefixed with "@types/" and come from a Github repository called DefinitelyTyped.

There is one caveat: the type definitions must match the version of the library you are using at run-time. If they do not, TypeScript might disallow you from calling a function or dereferencing a variable that exists or allow you to call a function or dereference a variable that does not exist, simply because the types do not match the run-time at compile-time. So make sure you load the right version of the type definitions for the right version of the library you are using.

To be honest, there is a slight hassle to this and it may be one of the reasons you do not choose TypeScript, but instead go for something like Babel that does not suffer from having to get type definitions at all. On the other hand, if you know what you are doing you can easily overcome any kind of issues caused by incorrect or missing definition files.

Converting from JavaScript to TypeScript

Any .js file can be renamed to a .ts file and ran through the TypeScript compiler to get syntactically the same JavaScript code as an output (if it was syntactically correct in the first place). Even when the TypeScript compiler gets compilation errors it will still produce a .js file. It can even accept .js files as input with the --allowJs flag. This allows you to start with TypeScript right away. Unfortunately, compilation errors are likely to occur in the beginning. One does need to remember that these are not show-stopping errors like you may be used to with other compilers.

The compilation errors one gets in the beginning when converting a JavaScript project to a TypeScript project are unavoidable by TypeScript's nature. TypeScript checks all code for validity and thus it needs to know about all functions and variables that are used. Thus type definitions need to be in place for all of them otherwise compilation errors are bound to occur. As mentioned in the chapter above, for pretty much any JavaScript framework there are .d.ts files that can easily be acquired with the installation of DefinitelyTyped packages. It might, however, be that you've used some obscure library for which no TypeScript definitions are available or that you've polyfilled some JavaScript primitives. In that case, you must supply type definitions for these bits for the compilation errors to disappear. Just create a .d.ts file and include it in the tsconfig.json's files array, so that it is always considered by the TypeScript compiler. In it declare those bits that TypeScript does not know about as type any. Once you've eliminated all errors you can gradually introduce typing to those parts according to your needs.

Some work on (re)configuring your build pipeline will also be needed to get TypeScript into the build pipeline. As mentioned in the chapter on compilation there are plenty of good resources out there and I encourage you to look for seed projects that use the combination of tools you want to be working with.

The biggest hurdle is the learning curve. I encourage you to play around with a small project at first. Look how it works, how it builds, which files it uses, how it is configured, how it functions in your IDE, how it is structured, which tools it uses, etc. Converting a large JavaScript codebase to TypeScript is doable when you know what you are doing. Read this blog for example on converting 600k lines to typescript in 72 hours). Just make sure you have a good grasp of the language before you make the jump.

Adoption

TypeScript is open-source (Apache 2 licensed, see GitHub) and backed by Microsoft. Anders Hejlsberg, the lead architect of C# is spearheading the project. It's a very active project; the TypeScript team has been releasing a lot of new features in the last few years and a lot of great ones are still planned to come (see the roadmap).

Some facts about adoption and popularity:

  • In the 2017 StackOverflow developer survey TypeScript was the most popular JavaScript transpiler (9th place overall) and won third place in the most loved programming language category.
  • In the 2018 state of js survey TypeScript was declared as one of the two big winners in the JavaScript flavors category (with ES6 being the other).
  • In the 2019 StackOverlow deverloper survey TypeScript rose to the 9th place of most popular languages amongst professional developers, overtaking both C and C++. It again took third place amongst most the most loved languages.

Angular2 - Radio Button Binding

As much as this answer might not be the best depending on your use case, it works. Instead of using the Radio button for a Male and Female selection, using the <select> </select> works perfectly, both for saving and editing.

<select formControlName="gender" name="gender" class="">
  <option value="M">Male</option>
  <option value="F">Female</option>
</select>

The above should do just fine, for editing using FormGroup with patchValue. For creating, you could use [(ngModel)] instead of the formControlName. Still works.

The plumbing work involved with the radio button one, I chose to go with the select instead. Visually and UX-wise, it doesn't appear to be the best, but from a developer's standpoint, it's a ton easier.

Undefined behavior and sequence points

In C99(ISO/IEC 9899:TC3) which seems absent from this discussion thus far the following steteents are made regarding order of evaluaiton.

[...]the order of evaluation of subexpressions and the order in which side effects take place are both unspecified. (Section 6.5 pp 67)

The order of evaluation of the operands is unspecified. If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior[sic] is undefined.(Section 6.5.16 pp 91)

Understanding .get() method in Python

The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).

So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:

def myget(d, k, v=None):
  try: return d[k]
  except KeyError: return v

The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).

SQL Server - inner join when updating

UPDATE R 
SET R.status = '0' 
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P 
       ON R.pid = P.id 
WHERE R.id = '17190' 
  AND P.shopkeeper = '89137';

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I just want to add what solved this problem for me, as it is different to all of the above answers.

The ajax calls that were causing the problem were trying to pass an empty data object. It seems IE does not like this, but other browsers don't mind.

To fix it I simply removed data: {}, from the ajax call.

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

What is the difference between re.search and re.match?

re.search searches for the pattern throughout the string, whereas re.match does not search the pattern; if it does not, it has no other choice than to match it at start of the string.

CSS :not(:last-child):after selector

For me it work fine

&:not(:last-child){
            text-transform: uppercase;
        }

How to verify a Text present in the loaded page through WebDriver

If you are not bothered about the location of the text present, then you could use Driver.PageSource property as below:

Driver.PageSource.Contains("expected message");

Get the current file name in gulp.src()

I'm not sure how you want to use the file names, but one of these should help:

  • If you just want to see the names, you can use something like gulp-debug, which lists the details of the vinyl file. Insert this anywhere you want a list, like so:

    var gulp = require('gulp'),
        debug = require('gulp-debug');
    
    gulp.task('examples', function() {
        return gulp.src('./examples/*.html')
            .pipe(debug())
            .pipe(gulp.dest('./build'));
    });
    
  • Another option is gulp-filelog, which I haven't used, but sounds similar (it might be a bit cleaner).

  • Another options is gulp-filesize, which outputs both the file and it's size.

  • If you want more control, you can use something like gulp-tap, which lets you provide your own function and look at the files in the pipe.

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

CUDA incompatible with my gcc version

Another way of configuring nvcc to use a specific version of gcc (gcc-4.4, for instance), is to edit nvcc.profile and alter PATH to include the path to the gcc you want to use first.

For example (gcc-4.4.6 installed in /opt):

PATH += /opt/gcc-4.4.6/lib/gcc/x86_64-unknown-linux-gnu/4.4.6:/opt/gcc-4.4.6/bin:$(TOP)/open64/bin:$(TOP)/share/cuda/nvvm:$(_HERE_):

The location of nvcc.profile varies, but it should be in the same directory as the nvcc executable itself.

This is a bit of a hack, as nvcc.profile is not intended for user configuration as per the nvcc manual, but it was the solution which worked best for me.

Convert timestamp long to normal date format

Not sure if JSF provides a built-in functionality, but you could use java.sql.Date's constructor to convert to a date object: http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html#Date(long)

Then you should be able to use higher level features provided by Java SE, Java EE to display and format the extracted date. You could instantiate a java.util.Calendar and explicitly set the time: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#setTime(java.util.Date)

EDIT: The JSF components should not take care of the conversion. Your data access layer (persistence layer) should take care of this. In other words, your JSF components should not handle the long typed attributes but only a Date or Calendar typed attributes.

How to restore the permissions of files and directories within git if they have been modified?

Git doesn't store file permissions other than executable scripts. Consider using something like git-cache-meta to save file ownership and permissions.

Git can only store two types of modes: 755 (executable) and 644 (not executable). If your file was 444 git would store it has 644.

JQuery, setTimeout not working

This accomplishes the same thing but is much simpler:

$(document).ready(function() {  
   $("#board").delay(1000).append(".");
});

You can chain a delay before almost any jQuery method.

c# Best Method to create a log file

Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.

Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.

Find by key deep in a nested array

Recursion is your friend. I updated the function to account for property arrays:

function getObject(theObject) {
    var result = null;
    if(theObject instanceof Array) {
        for(var i = 0; i < theObject.length; i++) {
            result = getObject(theObject[i]);
            if (result) {
                break;
            }   
        }
    }
    else
    {
        for(var prop in theObject) {
            console.log(prop + ': ' + theObject[prop]);
            if(prop == 'id') {
                if(theObject[prop] == 1) {
                    return theObject;
                }
            }
            if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                result = getObject(theObject[prop]);
                if (result) {
                    break;
                }
            } 
        }
    }
    return result;
}

updated jsFiddle: http://jsfiddle.net/FM3qu/7/

Console.log not working at all

I feel a bit stupid on this but let this be a lesson to everyone...Make sure you target the right selector!

Basically the console wasn't logging anything because this particular code snippet was attempting to grab the scrolling area of my window, when in fact my code was setup differently to scroll an entire DIV instead. As soon as I changed:

$(window).scroll(function() {

to this:

$('#scroller').scroll(function() {

The console started logging the correct messages.

What does 'var that = this;' mean in JavaScript?

I'm going to begin this answer with an illustration:

var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
    // this is a reference to the element clicked on

    var that = this;

    colours.forEach(function() {
        // this is undefined
        // that is a reference to the element clicked on
    });
});

My answer originally demonstrated this with jQuery, which is only very slightly different:

$('#element').click(function(){
    // this is a reference to the element clicked on

    var that = this;

    $('.elements').each(function(){
        // this is a reference to the current element in the loop
        // that is still a reference to the element clicked on
    });
});

Because this frequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to that allows you still to access the original value of this.

Personally, I dislike the use of that as the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I'd probably use clickedEl.

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

OPTional

It holds optional software and packages that you install that are not required for the system to run.

Java web start - Unable to load resource

changing java proxy settings to direct connection did not fix my issue.

What worked for me:

  1. Run "Configure Java" as administrator.
  2. Go to Advanced
  3. Scroll to bottom
  4. Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"
  5. Save

T-SQL How to create tables dynamically in stored procedures?

This is a way to create tables dynamically using T-SQL stored procedures:

declare @cmd nvarchar(1000), @MyTableName nvarchar(100);
set @MyTableName = 'CustomerDetails';
set @cmd = 'CREATE TABLE dbo.' + quotename(@MyTableName, '[') + '(ColumnName1 int not null,ColumnName2 int not null);';

Execute it as:

exec(@cmd);

SQL: How To Select Earliest Row

In this case a relatively simple GROUP BY can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER():

Runnable example (Wofkflow20 error in original data corrected)

;WITH partitioned AS (
    SELECT company
        ,workflow
        ,date
        ,other_columns
        ,ROW_NUMBER() OVER(PARTITION BY company, workflow
                            ORDER BY date) AS seq
    FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1

What are invalid characters in XML

In summary, valid characters in the text are:

  • tab, line-feed and carriage-return.
  • all non-control characters are valid except & and <.
  • > is not valid if following ]].

Sections 2.2 and 2.4 of the XML specification provide the answer in detail:

Characters

Legal characters are tab, carriage return, line feed, and the legal characters of Unicode and ISO/IEC 10646

Character data

The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.

How to add class active on specific li on user click with jQuery

        // Remove active for all items.
        $('.sidebar-menu li').removeClass('active');
        // highlight submenu item
        $('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
        // Highlight parent menu item.
        $('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active')

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

Have you tried using the "auto-fill" in Excel?

If you have an entire column of items you put the formula in the first cell, make sure you get the result you desire and then you can do the copy/paste, or use auto fill which is an option that sits on the bottom right corner of the cell.

You go to that corner in the cell and once your cursor changes to a "+", you can double-click on it and it should populate all the way down to the last entry (as long as there are no populated cells, that is).

What's the difference between Perl's backticks, system, and exec?

In general I use system, open, IPC::Open2, or IPC::Open3 depending on what I want to do. The qx// operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open to much handier.

system: run a command and wait for it to return

Use system when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.

#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");

or

#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");

qx// or ``: run a command and capture its STDOUT

Use qx// when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.

#arguments are always processed by the shell

#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;

#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;

exec: replace the current process with another process.

Use exec along with fork when you want to run a command, don't care about its output, and don't want to wait for it to return. system is really just

sub my_system {
    die "could not fork\n" unless defined(my $pid = fork);
    return waitpid $pid, 0 if $pid; #parent waits for child
    exec @_; #replace child with new process
}

You may also want to read the waitpid and perlipc manuals.

open: run a process and create a pipe to its STDIN or STDERR

Use open when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).

#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
    or die "could not open $filename: $!";

#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
    or die "could not open $filename: $!";

IPC::Open2: run a process and create a pipe to both STDIN and STDOUT

Use IPC::Open2 when you need to read from and write to a process's STDIN and STDOUT.

use IPC::Open2;

open2 my $out, my $in, "/usr/bin/bc"
    or die "could not run bc";

print $in "5+6\n";

my $answer = <$out>;

IPC::Open3: run a process and create a pipe to STDIN, STDOUT, and STDERR

use IPC::Open3 when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.

Change the color of a checked menu item in a navigation drawer

Here is the another way to achive this:

public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            item.setEnabled(true);
            item.setTitle(Html.fromHtml("<font color='#ff3824'>Settings</font>"));
            return false;
            }
        });


    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Reading settings from app.config or web.config in .NET

Another possible solution:

var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();

Removing character in list of strings

mylist = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print mylist
j=0
for i in mylist:
    mylist[j]=i.rstrip("8")
    j+=1
print mylist

C default arguments

No, but you might consider using a set of functions (or macros) to approximate using default args:

// No default args
int foo3(int a, int b, int c)
{
    return ...;
}

// Default 3rd arg
int foo2(int a, int b)
{
    return foo3(a, b, 0);  // default c
}

// Default 2nd and 3rd args
int foo1(int a)
{
    return foo3(a, 1, 0);  // default b and c
}

Import module from subfolder

Set your PYTHONPATH environment variable. For example like this PYTHONPATH=.:.. (for *nix family).

Also you can manually add your current directory (src in your case) to pythonpath:

import os
import sys
sys.path.insert(0, os.getcwd())

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

Defining private module functions in python

embedded with closures or functions is one way. This is common in JS although not required for non-browser platforms or browser workers.

In Python it seems a bit strange, but if something really needs to be hidden than that might be the way. More to the point using the python API and keeping things that require to be hidden in the C (or other language) is probably the best way. Failing that I would go for putting the code inside a function, calling that and having it return the items you want to export.

How do you create a Distinct query in HQL

It's worth noting that the distinct keyword in HQL does not map directly to the distinct keyword in SQL.

If you use the distinct keyword in HQL, then sometimes Hibernate will use the distinct SQL keyword, but in some situations it will use a result transformer to produce distinct results. For example when you are using an outer join like this:

select distinct o from Order o left join fetch o.lineItems

It is not possible to filter out duplicates at the SQL level in this case, so Hibernate uses a ResultTransformer to filter duplicates after the SQL query has been performed.

Always pass weak reference of self into block in ARC?

As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog in your operation's dealloc method and confirm that's getting called.

You said:

I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit

The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self, or even just references an instance variable of self, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation subclass is released.

For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.

If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation is getting deallocated). A common example is the use of a repeating NSTimer. Or some custom delegate or other object that is erroneously maintaining a strong reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:

record reference counts in Xcode 6

Or in Xcode 5:

record reference counts in Xcode 5

-bash: export: `=': not a valid identifier

First of all go to the /home directorty then open invisible shell script with some text editor, ~/.bash_profile (macOS) or ~/.bashrc (linux) go to the bottom, you would see something like this,

export LD_LIBRARY_PATH = /usr/local/lib

change this like that( remove blank point around the = ),

export LD_LIBRARY_PATH=/usr/local/lib

it should be useful.

Simple bubble sort c#

public static int[] BubbleSort(int[] arr)
{
   int length = arr.Length();

   while (length > 0)
   {
      int newLength = 0;
      for (int i = 1; i < length; i++)
      {
         if (arr[i - 1] > arr[i])
         {
            Swap(ref arr[i - 1], ref arr[i]); 
            newLength = i;   
         }   
      }
      length = newLength;
   }
}

public static void Swap(ref int x, ref int y)
{
   int temp = y;
   y = x;
   x = temp;
}

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

How can I compare time in SQL Server?

TL;DR

Separate the time value from the date value if you want to use indexes in your search (you probably should, for performance). You can: (1) use function-based indexes or (2) create a new column for time only, index this column and use it in you SELECT clause.


Keep in mind you will lose any index performance boost if you use functions in a SQL's WHERE clause, the engine has to do a scan search. Just run your query with EXPLAIN SELECT... to confirm this. This happens because the engine has to process EVERY value in the field for EACH comparison, and the converted value is not indexed.

Most answers say to use float(), convert(), cast(), addtime(), etc.. Again, your database won't use indexes if you do this. For small tables that may be OK.

It is OK to use functions in WHERE params though (where field = func(value)), because you won't be changing EACH field's value in the table.

In case you want to keep use of indexes, you can create a function-based index for the time value. The proper way to do this (and support for it) may depend on your database engine. Another option is adding a column to store only the time value and index this column, but try the former approach first.


Edit 06-02

Do some performance tests before updating your database to have a new time column or whatever to make use of indexes. In my tests, I found out the performance boost was minimal (when I could see some improvement) and wouldn't be worth the trouble and overhead of adding a new index.

google chrome extension :: console.log() from background page?

In relation to the original question I'd like to add to the accepted answer by Mohamed Mansour that there is also a way to make this work the other way around:

You can access other extension pages (i.e. options page, popup page) from within the background page/script with the chrome.extension.getViews() call. As described here.

 // overwrite the console object with the right one.
var optionsPage = (  chrome.extension.getViews()  
                 &&  (chrome.extension.getViews().length > 1)  ) 
                ? chrome.extension.getViews()[1] : null;

 // safety precaution.
if (optionsPage) {
  var console = optionsPage.console;
}

Getting SyntaxError for print with keyword argument end=' '

Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because print is still a statement.

print("foo" % bar, end=" ")

in Python 2.x is identical to

print ("foo" % bar, end=" ")

or

print "foo" % bar, end=" "

i.e. as a call to print with a tuple as argument.

That's obviously bad syntax (literals don't take keyword arguments). In Python 3.x print is an actual function, so it takes keyword arguments, too.

The correct idiom in Python 2.x for end=" " is:

print "foo" % bar,

(note the final comma, this makes it end the line with a space rather than a linebreak)

If you want more control over the output, consider using sys.stdout directly. This won't do any special magic with the output.

Of course in somewhat recent versions of Python 2.x (2.5 should have it, not sure about 2.4), you can use the __future__ module to enable it in your script file:

from __future__ import print_function

The same goes with unicode_literals and some other nice things (with_statement, for example). This won't work in really old versions (i.e. created before the feature was introduced) of Python 2.x, though.

How to check if a table is locked in sql server

Better yet, consider sp_getapplock which is designed for this. Or use SET LOCK_TIMEOUT

Otherwise, you'd have to do something with sys.dm_tran_locks which I'd use only for DBA stuff: not for user defined concurrency.

How do I "break" out of an if statement?

Nested ifs:

if (condition)
{
    // half-massive amount of code here

    if (!breakOutCondition)
    {
        //half-massive amount of code here
    }
}

At the risk of being downvoted -- it's happened to me in the past -- I'll mention that another (unpopular) option would of course be the dreaded goto; a break statement is just a goto in disguise.

And finally, I'll echo the common sentiment that your design could probably be improved so that the massive if statement is not necessary, let alone breaking out of it. At least you should be able to extract a couple of methods, and use a return:

if (condition)
{
    ExtractedMethod1();

    if (breakOutCondition)
        return;

    ExtractedMethod2();
}

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

VS Code - Search for text in all files in a directory

I think these official guide should work for your case.

VS Code allows you to quickly search over all files in the currently-opened folder. Press Ctrl+Shift+F and enter in your search term. Search results are grouped into files containing the search term, with an indication of the hits in each file and its location. Expand a file to see a preview of all of the hits within that file. Then single-click on one of the hits to view it in the editor.

How do I set up curl to permanently use a proxy?

One notice. On Windows, place your _curlrc in '%APPDATA%' or '%USERPROFILE%\Application Data'.

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

I had this issue recently and I resolved it by simply rolling IE8 back to IE7.

My guess is that IE7 had these files as a wrapper for working on Windows XP, but IE8 was likely made to work with Vista/7 so it removed the files because the later editions just don't use the shim.

Create folder with batch but only if it doesn't already exist

This should work for you:

IF NOT EXIST "\path\to\your\folder" md \path\to\your\folder

However, there is another method, but it may not be 100% useful:

md \path\to\your\folder >NUL 2>NUL

This one creates the folder, but does not show the error output if folder exists. I highly recommend that you use the first one. The second one is if you have problems with the other.

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Load dimension value from res/values/dimension.xml from source code

Context.getResources().getDimension(int id);

Display image at 50% of its "native" size

Set the image to be the background of a div, then set the background size to be half the width of the image.

<div class="myimage"></div>

Then in your css, if your image is 300px x 200px:

.myimage {
    background: url('images/myimage.png') no-repeat;
    background-size:150px;
    width:150px;
    height:100px;
}

How to cast Object to boolean?

If the object is actually a Boolean instance, then just cast it:

boolean di = (Boolean) someObject;

The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:

boolean di = ((Boolean) someObject).booleanValue();

If someObject doesn't refer to a Boolean value though, what do you want the code to do?

git ignore vim temporary files

I found this will have git ignore temporary files created by vim:

[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~

It can also be viewed here.

Javascript call() & apply() vs bind()?

call/apply executes function immediately:

func.call(context, arguments);
func.apply(context, [argument1,argument2,..]);

bind doesn't execute function immediately, but returns wrapped apply function (for later execution):

function bind(func, context) {
    return function() {
        return func.apply(context, arguments);
    };
}

How to add a second css class with a conditional value in razor MVC 4

You can add property to your model as follows:

    public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }

and then your view will be simpler and will contain no logic at all:

    <div class="details @Model.DetailsClass"/>

This will work even with many classes and will not render class if it is null:

    <div class="@Model.Class1 @Model.Class2"/>

with 2 not null properties will render:

    <div class="class1 class2"/>

if class1 is null

    <div class=" class2"/>

Debugging in Maven?

I thought I would expand on these answers for OSX and Linux folks (not that they need it):

I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.

$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found

DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.

I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)

Let's see:

$ which mvn
/usr/local/bin/mvn

There you are... you little b@stard.

Now where did you get installed to:

$ ls -l /usr/local/bin/mvn

lrwxr-xr-x  1 root  wheel  39 Oct 31 13:00 /
                  /usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn

Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...

Do you have your little buddy mvnDebug with you?

$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug 
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug

Good. Good. Very good. All going as planned.

Now move that little b@stard where I can remember him more easily.

$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
  ln: /usr/local/bin/mvnDebug: Permission denied

Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!

$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug

Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)

$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000

Internally mvnDebug uses this:

MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE  \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"

So you could modify it (I usually debug on port 9090).

This blog explains how to setup Eclipse remote debugging (shudder)

http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html

Ditto Netbeans

https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a

Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html

Here is some good docs on the -Xdebug command in general.

http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."

"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."

-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp

Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.

Check if key exists and iterate the JSON array using Python

You can use a try-except

try:
   print(str.to.id)
except AttributeError: # Not a Retweet
   print('null')

C# Enum - How to Compare Value

Comparision:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

In case to prevent the NullPointerException you could add the following condition before comparing the AccountType:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}

or shorter version:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}

Two way sync with rsync

You could try csync, it is the sync engine under the hood of owncloud.

Delete a row in DataGridView Control in VB.NET

For Each row As DataGridViewRow In yourDGV.SelectedRows
    yourDGV.Rows.Remove(row)
Next

This will delete all rows that had been selected.

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

In newer versions of OS X (especially Yosemite, EL Capitan), Apple has removed Java support for security reasons. To fix this you have to do the following.

  1. Download Java for OS X 2015-001 from this link: https://support.apple.com/kb/dl1572?locale=en_US
  2. Mount the disk image file and install Java 6 runtime for OS X.

    After this you should not be seeing any of the below messages:

    - Unable to find any JVMs matching version "(null)"

    - No Java runtime present, try --request to install.

    This should resolve the issue for the pop-up shown below: enter image description here

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Use Message.get_payload

b = email.message_from_string(a)
if b.is_multipart():
    for payload in b.get_payload():
        # if payload.is_multipart(): ...
        print payload.get_payload()
else:
    print b.get_payload()

Check if SQL Connection is Open or Closed

The .NET documentation says: State Property: A bitwise combination of the ConnectionState values

So I think you should check

!myConnection.State.HasFlag(ConnectionState.Open)

instead of

myConnection.State != ConnectionState.Open

because State can have multiple flags.

IIS7 URL Redirection from root to sub directory

I think, this could be done without IIS URL Rewrite module. <httpRedirect> supports wildcards, so you can configure it this way:

  <system.webServer>
    <httpRedirect enabled="true">
      <add wildcard="/" destination="/menu_1/MainScreen.aspx" />
    </httpRedirect>
  </system.webServer>

Note that you need to have the "HTTP Redirection" feature enabled on IIS - see HTTP Redirects

CSS-Only Scrollable Table with fixed headers

Only with CSS :

CSS:

tr {
  width: 100%;
  display: inline-table;
  table-layout: fixed;
}

table{
 height:300px;              // <-- Select the height of the table
 display: -moz-groupbox;    // Firefox Bad Effect
}
tbody{
  overflow-y: scroll;      
  height: 200px;            //  <-- Select the height of the body
  width: 100%;
  position: absolute;
}

Bootply : http://www.bootply.com/AgI8LpDugl

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

Get current domain

Everybody is using the parse_url function, but sometimes user may pass the argumet in different format.

So as to fix that, I have created the function. Check this out:

function fixDomainName($url='')
{
    $strToLower = strtolower(trim($url));
    $httpPregReplace = preg_replace('/^http:\/\//i', '', $strToLower);
    $httpsPregReplace = preg_replace('/^https:\/\//i', '', $httpPregReplace);
    $wwwPregReplace = preg_replace('/^www\./i', '', $httpsPregReplace);
    $explodeToArray = explode('/', $wwwPregReplace);
    $finalDomainName = trim($explodeToArray[0]);
    return $finalDomainName;
}

Just pass the URL and get the domain.

For example,

echo fixDomainName('https://stackoverflow.com');

will return the result will be

stackoverflow.com

And in some situation:

echo fixDomainName('stackoverflow.com/questions/id/slug');

And it will also return stackoverflow.com.

How to chain scope queries with OR instead of AND?

You can also use MetaWhere gem to not mix up your code with SQL stuff:

Person.where((:name => "John") | (:lastname => "Smith"))

Adding three months to a date in PHP

The following should work, but you may need to change the format:

echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));

ANTLR: Is there a simple example?

For Antlr 4 the java code generation process is below:-

java -cp antlr-4.5.3-complete.jar org.antlr.v4.Tool Exp.g

Update your jar name in classpath accordingly.

Mockito. Verify method arguments

Have you tried it with the same() matcher? As in:

verify(mockObj).someMethod(same(specificInstance));

I had the same problem. I tried it with the eq() matcher as well as the refEq() matcher but I always had false positives. When I used the same() matcher, the test failed when the arguments were different instances and passed once the arguments were the same instance.

One time page refresh after first page load

        var foo = true;
        if (foo){
            window.location.reload(true);
            foo = false;

        }

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

I was able to figure it out. In case someone wants to know below the code that worked for me:

ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

AFNetworking Post Request

// For Image with parameter /// AFMultipartFormData

NSDictionary *dictParam =@{@"user_id":strGlobalUserId,@"name":[dictParameter objectForKey:@"Name"],@"contact":[dictParameter objectForKey:@"Contact Number"]};

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    if (Imagedata.length>0) {
        [formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    }
} progress:nil
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {
     NSLog(@"update_profile %@", responseObject);

     if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
             [self.navigationController popViewControllerAnimated:YES];

         }] animated:YES completion:nil];


     }
     else
     {
         [self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
         }] animated:YES completion:nil];

     }
     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     [SVProgressHUD dismiss];
 }];

What is the OAuth 2.0 Bearer Token exactly?

Bearer token is one or more repetition of alphabet, digit, "-" , "." , "_" , "~" , "+" , "/" followed by 0 or more "=".

RFC 6750 2.1. Authorization Request Header Field (Format is ABNF (Augmented BNF))

The syntax for Bearer credentials is as follows:

     b64token    = 1*( ALPHA / DIGIT /
                       "-" / "." / "_" / "~" / "+" / "/" ) *"="
     credentials = "Bearer" 1*SP b64token

It looks like Base64 but according to Should the token in the header be base64 encoded?, it is not.

Digging a bit deeper in to "HTTP/1.1, part 7: Authentication"**, however, I see that b64token is just an ABNF syntax definition allowing for characters typically used in base64, base64url, etc.. So the b64token doesn't define any encoding or decoding but rather just defines what characters can be used in the part of the Authorization header that will contain the access token.

This fully addresses the first 3 items in the OP question's list. So I'm extending this answer to address the 4th question, about whether the token must be validated, so @mon feel free to remove or edit:

The authorizer is responsible for accepting or rejecting the http request. If the authorizer says the token is valid, it's up to you to decide what this means:

  • Does the authorizer have a way of inspecting the URL, identifying the operation, and looking up some role-based access control database to see if it is allowed? If yes and the request comes through, the service can assume it is allowed, and does not need to verify.
  • Is the token an all-or-nothing, so if the token is correct, all operations are allowed? Then the service doesn't need to verify.
  • Does the token mean "this request is allowed, but here is the UUID for the role, you check whether the operation is allowed". Then it's up to the service to look up that role, and see if the operation is allowed.

References

How do I install PyCrypto on Windows?

For Windows 7:

To install Pycrypto in Windows,

Try this in Command Prompt,

Set path=C:\Python27\Scripts (i.e path where easy_install is located)

Then execute the following,

easy_install pycrypto

For Ubuntu:

Try this,

Download Pycrypto from "https://pypi.python.org/pypi/pycrypto"

Then change your current path to downloaded path using your terminal and user should be root:

Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#

Then execute the following using the terminal:

python setup.py install

It's worked for me. Hope works for all..

Update records using LINQ

You have two options as far as I know:

  1. Perform your query, iterate over it to modify the entities, then call SaveChanges().
  2. Execute a SQL command like you mentioned at the top of your question. To see how to do this, take a look at this page.

If you use option 2, you're losing some of the abstraction that the Entity Framework gives you, but if you need to perform a very large update, this might be the best choice for performance reasons.

How can I make git accept a self signed certificate?

It works for me just run following command

git config --global http.sslVerify false

it will open a git credentials window give your credentials . for first time only it ask

SELECT inside a COUNT

SELECT a AS current_a, COUNT(*) AS b,
   (SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d
   from t group by a order by b desc

A variable modified inside a while loop is not remembered

You are the 742342nd user to ask this bash FAQ. The answer also describes the general case of variables set in subshells created by pipes:

E4) If I pipe the output of a command into read variable, why doesn't the output show up in $variable when the read command finishes?

This has to do with the parent-child relationship between Unix processes. It affects all commands run in pipelines, not just simple calls to read. For example, piping a command's output into a while loop that repeatedly calls read will result in the same behavior.

Each element of a pipeline, even a builtin or shell function, runs in a separate process, a child of the shell running the pipeline. A subprocess cannot affect its parent's environment. When the read command sets the variable to the input, that variable is set only in the subshell, not the parent shell. When the subshell exits, the value of the variable is lost.

Many pipelines that end with read variable can be converted into command substitutions, which will capture the output of a specified command. The output can then be assigned to a variable:

grep ^gnu /usr/lib/news/active | wc -l | read ngroup

can be converted into

ngroup=$(grep ^gnu /usr/lib/news/active | wc -l)

This does not, unfortunately, work to split the text among multiple variables, as read does when given multiple variable arguments. If you need to do this, you can either use the command substitution above to read the output into a variable and chop up the variable using the bash pattern removal expansion operators or use some variant of the following approach.

Say /usr/local/bin/ipaddr is the following shell script:

#! /bin/sh
host `hostname` | awk '/address/ {print $NF}'

Instead of using

/usr/local/bin/ipaddr | read A B C D

to break the local machine's IP address into separate octets, use

OIFS="$IFS"
IFS=.
set -- $(/usr/local/bin/ipaddr)
IFS="$OIFS"
A="$1" B="$2" C="$3" D="$4"

Beware, however, that this will change the shell's positional parameters. If you need them, you should save them before doing this.

This is the general approach -- in most cases you will not need to set $IFS to a different value.

Some other user-supplied alternatives include:

read A B C D << HERE
    $(IFS=.; echo $(/usr/local/bin/ipaddr))
HERE

and, where process substitution is available,

read A B C D < <(IFS=.; echo $(/usr/local/bin/ipaddr))

Split function equivalent in T-SQL?

This blog came with a pretty good solution using XML in T-SQL.

This is the function I came up with based on that blog (change function name and result type cast per need):

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[SplitIntoBigints]
(@List varchar(MAX), @Splitter char)
RETURNS TABLE 
AS
RETURN 
(
    WITH SplittedXML AS(
        SELECT CAST('<v>' + REPLACE(@List, @Splitter, '</v><v>') + '</v>' AS XML) AS Splitted
    )
    SELECT x.v.value('.', 'bigint') AS Value
    FROM SplittedXML
    CROSS APPLY Splitted.nodes('//v') x(v)
)
GO

How do you style a TextInput in react native for password input

I am using 0.56RC secureTextEntry={true} Along with password={true} then only its working as mentioned by @NicholasByDesign

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Can I stretch text using CSS?

I'll answer for horizontal stretching of text, since the vertical is the easy part - just use "transform: scaleY()"

_x000D_
_x000D_
.stretched-text {
  letter-spacing: 2px;
  display: inline-block;
  font-size: 32px;
  transform: scaleY(0.5);
  transform-origin: 0 0;
  margin-bottom: -50%;
}
span {
  font-size: 16px;
  vertical-align: top;
}
_x000D_
<span class="stretched-text">this is some stretched text</span>
<span>and this is some random<br />triple line <br />not stretched text</span>
_x000D_
_x000D_
_x000D_

letter-spacing just adds space between letters, stretches nothing, but it's kinda relative

inline-block because inline elements are too restrictive and the code below wouldn't work otherwise

Now the combination that makes the difference

font-size to get to the size we want - that way the text will really be of the length it's supposed to be and the text before and after it will appear next to it (scaleX is just for show, the browser still sees the element at its original size when positioning other elements).

scaleY to reduce the height of the text, so that it's the same as the text beside it.

transform-origin to make the text scale from the top of the line.

margin-bottom set to a negative value, so that the next line will not be far below - preferably percentage, so that we won't change the line-height property. vertical-align set to top, to prevent the text before or after from floating to other heights (since the stretched text has a real size of 32px)

-- The simple span element has a font-size, only as a reference.

The question asked for a way to prevent the boldness of the text caused by the stretch and I still haven't given one, BUT the font-weight property has more values than just normal and bold.

I know, you just can't see that, but if you search for the appropriate fonts, you can use the more values.

How is "mvn clean install" different from "mvn install"?

To stick with the Maven terms:

  • "clean" is a phase of the clean lifecycle
  • "install" is a phase of the default lifecycle

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference

JSchException: Algorithm negotiation fail

FWIW, I had this same error message under JSch 0.1.50. Upgrading to 0.1.52 solved the problem.

The type or namespace name 'System' could not be found

I had the same problem earlier when I tried to edit an open source project from the internet .

Solved it by just Cleaning the solution and rebuilding it .

Hope this helps.

How do I get the classes of all columns in a data frame?

One option is to use lapply and class. For example:

> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"

$SomeNumeric
[1] "numeric"

Another option is str:

> str(foo)
'data.frame':   2 obs. of  2 variables:
 $ SomeFactor : Factor w/ 2 levels "a","b": 1 2
 $ SomeNumeric: num  1 2

SQL SELECT multi-columns INTO multi-variable

SELECT @var = col1,
       @var2 = col2
FROM   Table

Here is some interesting information about SET / SELECT

  • SET is the ANSI standard for variable assignment, SELECT is not.
  • SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  • If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  • When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  • As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Illegal access: this web application instance has been stopped already

I suspect that this occurs after an attempt to undeploy your app. Do you ever kill off that thread that you've initialised during the init() process ? I would do this in the corresponding destroy() method.

Passing a Bundle on startActivity()?

You have a few options:

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);  

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);


Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key)

NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.

What does Docker add to lxc-tools (the userspace LXC tools)?

Going to keep this pithier, this is already asked and answered above .

I'd step back however and answer it slightly differently, the docker engine itself adds orchestration as one of its extras and this is the disruptive part. Once you start running an app as a combination of containers running 'somewhere' across multiple container engines it gets really exciting. Robustness, Horizontal Scaling, complete abstraction from the underlying hardware, i could go on and on...

Its not just Docker that gives you this, in fact the de facto Container Orchestration standard is Kubernetes which comes in a lot of flavours, a Docker one, but also OpenShift, SuSe, Azure, AWS...

Then beneath K8S there are alternative container engines; the interesting ones are Docker and CRIO - recently built, daemonless, intended as a container engine specifically for Kubernetes but immature. Its the competition between these that I think will be the real long term choice for a container engine.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

There are two main differences.

Accessing the association sides

The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.

So, for a unidirectional @ManyToOne association, it means you can only access the relationship from the child side where the foreign key resides.

If you have a unidirectional @OneToMany association, it means you can only access the relationship from the parent side which manages the foreign key.

For the bidirectional @OneToMany association, you can navigate the association in both ways, either from the parent or from the child side.

You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.

Performance

The second aspect is related to performance.

  1. For @OneToMany, unidirectional associations don't perform as well as bidirectional ones.
  2. For @OneToOne, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.
  3. For @ManyToMany, the collection type makes quite a difference as Sets perform better than Lists.

How do I auto-resize an image to fit a 'div' container?

Give the height and width you need for your image to the div that contains the <img> tag. Don't forget to give the height/width in the proper style tag.

In the <img> tag, give the max-height and max-width as 100%.

<div style="height:750px; width:700px;">
    <img alt="That Image" style="max-height:100%; max-width:100%;" src="">
</div>

You can add the details in the appropriate classes after you get it right.

SQL Server Installation - What is the Installation Media Folder?

For SQL Server 2017

Download and run the installer, you are given 3 options:

  1. Basic
  2. Custom
  3. Download Media <- pick this one!

    • Select Language
    • Select ISO
    • Set download location
    • Click download
    • Exit installer once finished
  4. Extract ISO using your preferred archive utility or mount

logout and redirecting session in php

Only this is necessary

session_start();
unset($_SESSION["nome"]);  // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");

How to get the root dir of the Symfony2 application?

In Symfony 3.3 you can use

$projectRoot = $this->get('kernel')->getProjectDir();

to get the web/project root.

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Oracle database: How to read a BLOB?

You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2()).

SELECT b FROM foo;
-- (BLOB)

SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000

This is handy because you this is the same format used for inserting into BLOB columns:

CREATE GLOBAL TEMPORARY TABLE foo (
    b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');

DESC foo;
-- Name Null Type 
-- ---- ---- ---- 
-- B        BLOB 

However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR for a more complicated approach that will allow you to see substrings of the BLOB.

did you specify the right host or port? error on Kubernetes

Solution is this:

minikube delete
minikube start --vm-driver none

Bulk insert with SQLAlchemy ORM

I usually do it using add_all.

from app import session
from models import User

objects = [User(name="u1"), User(name="u2"), User(name="u3")]
session.add_all(objects)
session.commit()

How can I make a menubar fixed on the top while scrolling

This should get you started

 <div class="menuBar">
        <img class="logo" src="logo.jpg"/>
        <div class="nav"> 
            <ul>
                <li>Menu1</li>
                <li>Menu 2</li>
                <li>Menu 3</li>
            </ul> 
        </div>
    </div>



body{
    margin-top:50px;}
.menuBar{
    width:100%;
    height:50px;
    display:block;
    position:absolute;
    top:0;
    left:0;
    }
.logo{
    float:left;
    }
.nav{
    float:right;
    margin-right:10px;}
.nav ul li{
    list-style:none;
    float:left;
    }

downloading all the files in a directory with cURL

If you're not bound to curl, you might want to use wget in recursive mode but restricting it to one level of recursion, try the following;

wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
  • --no-parent : Do not ever ascend to the parent directory when retrieving recursively.
  • --level=depth : Specify recursion maximum depth level depth. The default maximum depth is five layers.
  • --no-directories : Do not create a hierarchy of directories when retrieving recursively.

How to use the CSV MIME-type?

You could try to force the browser to open a "Save As..." dialog by doing something like:

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
echo "cell 1, cell 2";

Which should work across most major browsers.

Toggle Class in React

Toggle function in react

At first you should create constructor like this

constructor(props) {
        super(props);
        this.state = {
            close: true,
        };
    }

Then create a function like this

yourFunction = () => {
        this.setState({
            close: !this.state.close,
        });
    };

then use this like

render() {
        const {close} = this.state;
        return (

            <Fragment>

                 <div onClick={() => this.yourFunction()}></div>

                 <div className={close ? "isYourDefaultClass" : "isYourOnChangeClass"}></div>

            </Fragment>
        )
    }
}

Please give better solutions

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

How to remove listview all items

if you used List object and passed to the adapter you can remove the value from the List object and than call the notifyDataSetChanged() using adapter object.

for e.g.

List<String> list = new ArrayList<String>();
ArrayAdapter adapter;


adapter = new ArrayAdapter<String>(DeleteManyTask.this, 
            android.R.layout.simple_list_item_1,
            (String[])list.toArray(new String[0]));

listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);

listview.setAdapter(listAdapter);

for remove do this way

list.remove(index); //or
list.clear();
adpater.notifyDataSetChanged();

or without list object remove item from list.

adapter.clear();
adpater.notifyDataSetChanged();

No submodule mapping found in .gitmodule for a path that's not a submodule

Scenario: changing the submodule from directory dirA-xxx to another directory dirB-xxx

  1. move the dirA-xxx to dirB-xxx
  2. modify entry in .gitmodules to use dirB-xxx
  3. modify entry in .git/config to use dirB-xxx
  4. modify .git/modules/dirA-xxx/config to reflect the correct directory
  5. modify dirA-xxx/.git to reflect the correct directory
  6. run git submodule status

    if return error: No submodule mapping found in .gitmodules for path dirA-xxx. This is due to dirA-xxx is not existing, yet it is still tracked by git. Update the git index by: git rm --cached dirA-xxx

    Try with git submodule foreach git pull. I didn't go through the actual study of git submodule structure, so above steps may break something. Nonetheless going through above steps, things look good at the moment. If you have any insight or proper steps to get thing done, do share it here. :)

C# Copy a file to another location with a different name

Use the File.Copy method instead

eg.

File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt");

You can call it whatever you want in the newFile, and it will rename it accordingly.

Is there a way to perform "if" in python's lambda

Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like and, not, or, etc) in their body.

So, there's no way you could use a lambda for your example (because you can't use raise), but if you're willing to concede on that… You could use:

f = lambda x: x == 2 and x or None

AngularJS. How to call controller function from outside of controller component

I would rather include the factory as dependencies on the controllers than inject them with their own line of code: http://jsfiddle.net/XqDxG/550/

myModule.factory('mySharedService', function($rootScope) {
    return sharedService = {thing:"value"};
});

function ControllerZero($scope, mySharedService) {
    $scope.thing = mySharedService.thing;

ControllerZero.$inject = ['$scope', 'mySharedService'];

ImportError: Cannot import name X

If you are importing file1.py from file2.py and used this:

if __name__ == '__main__':
    # etc

Variables below that in file1.py cannot be imported to file2.py because __name__ does not equal __main__!

If you want to import something from file1.py to file2.py, you need to use this in file1.py:

if __name__ == 'file1':
    # etc

In case of doubt, make an assert statement to determine if __name__=='__main__'

How to handle click event in Button Column in Datagridview?

Here's the better answer:

You can't implement a button clicked event for button cells in a DataGridViewButtonColumn. Instead, you use the DataGridView's CellClicked event and determine if the event fired for a cell in your DataGridViewButtonColumn. Use the event's DataGridViewCellEventArgs.RowIndex property to find out which row was clicked.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
  // Ignore clicks that are not in our 
  if (e.ColumnIndex == dataGridView1.Columns["MyButtonColumn"].Index && e.RowIndex >= 0) {
    Console.WriteLine("Button on row {0} clicked", e.RowIndex);
  }
}

found here: button click event in datagridview

When should I create a destructor?

It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.

It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.

In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.

A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

Jenkins: Can comments be added to a Jenkinsfile?

The official Jenkins documentation only mentions single line commands like the following:

// Declarative //

and (see)

pipeline {
    /* insert Declarative Pipeline here */
}

The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:

/* a standalone multiline comment
   spanning two lines */
println "hello" /* a multiline comment starting
                   at the end of a statement */
println 1 /* one */ + 2 /* two */

or

/**
 * such a nice comment
 */

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Why do I get a SyntaxError for a Unicode escape in my file path?

I had the same error. Basically, I suspect that the path cannot start either with "U" or "User" after "C:\". I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.

In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.

Measuring elapsed time with the Time module

Here is an update to Vadim Shender's clever code with tabular output:

import collections
import time
from functools import wraps

PROF_DATA = collections.defaultdict(list)

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()
        ret = fn(*args, **kwargs)
        elapsed_time = time.time() - start_time
        PROF_DATA[fn.__name__].append(elapsed_time)
        return ret
    return with_profiling

Metrics = collections.namedtuple("Metrics", "sum_time num_calls min_time max_time avg_time fname")

def print_profile_data():
    results = []
    for fname, elapsed_times in PROF_DATA.items():
        num_calls = len(elapsed_times)
        min_time = min(elapsed_times)
        max_time = max(elapsed_times)
        sum_time = sum(elapsed_times)
        avg_time = sum_time / num_calls
        metrics = Metrics(sum_time, num_calls, min_time, max_time, avg_time, fname)
        results.append(metrics)
    total_time = sum([m.sum_time for m in results])
    print("\t".join(["Percent", "Sum", "Calls", "Min", "Max", "Mean", "Function"]))
    for m in sorted(results, reverse=True):
        print("%.1f\t%.3f\t%d\t%.3f\t%.3f\t%.3f\t%s" % (100 * m.sum_time / total_time, m.sum_time, m.num_calls, m.min_time, m.max_time, m.avg_time, m.fname))
    print("%.3f Total Time" % total_time)

PHP Warning Permission denied (13) on session_start()

I have had this issue before, you need more than the standard 755 or 644 permission to store the $_SESSION information. You need to be able to write to that file as that is how it remembers.

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

PPK ? OpenSSH RSA with PuttyGen & Docker.

Private key:

docker run --rm -v $(pwd):/app zinuzoid/puttygen private.ppk -O private-openssh -o my-openssh-key

Public key:

docker run --rm -v $(pwd):/app zinuzoid/puttygen private.ppk -L -o my-openssh-key.pub

See also https://hub.docker.com/r/zinuzoid/puttygen

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Here are three ways you can check if dict is empty. I prefer using the first way only though. The other two ways are way too wordy.

test_dict = {}

if not test_dict:
    print "Dict is Empty"


if not bool(test_dict):
    print "Dict is Empty"


if len(test_dict) == 0:
    print "Dict is Empty"