Programs & Examples On #Ssa

Static single assignment is a property of a compiler's intermediate representation for optimization and static analysis.

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

Uninitialized Constant MessagesController

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

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

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

rails g migration ChangeMessagesToMessage 

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

rake db:migrate 

And your app should be fine since then.

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

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.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

500 Error on AppHarbor but downloaded build works on my machine

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

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

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

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

iPhone is not available. Please reconnect the device

My experience, yesterday my iOS 13.6 is supported by Xcode 11.7 and now today the Xcode rejected my iPhone and I update the Xcode to version 12 and everything get back on track.

Solution:

Update your Xcode to the latest version.

Hint: there is no need to update iOS.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

The solution is:-

  • Check out the chrome version of your chrome.From chrome://settings/help
  • Check out which version of ChromeDriver is compatible with your current chrome version from here
  • download the compatible one and replace the existing ChromeDriver with a new ChromeDriver.
  • Now run the code

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

In a conda environment, this is what solved my problem (I was missing cudart64-100.dll:

  1. Downloaded it from dll-files.com/CUDART64_100.DLL

  2. Put it in my conda environment at C:\Users\<user>\Anaconda3\envs\<env name>\Library\bin

That's all it took! You can double check if it's working:

import tensorflow as tf
tf.config.experimental.list_physical_devices('GPU')

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

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

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

isset($cOTLdata['char_data'])

Which means the line should look something like this:

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

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

Template not provided using create-react-app

This worked for me 1.First uninstall create-react-app globally by this command:

npm uninstall -g create-react-app

If there you still have the previous installation please delete the folder called my app completely.(Make sure no program is using that folder including your terminal or cmd promt)

2.then in your project directory:

npm install create-react-app@latest

3.finally:

npx create-react-app my-app

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

I had a similar issue and running the command below fixed the error for me:

brew update && brew upgrade

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

The problem is that you compiled the code with java 13 (class file 57), and the java runtime is set to java 8 (class file 52).

Assuming you have the JRE 13 installed in your local system, you could change your runtime from 52 to 57. That you can do with the plugin Choose Runtime. To install it go to File/Settings/Plugins

enter image description here

Once installed go to Help/Find Action, type "runtime" and select the jre 13 from the dropdown menu.

enter image description here

Server Discovery And Monitoring engine is deprecated

Update

Mongoose 5.7.1 was release and seems to fix the issue, so setting up the useUnifiedTopology option work as expected.

mongoose.connect(mongoConnectionString, {useNewUrlParser: true, useUnifiedTopology: true});

Original answer

I was facing the same issue and decided to deep dive on Mongoose code: https://github.com/Automattic/mongoose/search?q=useUnifiedTopology&unscoped_q=useUnifiedTopology

Seems to be an option added on version 5.7 of Mongoose and not well documented yet. I could not even find it mentioned in the library history https://github.com/Automattic/mongoose/blob/master/History.md

According to a comment in the code:

  • @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to true to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine.

There is also an issue on the project GitHub about this error: https://github.com/Automattic/mongoose/issues/8156

In my case I don't use Mongoose in a replica set or sharded cluster and though the option should be false. But if false it complains the setting should be true. Once is true it still don't work, probably because my database does not run on a replica set or sharded cluster.

I've downgraded to 5.6.13 and my project is back working fine. So the only option I see for now is to downgrade it and wait for the fix to update for a newer version.

dotnet ef not found in .NET Core 3

I had the same problem. I resolved, uninstalling all de the versions in my pc and then reinstall dotnet.

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

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

I just want to add a non-obvious possibility not covered here. I am using @react-native-community/netinfo for detecting network changes, primarily network state. To test network-off state, the WIFI switch (on the emulator) needs to be switched off. This also effectively cuts off the bridge between the emulator and the debug environment. I had not re-enabled WIFI after my tests since i was away from the computer and promptly forgot about it when i got back.

There is a possibility that this could be the case for somebody else as well and worth checking before taking any other drastic steps.

Updating Anaconda fails: Environment Not Writable Error

On Windows, search for Anaconda PowerShell Prompt. Right click the program and select Run as administrator. In the command prompt, execute the following command:

conda update -n base -c defaults conda

Your Anaconda should now update without admin related errors.

Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`

Continuation of answer above.

Had the same "plugin error" as @MehrdadBabaki. I uninstalled web compiler, deleted the AppData WebCompiler folder mentioned above, then reopened VS2019 and reinstalled web compiler.

THEN I went to the WebCompiler folder again and did npm i autoprefixer@latest npm i caniuse-lite@latest and npm i caniuse-lite browserslist@latest

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

If you don't have cocoa pods installed you need to:

sudo gem install cocoapods

Then run:

cd /ios
pod install

delete the build folder in ios folder of your react native project

run:

react-native run-ios

if error persists:

  • delete build folder again
  • open the /ios folder in Xcode
  • navigate File -> Project Settings -> Build System -> change (Shared workspace settings and Per-User workspace settings): Build System -> Legacy Build System

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

i had similar issue just updated webdriver manager on mac use this in terminal to update webdriver manager-

 sudo webdriver-manager update

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

According to TF 1:1 Symbols Map, in TF 2.0 you should use tf.compat.v1.Session() instead of tf.Session()

https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0

To get TF 1.x like behaviour in TF 2.0 one can run

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

but then one cannot benefit of many improvements made in TF 2.0. For more details please refer to the migration guide https://www.tensorflow.org/guide/migrate

react hooks useEffect() cleanup for only componentWillUnmount?

instead of creating too many complicated functions and methods what I do is I create an event listener and automatically have mount and unmount done for me without having to worry about doing it manually. Here is an example.

//componentDidMount
useEffect( () => {

    window.addEventListener("load",  pageLoad);

    //component will unmount
    return () => {
       
        window.removeEventListener("load", pageLoad);
    }

 });

now that this part is done I just run anything I want from the pageLoad function like this.

const pageLoad = () =>{
console.log(I was mounted and unmounted automatically :D)}

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

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

for cordova developers having this issue

try to set

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

in confix.xml

How do I prevent Conda from activating the base environment by default?

This might be a bug of the recent anaconda. What works for me:

step1: vim /anaconda/bin/activate, it shows:

 #!/bin/sh                                                                                
 _CONDA_ROOT="/anaconda"
 # Copyright (C) 2012 Anaconda, Inc
 # SPDX-License-Identifier: BSD-3-Clause
 \. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
 conda activate "$@"

step2: comment out the last line: # conda activate "$@"

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

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

Looks like the NoCoffee Vision Simulator extension for Chrome will also cause this error. Just adding it as a prospective cause for people looking in their own instance.

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I suggest removing the below code from getMails

 .catch(error => { throw error})

In your main function you should put await and related code in Try block and also add one catch block where you failure code.


you function gmaiLHelper.getEmails should return a promise which has reject and resolve in it.

Now while calling and using await put that in try catch block(remove the .catch) as below.

router.get("/emailfetch", authCheck, async (req, res) => {
  //listing messages in users mailbox 
try{
  let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
}
catch (error) { 
 // your catch block code goes here
})

FlutterError: Unable to load asset

You should consider the indentation for assets

flutter:

  assets:
    - images/pizza1.png
    - images/pizza0.png

More details:

flutter:

[2 whitespaces or 1 tab]assets:
[4 whitespaces or 2 tabs]- images/pizza1.png
[4 whitespaces or 2 tabs]- images/pizza0.png

How to compare oldValues and newValues on React Hooks useEffect?

Going off the accepted answer, an alternative solution that doesn't require a custom hook:

const Component = ({ receiveAmount, sendAmount }) => {
  const prevAmount = useRef({ receiveAmount, sendAmount }).current;
  useEffect(() => {
    if (prevAmount.receiveAmount !== receiveAmount) {
     // process here
    }
    if (prevAmount.sendAmount !== sendAmount) {
     // process here
    }
    return () => { 
      prevAmount.receiveAmount = receiveAmount;
      prevAmount.sendAmount = sendAmount;
    };
  }, [receiveAmount, sendAmount]);
};

This assumes you actually need reference to the previous values for anything in the "process here" bits. Otherwise unless your conditionals are beyond a straight !== comparison, the simplest solution here would just be:

const Component = ({ receiveAmount, sendAmount }) => {
  useEffect(() => {
     // process here
  }, [receiveAmount]);

  useEffect(() => {
     // process here
  }, [sendAmount]);
};

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

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

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

Try this:

sudo apt-get install libpcap-dev libpq-dev

It has worked for me when I have installed these two.

See the link here for more information

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Make sure that both the chromedriver and google-chrome executable have execute permissions

sudo chmod -x "/usr/bin/chromedriver"

sudo chmod -x "/usr/bin/google-chrome"

Could not install packages due to an EnvironmentError: [Errno 13]

I have anaconda installed for Python 3. I also have Python2 in my mac.

python --version

gives me

Python 3.7.3

python2.7 --version

gives me

Python 2.7.10

I wanted to install pyspark package in python2, given that it was already installed in python3.

python2.7 -m pip install pyspark

gives me an error

Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pyspark' Consider using the --user option or check the permissions.

The below command solved it. Thank god I didn't have to do any config changes.

python2.7 -m pip install pyspark --user

Collecting pyspark Requirement already satisfied: py4j==0.10.7 in /Library/Python/2.7/site-packages (from pyspark) (0.10.7) Installing collected packages: pyspark Successfully installed pyspark-2.4.4 You are using pip version 18.1, however version 19.3.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command.

Flutter: RenderBox was not laid out

You can add some code like this

ListView.builder{
   shrinkWrap: true,
}

OpenCV !_src.empty() in function 'cvtColor' error

In my case it was a permission issue. I had to:

  • chmod a+wrx the image,

then it worked.

How to install OpenJDK 11 on Windows?

  1. Extract the zip file into a folder, e.g. C:\Program Files\Java\ and it will create a jdk-11 folder (where the bin folder is a direct sub-folder). You may need Administrator privileges to extract the zip file to this location.

  2. Set a PATH:

    • Select Control Panel and then System.
    • Click Advanced and then Environment Variables.
    • Add the location of the bin folder of the JDK installation to the PATH variable in System Variables.
    • The following is a typical value for the PATH variable: C:\WINDOWS\system32;C:\WINDOWS;"C:\Program Files\Java\jdk-11\bin"
  3. Set JAVA_HOME:

    • Under System Variables, click New.
    • Enter the variable name as JAVA_HOME.
    • Enter the variable value as the installation path of the JDK (without the bin sub-folder).
    • Click OK.
    • Click Apply Changes.
  4. Configure the JDK in your IDE (e.g. IntelliJ or Eclipse).

You are set.

To see if it worked, open up the Command Prompt and type java -version and see if it prints your newly installed JDK.

If you want to uninstall - just undo the above steps.

Note: You can also point JAVA_HOME to the folder of your JDK installations and then set the PATH variable to %JAVA_HOME%\bin. So when you want to change the JDK you change only the JAVA_HOME variable and leave PATH as it is.

Can't compile C program on a Mac after upgrade to Mojave

@JL Peyret is right!

if you macos 10.14.6 Mojave, Xcode 11.0+

then

cd /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs

sudo ln -s MacOSX.sdk/ MacOSX10.14.sdk

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

Had the same error but with a different scenario. I had my state as

        this.state = {
        date: new Date()
    }

so when I was asking it in my Class Component I had

p>Date = {this.state.date}</p>

Instead of

p>Date = {this.state.date.toLocaleDateString()}</p>

Xcode 10, Command CodeSign failed with a nonzero exit code

In my experience, the reason that caused this problem was I wrongly reset the Keychain Access to default, so I lost my development certificate.

How did I solve this?

  1. I cleaned my Apple Development Certificate from Keychain Access
  2. I cleaned my Apple Development private key from Keychain Access
  3. Then I got the new error : Revoke certificate Your account already has an Apple Development signing certificate for this machine, but its private key is not installed in your keychain. Xcode can create a new one after revoking your existing certificate.
  4. Go to Xcode Preference -> Accounts Tab -> Fine the team name under the Apple ID -> Double Click it -> Click the + button at the bottom left of box -> Select App Development
  5. In the team drop-down of the target, select "None"
  6. Re-select the correct development team
  7. Clean the project by shift+cmd+k
  8. Rebuild the project cmd+b

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

I had this problem running WSL 2

the solution was the command

 $ sudo dockerd

if after that you still have a problem with permission, run the command:

 $ sudo usermod -aG docker your-user

DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server

The use of the deprecated new Buffer() constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.

According to the deprecation warning new Buffer() should be replaced with one of:

  • Buffer.alloc()
  • Buffer.allocUnsafe() or
  • Buffer.from()

Another option in order to avoid this issue would be using the safe-buffer package instead.

You can also try (when using yarn..):

yarn global add yarn

as mentioned here: Link

Another suggestion from the comments (thx to gkiely): self-update

Note: self-update is not available. See policies for enforcing versions within a project

In order to update your version of Yarn, run

curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

Flutter - The method was called on null

You have a CryptoListPresenter _presenter but you are never initializing it. You should either be doing that when you declare it or in your initState() (or another appropriate but called-before-you-need-it method).

One thing I find that helps is that if I know a member is functionally 'final', to actually set it to final as that way the analyzer complains that it hasn't been initialized.

EDIT:

I see diegoveloper beat me to answering this, and that the OP asked a follow up.

@Jake - it's hard for us to tell without knowing exactly what CryptoListPresenter is, but depending on what exactly CryptoListPresenter actually is, generally you'd do final CryptoListPresenter _presenter = new CryptoListPresenter(...);, or

CryptoListPresenter _presenter;

@override
void initState() {
  _presenter = new CryptoListPresenter(...);
}

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

working example:

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_db_name?autoReconnect=true&useSSL=false", "root", "root");

call like this it will work.

How do I install opencv using pip?

Install opencv-python (which is an unofficial pre-built OpenCV package for Python) by issuing the following command:

pip install opencv-python

Waiting for another flutter command to release the startup lock

Restart your IDE first and then run the following command in project folder from terminal

killall -9 dart

It worked for me. Hope it will help some of the guys facing the same problem.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

It was fixed this kind of error after migrate to AndroidX

  • Go to Refactor ---> Migrate to AndroidX

Confirm password validation in Angular 6

In case you have more than just Password and Verify Password fields. Like this the Confirm password field will only highlights error when user write something on this field:

validators.ts

import { FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

export const EmailValidation = [Validators.required, Validators.email];
export const PasswordValidation = [
  Validators.required,
  Validators.minLength(6),
  Validators.maxLength(24),
];

export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value && control.dirty)
  }
}
export function RepeatPasswordValidator(group: FormGroup) {
  const password = group.controls.password.value;
  const passwordConfirmation = group.controls.passwordAgain.value;

  return password === passwordConfirmation ? null : { passwordsNotEqual: true }     
}

register.component.ts

import { FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import { EmailValidation, PasswordValidation, RepeatPasswordEStateMatcher, RepeatPasswordValidator } from 'validators';

...

form: any;
passwordsMatcher = new RepeatPasswordEStateMatcher;


constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group ( {
      email: new FormControl('', EmailValidation),
      password: new FormControl('', PasswordValidation),
      passwordAgain: new FormControl(''),
      acceptTerms: new FormControl('', [Validators.requiredTrue])
    }, { validator: RepeatPasswordValidator });
  }

...

register.component.html

<form [formGroup]="form" (ngSubmit)="submitAccount(form)">
    <div class="form-content">
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="email" placeholder="Email">
            <mat-error *ngIf="form.get('email').hasError('required')">
                E-mail is mandatory.
            </mat-error>
            <mat-error *ngIf="form.get('email').hasError('email')">
                Incorrect E-mail.
            </mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="password" placeholder="Password" type="password">
            <mat-hint class="ac-form-field-description">Between 6 and 24 characters.</mat-hint>
            <mat-error *ngIf="form.get('password').hasError('required')">
                Password is mandatory.
            </mat-error>
            <mat-error *ngIf="form.get('password').hasError('minlength')">
                Password with less than 6 characters.
            </mat-error>
            <mat-error *ngIf="form.get('password').hasError('maxlength')">
                Password with more than 24 characters.
            </mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="passwordAgain" placeholder="Confirm the password" type="password" [errorStateMatcher]="passwordsMatcher">
            <mat-error *ngIf="form.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-checkbox name="acceptTerms" formControlName="acceptTerms">I accept terms and conditions</mat-checkbox>
        </div>
    </div>
    <div class="form-bottom">
        <button mat-raised-button [disabled]="!form.valid">Create Account</button>
    </div>
</form>

i hope it helps!

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

MSDocs state this for your scenario:

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

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

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

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

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

Xcode couldn't find any provisioning profiles matching

You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

  1. Find the path from error log and open the file in explorer 2)select the file and right-click -> properties
  2. Then check the 'unblock' option and click on apply enter image description here

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

instead of using " + " operator

print( "Alireza" + 1980)

Use comma " , " operator

print( "Alireza" , 1980)

ADB.exe is obsolete and has serious performance problems

I followed the answer, but the magic final step was deleting the existing virtual environment and creating a new one.

FirebaseInstanceIdService is deprecated

Use FirebaseMessaging instead

 FirebaseMessaging.getInstance().getToken()
    .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
          if (!task.isSuccessful()) {
            Log.w(TAG, "Fetching FCM registration token failed", task.getException());
            return;
          }

          // Get new FCM registration token
          String token = task.getResult();

          // Log and toast
          String msg = getString(R.string.msg_token_fmt, token);
          Log.d(TAG, msg);
          Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

installation app blocked by play protect

Try to create a new key store and replace with old one, then rebuild a new signed APK.

Update: Note that if you're using a http connection with server ,you should use SSL.

Take a look at: https://developer.android.com/distribute/best-practices/develop/understand-play-policies

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

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

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

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

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

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


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

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Google Maps shows "For development purposes only"

As Victoria wrote, Google Maps is no longer free, but you can switch your map provider. You may be interested in OpenStreetMap, there is an easy way to use it on your site described here: https://handyman.dulare.com/switching-from-google-maps-to-openstreetmap/

Unfortunately, on the OpenStreetMap, there is no easy way to provide directions from one point to another, there is also no street view.

How to add image in Flutter

  1. Create images folder in root level of your project.

    enter image description here

    enter image description here

  2. Drop your image in this folder, it should look like

    enter image description here

  3. Go to your pubspec.yaml file, add assets header and pay close attention to all the spaces.

    flutter:
    
      uses-material-design: true
    
      # add this
      assets:
        - images/profile.jpg
    
  4. Tap on Packages get at the top right corner of the IDE.

    enter image description here

  5. Now you can use your image anywhere using

    Image.asset("images/profile.jpg")
    

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

If anyone is getting this error using Nginx, try adding the following to your server config:

server {
    listen 443 ssl;
    ...
}

The issue stems from Nginx serving an HTTP server to a client expecting HTTPS on whatever port you're listening on. When you specify ssl in the listen directive, you clear this up on the server side.

Angular 6: How to set response type as text while making http call

You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.

Instead you should set the option responseType to text:

addToCart(productId: number, quantity: number): Observable<any> {
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');

  return this.http.post(
    'http://localhost:8080/order/addtocart', 
    { dealerId: 13, createdBy: "-1", productId, quantity }, 
    { headers, responseType: 'text'}
  ).pipe(catchError(this.errorHandlerService.handleError));
}

On npm install: Unhandled rejection Error: EACCES: permission denied

If none of suggestions in answers worked out, try the following command: npm cache clear --force. It worked for me.

I found it at https://github.com/vuejs/vue-cli/issues/1809.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.

By default Elasticsearch's decision is based on the percentage of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.

The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.

For docs about the flood stage watermark see https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html.

The right solution depends on the context - for example a production environment vs a development environment.

Solution 1: free up disk space

Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:

$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Solution 2: change the flood stage watermark setting

Change the "cluster.routing.allocation.disk.watermark.flood_stage" setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from the docs:

PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.disk.watermark.low": "100gb",
    "cluster.routing.allocation.disk.watermark.high": "50gb",
    "cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
    "cluster.info.update.interval": "1m"
  }
}

Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.

Iterating through a list to render multiple widgets in Flutter?

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

you can do something like this:

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

After that call like this

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

enter image description here

destination path already exists and is not an empty directory

This error comes up when you try to clone a repository in a folder which still contains .git folder (Hidden folder).

If the earlier answers doesn't work then you can proceed with my answer. Hope it will solve your issue.

Open terminal & change the directory to the destination folder (where you want to clone).

Now type: ls -a

You may see a folder named .git.

You have to remove that folder by the following command: rm -rf .git

Now you are ready to clone your project.

what is an illegal reflective access

There is an Oracle article I found regarding Java 9 module system

By default, a type in a module is not accessible to other modules unless it’s a public type and you export its package. You expose only the packages you want to expose. With Java 9, this also applies to reflection.

As pointed out in https://stackoverflow.com/a/50251958/134894, the differences between the AccessibleObject#setAccessible for JDK8 and JDK9 are instructive. Specifically, JDK9 added

This method may be used by a caller in class C to enable access to a member of declaring class D if any of the following hold:

  • C and D are in the same module.
  • The member is public and D is public in a package that the module containing D exports to at least the module containing C.
  • The member is protected static, D is public in a package that the module containing D exports to at least the module containing C, and C is a subclass of D.
  • D is in a package that the module containing D opens to at least the module containing C. All packages in unnamed and open modules are open to all modules and so this method always succeeds when D is in an unnamed or open module.

which highlights the significance of modules and their exports (in Java 9)

Angular 5 Button Submit On Enter Key Press

In case anyone is wondering what input value

<input (keydown.enter)="search($event.target.value)" />

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Add the below line in your app.gradle file before depencencies block.

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-annotations:26.1.0'
    }
}

There's also screenshot below for a better understanding.

Configurations.all block

  1. the configurations.all block will only be helpful if you want your target sdk to be 26. If you can change it to 27 the error will be gone without adding the configuration block in app.gradle file.

  2. There is one more way if you would remove all the test implementation from app.gradle file it would resolve the error and in this also you dont need to add the configuration block nor you need to change the targetsdk version.

Hope that helps.

Axios handling errors

I tried using the try{}catch{} method but it did not work for me. However, when I switched to using .then(...).catch(...), the AxiosError is caught correctly that I can play around with. When I try the former when putting a breakpoint, it does not allow me to see the AxiosError and instead, says to me that the caught error is undefined, which is also what eventually gets displayed in the UI.

Not sure why this happens I find it very trivial. Either way due to this, I suggest using the conventional .then(...).catch(...) method mentioned above to avoid throwing undefined errors to the user.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

You should have added muted attribute inside your videoElement for your code work as expected. Look bellow ..

<video id="IPcamerastream" muted="muted" autoplay src="videoplayback%20(1).mp4" width="960" height="540"></video>

Don' t forget to add a valid video link as source

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

Here is what worked for me (Angular 7):

First import HttpClientModule in your app.module.ts if you didn't:

import { HttpClientModule } from '@angular/common/http';
...
imports: [
        HttpClientModule
    ],

Then change your service

@Injectable()
export class FooService {

to

@Injectable({
    providedIn: 'root'
})
export class FooService {

Hope it helps.

Edit:

providedIn

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:

'root' : The application-level injector in most apps.

'platform' : A special singleton platform injector shared by all applications on the page.

'any' : Provides a unique instance in every module (including lazy modules) that injects the token.

Be careful platform is available only since Angular 9 (https://blog.angular.io/version-9-of-angular-now-available-project-ivy-has-arrived-23c97b63cfa3)

Read more about Injectable here: https://angular.io/api/core/Injectable

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

The answer to this question has changed as Jest has evolved. Current answer (March 2019):

  1. You can override the timeout of any individual test by adding a third parameter to the it. I.e., it('runs slow', () => {...}, 9999)

  2. You can change the default using jest.setTimeout. To do this:

    // Configuration
    "setupFilesAfterEnv": [  // NOT setupFiles
        "./src/jest/defaultTimeout.js"
    ],
    

    and

    // File: src/jest/defaultTimeout.js
    /* Global jest */
    jest.setTimeout(1000)
    
  3. Like others have noted, and not directly related to this, done is not necessary with the async/await approach.

Error occurred during initialization of boot layer FindException: Module not found

The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src ? Default package. Keep only one class (in which you had written code) and delete others.

After that, run your program and it will definitely run without any error.

Default interface methods are only supported starting with Android N

In app-level gradle, you have to write these code:

android {
...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

They come from JavaVersion.java in Android.

An enumeration of Java versions.

Before 9: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html

After 9: http://openjdk.java.net/jeps/223

@canerkaseler

How to clear Flutter's Build cache?

You can run flutter clean.

But that's most likely a problem with your IDE or similar, as flutter run creates a brand new apk. And hot reload push only modifications.

Try running your app using the command line flutter run and then press r or R for respectively hot-reload and full-reload.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

This happened to me because I was using:

app.datasource.url=jdbc:mysql://localhost/test

When I replaced url by jdbc-url then it worked:

app.datasource.jdbc-url=jdbc:mysql://localhost/test

Returning data from Axios API

You can use Async - Await:

async function axiosTest() {
  const response = await axios.get(url);
  const data = await response.json();  
}

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".

Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."

My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.

As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.

How to remove the Flutter debug banner?

On your MaterialApp set debugShowCheckedModeBanner to false.

MaterialApp(
  debugShowCheckedModeBanner: false,
)

The debug banner will also automatically be removed on release build.

Could not find a version that satisfies the requirement tensorflow

Uninstalling Python and then reinstalling solved my issue and I was able to successfully install TensorFlow.

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

I found that running the npm install command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.

Specifically, I was trying to use ng2-completer

$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.

I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.

cd foo/foo_app
$ npm install ng2-completer --save

Failed linking file resources

I had the same problem but it occured in all my projects, I tried Invalidate Cache / Restart but even it doesn´t solved the problem.

At the end I realized that in my Gradle Settings, Offline Work was enabled.

Go to Build, Execution, Deployment > Gradle in Gradle Settings unchecked Offline Work.

enter image description here

It solved the the problem downloading some configuration files for my Android Studio.

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

sometimes you miss -e flag while specific multiple env vars inline

e.g. bad: docker run --name somecontainername -e ENV_VAR1=somevalue1 ENV_VAR2=somevalue2 -d -v "mypath:containerpath" <imagename e.g. postgres>

good: docker run --name somecontainername -e ENV_VAR1=somevalue1 -e ENV_VAR2=somevalue2 -d -v "mypath:containerpath" <imagename e.g. postgres>

PackagesNotFoundError: The following packages are not available from current channels:

If your base conda environment is active...

  • in which case "(base)" will most probably show at the start or your terminal command prompt.

... and pip is installed in your base environment ...

  • which it is: $ conda list | grep pip

... then install the not-found package simply by $ pip install <packagename>

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Old one but I would add my answer as per my findings:

var ancestralState = context.findAncestorStateOfType<ParentState>();
      ancestralState.setState(() {
        // here you can access public vars and update state.
        ...
      });

Assets file project.assets.json not found. Run a NuGet package restore

Select Tools > NuGet Package Manager > Package Manager Console

And then Run:

dotnet restore <project or solution name>

Google Colab: how to read data from my google drive?

There are many ways to read the files in your colab notebook(**.ipnb), a few are:

  1. Mounting your Google Drive in the runtime's virtual machine.here &, here
  2. Using google.colab.files.upload(). the easiest solution
  3. Using the native REST API;
  4. Using a wrapper around the API such as PyDrive

Method 1 and 2 worked for me, rest I wasn't able to figure out. If anyone could, as others tried in above post please write an elegant answer. thanks in advance.!

First method:

I wasn't able to mount my google drive, so I installed these libraries

# Install a Drive FUSE wrapper.
# https://github.com/astrada/google-drive-ocamlfuse

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

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

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

Once the installation & authorization process is finished, you first mount your drive.

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

After installation I was able to mount the google drive, everything in your google drive starts from /content/drive

!ls /content/drive/ML/../../../../path_to_your_folder/

Now you can simply read the file from path_to_your_folder folder into pandas using the above path.

import pandas as pd
df = pd.read_json('drive/ML/../../../../path_to_your_folder/file.json')
df.head(5)

you are suppose you use absolute path you received & not using /../..

Second method:

Which is convenient, if your file which you want to read it is present in the current working directory.

If you need to upload any files from your local file system, you could use below code, else just avoid it.!

from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

suppose you have below the folder hierarchy in your google drive:

/content/drive/ML/../../../../path_to_your_folder/

Then, you simply need below code to load into pandas.

import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))
df

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

I see you have all the settings right. You just need to end the local web server and start it again with

php artisan serve

Everytime you change your .env file, you need tor restart the server for the new options to take effect.

Or clear and cache your configuration with

php artisan config:cache

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

I couldn't resist - the other answers are undoubtedly true, but you really can't walk past the following code:

_x000D_
_x000D_
var a? = 1;_x000D_
var a = 2;_x000D_
var ?a = 3;_x000D_
if(a?==1 && a== 2 &&?a==3) {_x000D_
    console.log("Why hello there!")_x000D_
}
_x000D_
_x000D_
_x000D_

Note the weird spacing in the if statement (that I copied from your question). It is the half-width Hangul (that's Korean for those not familiar) which is an Unicode space character that is not interpreted by ECMA script as a space character - this means that it is a valid character for an identifier. Therefore there are three completely different variables, one with the Hangul after the a, one with it before and the last one with just a. Replacing the space with _ for readability, the same code would look like this:

_x000D_
_x000D_
var a_ = 1;_x000D_
var a = 2;_x000D_
var _a = 3;_x000D_
if(a_==1 && a== 2 &&_a==3) {_x000D_
    console.log("Why hello there!")_x000D_
}
_x000D_
_x000D_
_x000D_

Check out the validation on Mathias' variable name validator. If that weird spacing was actually included in their question, I feel sure that it's a hint for this kind of answer.

Don't do this. Seriously.

Edit: It has come to my attention that (although not allowed to start a variable) the Zero-width joiner and Zero-width non-joiner characters are also permitted in variable names - see Obfuscating JavaScript with zero-width characters - pros and cons?.

This would look like the following:

_x000D_
_x000D_
var a= 1;_x000D_
var a?= 2; //one zero-width character_x000D_
var a??= 3; //two zero-width characters (or you can use the other one)_x000D_
if(a==1&&a?==2&&a??==3) {_x000D_
    console.log("Why hello there!")_x000D_
}
_x000D_
_x000D_
_x000D_

Stylesheet not loaded because of MIME-type

The solution from this thread solved my problem:

Not sure if this will help anyone, but if you are using angular-cli, I fixed this by removing the CSS reference from my index.html and adding it to the angular-cli.json file under the "style" portion. After restarting my webserver I no longer had that issue.

Read response headers from API response - Angular 5 + TypeScript

As Hrishikesh Kale has explained we need to pass the Access-Control-Expose-Headers.

Here how we can do it in the WebAPI/MVC environment:

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

Another way is we can add code as below in the webApiconfig.cs file.

config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

**We can add custom headers in the web.config file as below. *

<httpProtocol>
   <customHeaders>
      <add name="Access-Control-Expose-Headers" value="TestHeaderToExpose" />
   </customHeaders>
</httpProtocol>

we can create an attribute and decore the method with the attribute.

Happy Coding !!

Force flex item to span full row width

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

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

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

#range, #text {
  flex: 1;
}

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

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

'mat-form-field' is not a known element - Angular 5 & Material2

When using the 'mat-form-field' MatInputModule needs to be imported also

import { 
    MatToolbarModule, 
    MatButtonModule,
    MatSidenavModule,
    MatIconModule,
    MatListModule ,
    MatStepperModule,
    MatInputModule
} from '@angular/material';

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

Another possible way to do this:

In system tray, right click on docker icon, then click on Switch to Linux containers.

(Docker for Windows, Community Edition, version 18.03.1)

How to start up spring-boot application via command line?

Run Spring Boot app using Maven

You can also use Maven plugin to run your Spring Boot app. Use the below example to run your Spring Boot app with Maven plugin:

mvn spring-boot:run

Run Spring Boot App with Gradle

And if you use Gradle you can run the Spring Boot app with the following command:

gradle bootRun

React Native version mismatch

This is not a fix, but in my case, I had multiple RN apps installed on my device and I was unknowingly attempting to 'Reload` from within the wrong application. (I'm developing two apps simultaneously at the moment) So make sure you're in the correct application!

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

I had this problem and it took me nearly 2 days to resolve...

I had moved my SDK location, due to the system drive being full, and it seems that someone, somewhere at Android Studio central has hard-coded the path to the HaxM driver installer. As my HamX driver was out of date, the emulator wouldn't start.

Solution: navigate to [your sdk location]\extras\intel\Hardware_Accelerated_Execution_Manager and run the intelhaxm-android.exe installer to update yourself to the latest driver.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:

public class TargetClassController : ControllerBase
{
    private readonly IConfiguration _config;

    public TargetClassController(IConfiguration config)
    {
        _config = config;
    }

    [HttpGet("{id:int}")]
    public async Task<ActionResult<DTOResponse>> Get(int id)
    {
        var config = _config["YourKeySection:key"];
    }
}

Exception : AAPT2 error: check logs for details

Check the latest edited XML file. It is the main Villian I had once such error, I then checked the last xml file, ther was a line like android:layout_marginTop="." I changed it to android:layout_marginTop="16dp". That fixed the bug!

startForeground fail after upgrade to Android 8.1

Alternative answer: if it's a Huawei device and you have implemented requirements needed for Oreo 8 Android and there are still issues only with Huawei devices than it's only device issue, you can read https://dontkillmyapp.com/huawei

Class has been compiled by a more recent version of the Java Environment

This is just a version mismatch. You have compiled your code using java version 9 and your current JRE is version 8. Try upgrading your JRE to 9.

49 = Java 5
50 = Java 6
51 = Java 7
52 = Java 8
53 = Java 9
54 = Java 10
55 = Java 11
56 = Java 12
57 = Java 13
58 = Java 14

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

this work for me. add configurations.all in app/build.gradle

android {
    configurations.all {
        resolutionStrategy.force 'com.android.support:support-annotations:27.1.1'
    }
}

Where to declare variable in react js

Assuming that onMove is an event handler, it is likely that its context is something other than the instance of MyContainer, i.e. this points to something different.

You can manually bind the context of the function during the construction of the instance via Function.bind:

class MyContainer extends Component {
  constructor(props) {
    super(props);

    this.onMove = this.onMove.bind(this);

    this.test = "this is a test";
  }

  onMove() {
    console.log(this.test);
  }
}

Also, test !== testVariable.

NullInjectorError: No provider for AngularFirestore

import angularFirebaseStore 

in app.module.ts and set it as a provider like service

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

In my case, I pressed Deny unfortunately during first time installation. So I was getting INSTALL_FAILED_USER_RESTRICTED.

You can get modify this permission for app under permissions.

Settings->Permissions->Install via USB->{Your App}

You should have enabled below options too.

Settings->Additional Settings->Privacy->Unknown Sources

Settings->Additional Settings->Developer Options->Install via USB

No provider for HttpClient

I had same issue. After browsing and struggling with issue found the below solution

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

imports: [
  HttpModule,
  HttpClientModule
]

Import HttpModule and HttpClientModule in app.module.ts and add into the imports like mentioned above.

How to reload current page in ReactJS?

Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount() in a React class.

For you edit, you may want to try something like this:

class Component extends React.Component {
  constructor(props) {
    super(props);
    this.onAddBucket = this.onAddBucket.bind(this);
  }
  componentWillMount() {
    this.setState({
      buckets: {},
    })
  }
  componentDidMount() {
    this.onAddBucket();
  }
  onAddBucket() {
    let self = this;
    let getToken = localStorage.getItem('myToken');
    var apiBaseUrl = "...";
    let input = {
      "name" :  this.state.fields["bucket_name"]
    }
    axios.defaults.headers.common['Authorization'] = getToken;
    axios.post(apiBaseUrl+'...',input)
    .then(function (response) {
      if (response.data.status == 200) {
        this.setState({
          buckets: this.state.buckets.concat(response.data.buckets),
        });
      } else {
        alert(response.data.message);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  }
  render() {
    return (
      {this.state.bucket}
    );
  }
}

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

Is not as old as other questions, but I just struggled with this in an Ionic-Laravel app, and nothing works from here (and other posts), so I installed https://github.com/barryvdh/laravel-cors complement in Laravel and started and it works pretty well.

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

If you use pip version of tensorflow, it means it's already compiled and you are just installing it. Basically you install tensorflow-gpu, but when you download it from repository and trying to build, you should build it with CPU AVX support. If you ignore it, you will get the warning every time when you run on cpu.

How to work with progress indicator in flutter?

Step 1: Create Dialog

   showAlertDialog(BuildContext context){
      AlertDialog alert=AlertDialog(
        content: new Row(
            children: [
               CircularProgressIndicator(),
               Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
            ],),
      );
      showDialog(barrierDismissible: false,
        context:context,
        builder:(BuildContext context){
          return alert;
        },
      );
    }

Step 2:Call it

showAlertDialog(context);
await firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
Navigator.pop(context);

Example With Dialog and login form

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class DynamicLayout extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new MyWidget();
    }
  }
showAlertDialog(BuildContext context){
  AlertDialog alert=AlertDialog(
    content: new Row(
        children: [
           CircularProgressIndicator(),
           Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
        ],),
  );
  showDialog(barrierDismissible: false,
    context:context,
    builder:(BuildContext context){
      return alert;
    },
  );
}

  class MyWidget extends State<DynamicLayout>{
  Color color = Colors.indigoAccent;
  String title='app';
  GlobalKey<FormState> globalKey=GlobalKey<FormState>();
  String email,password;
  login() async{
   var currentState= globalKey.currentState;
   if(currentState.validate()){
        currentState.save();
        FirebaseAuth firebaseAuth=FirebaseAuth.instance;
        try {
          showAlertDialog(context);
          AuthResult authResult=await firebaseAuth.signInWithEmailAndPassword(
              email: email, password: password);
          FirebaseUser user=authResult.user;
          Navigator.pop(context);
        }catch(e){
          print(e);
        }
   }else{

   }
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar:AppBar(
        title: Text("$title"),
        ) ,
          body: Container(child: Form(
            key: globalKey,
            child: Container(
              padding: EdgeInsets.all(10),
              child: Column(children: <Widget>[
              TextFormField(decoration: InputDecoration(icon: Icon(Icons.email),labelText: 'Email'),
              // ignore: missing_return
              validator:(val){
                if(val.isEmpty)
                  return 'Please Enter Your Email';
              },
              onSaved:(val){
                email=val;
              },
              ),
                TextFormField(decoration: InputDecoration(icon: Icon(Icons.lock),labelText: 'Password'),
             obscureText: true,
                  // ignore: missing_return
                  validator:(val){
                    if(val.isEmpty)
                      return 'Please Enter Your Password';
                  },
                  onSaved:(val){
                    password=val;
                  },
              ),
                RaisedButton(color: Colors.lightBlue,textColor: Colors.white,child: Text('Login'),
                  onPressed:login),
            ],)
              ,),)
         ),
    );
  }
}

enter image description here

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

Open Gemfile.lock, which is to be found in the root of your app folder. Scroll to the end of the file and see the bundler version used. Then you make sure you install the bundler version used:

gem install bundler -v x.xx.xx

Or - delete the Gemfile.lock and bundle if you have higher bundler version installed.

The choice is yours, my friend.

Getting error "The package appears to be corrupt" while installing apk file

As I got this case at my own and the answers here didn't help me, my situation was because of I downgraded the targetSdkVersion in gradle app module file from 24 to 22 for some reason, and apparently the apk doesn't accept another one with downgraded targetSdkVersion to be installed over it.

So, once I changed it back to 24 the error disappeared and app installed correctly.

mat-form-field must contain a MatFormFieldControl

MatRadioModule won't work inside MatFormField. The docs say

This error occurs when you have not added a form field control to your form field. If your form field contains a native or element, make sure you've added the matInput directive to it and have imported MatInputModule. Other components that can act as a form field control include < mat-select>, < mat-chip-list>, and any custom form field controls you've created.

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

If you have control over your server, you can use PHP:

<?PHP
header('Access-Control-Allow-Origin: *');
?>

How can I use async/await at the top level?

The actual solution to this problem is to approach it differently.

Probably your goal is some sort of initialization which typically happens at the top level of an application.

The solution is to ensure that there is only ever one single JavaScript statement at the top level of your application. If you have only one statement at the top of your application, then you are free to use async/await at every other point everwhere (subject of course to normal syntax rules)

Put another way, wrap your entire top level in a function so that it is no longer the top level and that solves the question of how to run async/await at the top level of an application - you don't.

This is what the top level of your application should look like:

import {application} from './server'

application();

cmake error 'the source does not appear to contain CMakeLists.txt'

You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there.

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I had the same problem and the issue was that my child component had an @input named formControl.

So I just needed to change from:

<my-component [formControl]="formControl"><my-component/>

to:

<my-component [control]="control"><my-component/>

ts:

@Input()
control:FormControl;

Angular HttpClient "Http failure during parsing"

if you have options

return this.http.post(`${this.endpoint}/account/login`,payload, { ...options, responseType: 'text' })

TypeScript error TS1005: ';' expected (II)

  • Remove C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0 directory.

  • Now run :

    npm install -g typescript 
    

    this will install the latest version and then re-try.

Pipenv: Command Not Found

This is fixed for me to:

sudo -H pip install -U pipenv

Anaconda Navigator won't launch (windows 10)

I tried the following @janny loco's answer first and then reset anaconda to get it to work.

Step 1:

activate root
conda update -n root conda
conda update --all

Step 2:

anaconda-navigator --reset

After running the update commands in step 1 and not seeing any success, I reset anaconda by running the command above based on what I found here.

I am not sure if it was the combination of updating conda and reseting the navigator or just one of the two. So, please try accordingly.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

I realised I had less than 100 MBs of free space on my disc. Freeing up disk space solved the issue for me!

Unable to merge dex

There might be a duplicated dependency (possibly nested in another dependency). Use "gradlew app:dependencies" in the command-line to verify all of your dependencies.

After removing duplicates, the problem was solved for me.

How to use log4net in Asp.net core 2.0

Still looking for a solution? I got mine from this link .

All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".

 var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
 XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

Yes, you have to add:

  1. Microsoft.Extensions.Logging.Log4Net.AspNetCore using NuGet.
  2. A text file with the name of log4net.config and change the property(Copy to Output Directory) of the file to "Copy if Newer" or "Copy always".

You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How to test the type of a thrown exception in Jest

Further to Peter Danis' post, I just wanted to emphasize the part of his solution involving "[passing] a function into expect(function).toThrow(blank or type of error)".

In Jest, when you test for a case where an error should be thrown, within your expect() wrapping of the function under testing, you need to provide one additional arrow function wrapping layer in order for it to work. I.e.

Wrong (but most people's logical approach):

expect(functionUnderTesting();).toThrow(ErrorTypeOrErrorMessage);

Right:

expect(() => { functionUnderTesting(); }).toThrow(ErrorTypeOrErrorMessage);

It's very strange, but it should make the testing run successfully.

Catching errors in Angular HttpClient

The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor (hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.

To do this you will need to generate a stack in an extended HttpClient, so its not advisable to do this in a production environment.

/**
 * Extended HttpClient that generates a stack trace on error when not in a production build.
 */
@Injectable()
export class TraceHttpClient extends HttpClient {
  constructor(handler: HttpHandler) {
    super(handler);
  }

  request(...args: [any]): Observable<any> {
    const stack = environment.production ? null : Error().stack;
    return super.request(...args).pipe(
      catchError((err) => {
        // tslint:disable-next-line:no-console
        if (stack) console.error('HTTP Client error stack\n', stack);
        return throwError(err);
      })
    );
  }
}

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

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

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

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

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

As suggested above, this could possibly be an issue with your browser extensions. Disable all of your extensions including Adblock, and then try again as the code is loading fine in my browser right now (Google Chrome - latest) so it's probably an issue on your end. Also, have you tried a different browser like shudders IE if you have it? Adblock is known to conflict with domain names with track and market in them as a blanket rule. Try using private browsing mode or safe mode.

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.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

Fix urlpatterns in urls.py file

For example, my app name is "simulator",

My URL pattern for login and logout looks like

urlpatterns = [
    ...
    ...
    url(r'^login/$', simulator.views.login_view, name="login"),
    url(r'^logout/$', simulator.views.logout_view, name="logout"),
    ...
    ...

]

Angular4 - No value accessor for form control

For me it was due to "multiple" attribute on select input control as Angular has different ValueAccessor for this type of control.

const countryControl = new FormControl();

And inside template use like this

    <select multiple name="countries" [formControl]="countryControl">
      <option *ngFor="let country of countries" [ngValue]="country">
       {{ country.name }}
      </option>
    </select>

More details ref Official Docs

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Error: fix the version conflict (google-services plugin)

Same error gets thrown when

apply plugin: 'com.google.gms.google-services'

is not added to bottom of the module build.gradle file.

NotificationCompat.Builder deprecated in Android O

Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();  

Right code will be :

Notification.Builder notification=new Notification.Builder(this)

with dependency 26.0.1 and new updated dependencies such as 28.0.0.

Some users use this code in the form of this :

Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.

So Logic is that which Method you will declare or initilize then the same methode on Right side will be use for Allocation. if in Leftside of = you will use some method then the same method will be use in right side of = for Allocation with new.

Try this code...It will sure work

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

I had a free developer account. For me, I fixed it by paying the $99.00 developer fee to Apple.

Then went back into the Xcode PRODUCT menu and selected CLEAN BUILD FOLDER. After that this error went away.

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

This is definitely a bug.Laravel offers predefined code in routes/api.php

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

which is unabled to be processed by:

php artisan route:cache

This definitely should be fixed by Laravel team.(check the link),

simply if you want to fix it you should replace routes\api.php code with some thing like :

Route::middleware('auth:api')->get('/user', 'UserController@AuthRouteAPI');

and in UserController put this method:

 public function AuthRouteAPI(Request $request){
    return $request->user();
 }

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

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

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

How can I dismiss the on screen keyboard?

As of Flutter v1.7.8+hotfix.2, the way to go is:

FocusScope.of(context).unfocus()

Comment on PR about that:

Now that #31909 (be75fb3) has landed, you should use FocusScope.of(context).unfocus() instead of FocusScope.of(context).requestFocus(FocusNode()), since FocusNodes are ChangeNotifiers, and should be disposed properly.

-> DO NOT use ?r?e?q?u?e?s?t?F?o?c?u?s?(?F?o?c?u?s?N?o?d?e?(?)? anymore.

 F?o?c?u?s?S?c?o?p?e?.?o?f?(?c?o?n?t?e?x?t?)?.?r?e?q?u?e?s?t?F?o?c?u?s?(?F?o?c?u?s?N?o?d?e?(?)?)?;?

Python error message io.UnsupportedOperation: not readable

There are few modes to open file (read, write etc..)

If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.

more modes:

  • r. Opens a file for reading only.
  • rb. Opens a file for reading only in binary format.
  • r+ Opens a file for both reading and writing.
  • rb+ Opens a file for both reading and writing in binary format.
  • w. Opens a file for writing only.
  • you can find more modes in here

Specifying ssh key in ansible playbook file

If you run your playbook with ansible-playbook -vvv you'll see the actual command being run, so you can check whether the key is actually being included in the ssh command (and you might discover that the problem was the wrong username rather than the missing key).

I agree with Brian's comment above (and zigam's edit) that the vars section is too late. I also tested including the key in the on-the-fly definition of the host like this

# fails
- name: Add all instance public IPs to host group
  add_host: hostname={{ item.public_ip }} groups=ec2hosts ansible_ssh_private_key_file=~/.aws/dev_staging.pem
  loop: "{{ ec2.instances }}"

but that fails too.

So this is not an answer. Just some debugging help and things not to try.

Set value to an entire column of a pandas dataframe

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

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

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

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

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

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

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Worked by lowering the spring boot starter parent to 1.5.13

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.13.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

Kubernetes Pod fails with CrashLoopBackOff

Pod is not started due to problem coming after initialization of POD.

Check and use command to get docker container of pod

docker ps -a | grep private-reg

Output will be information of docker container with id.

See docker logs:

docker logs -f <container id>

How to run shell script file using nodejs?

You can execute any shell command using the shelljs module

 const shell = require('shelljs')

 shell.exec('./path_to_your_file')

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

There is a very simple class TextOneLine from package assorted_layout_widgets.

Just put your text in that class.

For example:

Row(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: <Widget>[
      SvgPicture.asset(
        loadAsset(SVG_CALL_GREEN),
        width: 23,
        height: 23,
        fit: BoxFit.fill,
      ),
      SizedBox(width: 16),
      Expanded(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextOneLine(
              widget.firstText,
              style: findTextStyle(widget.firstTextStyle),
              textAlign: TextAlign.left,
            ),
            SizedBox(height: 4),
            TextOneLine(
              widget.secondText,
              style: findTextStyle(widget.secondTextStyle),
              textAlign: TextAlign.left,
            ),
          ],
        ),
      ),
      Icon(
        Icons.arrow_forward_ios,
        color: Styles.iOSArrowRight,
      )
    ],
  )

Global Angular CLI version greater than local version

this should solve the issue:

ng update @angular/cli @angular/core

'router-outlet' is not a known element

Thank you Hero Editor example, where I found the correct definition:

When I generate app routing module:

ng generate module app-routing --flat --module=app

and update the app-routing.ts file to add:

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})

Here are the full example:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent }   from './dashboard/dashboard.component';
import { HeroesComponent }      from './heroes/heroes.component';
import { HeroDetailComponent }  from './hero-detail/hero-detail.component';

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

and add AppRoutingModule into app.module.ts imports:

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [...],
  bootstrap: [AppComponent]
})

Angular 2 'component' is not a known element

The problem in my case was missing component declaration in the module, but even after adding the declaration the error persisted. I had stop the server and rebuild the entire project in VS Code for the error to go away.

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

Try to remove /usr/local/lib/node_modules/npm and reinstall node again. This should work.

On MacOS with Homebrew:

sudo rm -rf /usr/local/lib/node_modules/npm
brew reinstall node

ssl.SSLError: tlsv1 alert protocol version

For python2 users on MacOS (python@2 formula won't be found), as brew stopped support of python2 you need to use such command! But don't forget to unlink old python if it was pre-installed.

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/86a44a0a552c673a05f11018459c9f5faae3becc/Formula/[email protected]

If you've done some mistake, simply brew uninstall python@2 old way, and try again.

thank you hyperknot (answer here)

Angular, Http GET with parameter?

For Angular 9+ You can add headers and params directly without the key-value notion:

const headers = new HttpHeaders().append('header', 'value');
const params = new HttpParams().append('param', 'value');
this.http.get('url', {headers, params}); 

VS 2017 Metadata file '.dll could not be found

This issue happens when you renamed your solution and the .net framework cannot find the old solution.

To resolve this, you need to find and replace the old name of solution and all dependencies on it with the new name. If you need to browse the physical file through file explorer do so.

The files that are normally affected are AssemblyInfo.cs, .sln an Properties > Application > Assembly name and Default namespace. Make sure to update them with the new name.

Open the file explorer, if the folder with the old name still exists, you need to delete it. Then clean and build the solution until the error is gone. (If needed clean and build the project one by one especially the affected project.)

How to send authorization header with axios

Install the cors middleware. We were trying to solve it with our own code, but all attempts failed miserably.

This made it work:

cors = require('cors')
app.use(cors());

Original link

How to view kafka message

Old version includes kafka-simple-consumer-shell.sh (https://kafka.apache.org/downloads#1.1.1) which is convenient since we do not need cltr+c to exit.

For example

kafka-simple-consumer-shell.sh --broker-list $BROKERIP:$BROKERPORT --topic $TOPIC1 --property print.key=true --property key.separator=":"  --no-wait-at-logend

RestClientException: Could not extract response. no suitable HttpMessageConverter found

While the accepted answer solved the OP's original problem, most people finding this question through a Google search are likely having an entirely different problem which just happens to throw the same no suitable HttpMessageConverter found exception.

What happens under the covers is that MappingJackson2HttpMessageConverter swallows any exceptions that occur in its canRead() method, which is supposed to auto-detect whether the payload is suitable for json decoding. The exception is replaced by a simple boolean return that basically communicates sorry, I don't know how to decode this message to the higher level APIs (RestClient). Only after all other converters' canRead() methods return false, the no suitable HttpMessageConverter found exception is thrown by the higher-level API, totally obscuring the true problem.

For people who have not found the root cause (like you and me, but not the OP), the way to troubleshoot this problem is to place a debugger breakpoint on onMappingJackson2HttpMessageConverter.canRead(), then enable a general breakpoint on any exception, and hit Continue. The next exception is the true root cause.

My specific error happened to be that one of the beans referenced an interface that was missing the proper deserialization annotations.

UPDATE FROM THE FUTURE

This has proven to be such a recurring issue across so many of my projects, that I've developed a more proactive solution. Whenever I have a need to process JSON exclusively (no XML or other formats), I now replace my RestTemplate bean with an instance of the following:

public class JsonRestTemplate extends RestTemplate {

    public JsonRestTemplate(
            ClientHttpRequestFactory clientHttpRequestFactory) {
        super(clientHttpRequestFactory);

        // Force a sensible JSON mapper.
        // Customize as needed for your project's definition of "sensible":
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule())
                .configure(
                        SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter() {

            public boolean canRead(java.lang.Class<?> clazz,
                    org.springframework.http.MediaType mediaType) {
                return true;
            }    
            public boolean canRead(java.lang.reflect.Type type,
                    java.lang.Class<?> contextClass,
                    org.springframework.http.MediaType mediaType) {
                return true;
            }
            protected boolean canRead(
                    org.springframework.http.MediaType mediaType) {
                return true;
            }
        };

        jsonMessageConverter.setObjectMapper(objectMapper);
        messageConverters.add(jsonMessageConverter);
        super.setMessageConverters(messageConverters);

    }
}

This customization makes the RestClient incapable of understanding anything other than JSON. The upside is that any error messages that may occur will be much more explicit about what's wrong.

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

Database access on main thread locking the UI is the error, like Dale said.

--EDIT 2--

Since many people may come across this answer... The best option nowadays, generally speaking, is Kotlin Coroutines. Room now supports it directly (currently in beta). https://kotlinlang.org/docs/reference/coroutines-overview.html https://developer.android.com/jetpack/androidx/releases/room#2.1.0-beta01

--EDIT 1--

For people wondering... You have other options. I recommend taking a look into the new ViewModel and LiveData components. LiveData works great with Room. https://developer.android.com/topic/libraries/architecture/livedata.html

Another option is the RxJava/RxAndroid. More powerful but more complex than LiveData. https://github.com/ReactiveX/RxJava

--Original answer--

Create a static nested class (to prevent memory leak) in your Activity extending AsyncTask.

private static class AgentAsyncTask extends AsyncTask<Void, Void, Integer> {

    //Prevent leak
    private WeakReference<Activity> weakActivity;
    private String email;
    private String phone;
    private String license;

    public AgentAsyncTask(Activity activity, String email, String phone, String license) {
        weakActivity = new WeakReference<>(activity);
        this.email = email;
        this.phone = phone;
        this.license = license;
    }

    @Override
    protected Integer doInBackground(Void... params) {
        AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao();
        return agentDao.agentsCount(email, phone, license);
    }

    @Override
    protected void onPostExecute(Integer agentsCount) {
        Activity activity = weakActivity.get();
        if(activity == null) {
            return;
        }

        if (agentsCount > 0) {
            //2: If it already exists then prompt user
            Toast.makeText(activity, "Agent already exists!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(activity, "Agent does not exist! Hurray :)", Toast.LENGTH_LONG).show();
            activity.onBackPressed();
        }
    }
}

Or you can create a final class on its own file.

Then execute it in the signUpAction(View view) method:

new AgentAsyncTask(this, email, phone, license).execute();

In some cases you might also want to hold a reference to the AgentAsyncTask in your activity so you can cancel it when the Activity is destroyed. But you would have to interrupt any transactions yourself.

Also, your question about the Google's test example... They state in that web page:

The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don't require creating an activity, they should be faster to execute than your UI tests.

No Activity, no UI.

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

You could use the CSS calc parameter to calculate the height dynamically like so:

_x000D_
_x000D_
.dynamic-height {_x000D_
   color: #000;_x000D_
   font-size: 12px;_x000D_
   margin-top: calc(100% - 10px);_x000D_
   text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you fix the "element not interactable" exception?

For the html code:

test.html

<button class="dismiss"  onclick="alert('hello')">
    <string for="exit">Dismiss</string>
</button>

the below python code worked for me. You can just try it.

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()

The create-react-app imports restriction outside of src directory

The package react-app-rewired can be used to remove the plugin. This way you do not have to eject.

Follow the steps on the npm package page (install the package and flip the calls in the package.json file) and use a config-overrides.js file similar to this one:

const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');

module.exports = function override(config, env) {
    config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin));

    return config;
};

This will remove the ModuleScopePlugin from the used WebPack plugins, but leave the rest as it was and removes the necessity to eject.

Android Studio 3.0 Flavor Dimension Issue

I have used flavorDimensions for my application in build.gradle (Module: app)

flavorDimensions "tier"

productFlavors {
    production {
        flavorDimensions "tier"
        //manifestPlaceholders = [appName: APP_NAME]
        //signingConfig signingConfigs.config
    }
    staging {
        flavorDimensions "tier"
        //manifestPlaceholders = [appName: APP_NAME_STAGING]
        //applicationIdSuffix ".staging"
        //versionNameSuffix "-staging"
        //signingConfig signingConfigs.config
    }
}

Check this link for more info

// Specifies two flavor dimensions.
flavorDimensions "tier", "minApi"

productFlavors {
     free {
            // Assigns this product flavor to the "tier" flavor dimension. Specifying
            // this property is optional if you are using only one dimension.
            dimension "tier"
            ...
     }

     paid {
            dimension "tier"
            ...
     }

     minApi23 {
            dimension "minApi"
            ...
     }

     minApi18 {
            dimension "minApi"
            ...
     }
}

Jersey stopped working with InjectionManagerFactory not found

Add this dependency:

<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.28</version>
</dependency>

cf. https://stackoverflow.com/a/44536542/1070215

Make sure not to mix your Jersey dependency versions. This answer says version "2.28", but use whatever version your other Jersey dependency versions are.

Cannot connect to the Docker daemon on macOS

i simply had to run spotlight search and execute the Docker application under /Applications folder which brew cask install created. Once this was run it asked to complete installation. I was then able to run docker ps

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

Finally I imported my Gradle project. These are the steps:

  1. I switched from local Gradle distrib to Intellij Idea Gradle Wrapper (gradle-2.14).
  2. I pointed system variable JAVA_HOME to JDK 8 (it was 7th previously) as I had figured out by experiments that Gradle Wrapper could process the project with JDK 8 only.
  3. I deleted previously manually created file gradle.properties (with org.gradle.java.homevariable) in windows user .gradle directory as, I guessed, it didn't bring any additional value to Gradle.

Disable Button in Angular 2

Change ng-disabled="!contractTypeValid" to [disabled]="!contractTypeValid"

If '<selector>' is an Angular component, then verify that it is part of this module

Check which module the parent component is being declared in...

If your parent component is defined in the shared module, so must your child module.

The parent component could be declared in a shared module and not the module that is logical based on the file directory structure / naming, even the Angular CLI added it into the wrong module in my case.

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

This error occurs when the client URL and server URL don't match, including the port number. In this case you need to enable your service for CORS which is cross origin resource sharing.

If you are hosting a Spring REST service then you can find it in the blog post CORS support in Spring Framework.

If you are hosting a service using a Node.js server then

  1. Stop the Node.js server.
  2. npm install cors --save
  3. Add following lines to your server.js

    var cors = require('cors')
    
    app.use(cors()) // Use this after the variable declaration
    

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Check if value exists in enum in TypeScript

If you want this to work with string enums, you need to use Object.values(ENUM).includes(ENUM.value) because string enums are not reverse mapped, according to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:

Enum Vehicle {
    Car = 'car',
    Bike = 'bike',
    Truck = 'truck'
}

becomes:

{
    Car: 'car',
    Bike: 'bike',
    Truck: 'truck'
}

So you just need to do:

if (Object.values(Vehicle).includes('car')) {
    // Do stuff here
}

If you get an error for: Property 'values' does not exist on type 'ObjectConstructor', then you are not targeting ES2017. You can either use this tsconfig.json config:

"compilerOptions": {
    "lib": ["es2017"]
}

Or you can just do an any cast:

if ((<any>Object).values(Vehicle).includes('car')) {
    // Do stuff here
}

angular 4: *ngIf with multiple conditions

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

How to include css files in Vue 2

You can import the css file on App.vue, inside the style tag.

<style>
  @import './assets/styles/yourstyles.css';
</style>

Also, make sure you have the right loaders installed, if you need any.

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

I had an identical problem with the same error message but the solution with removal of unused docker networks didn't help me. I've deleted all non-default docker networks (and all images and containers as well) but it didn't help - docker still was not able to create a new network.

The cause of the problem was in network interfaces that were left after OpenVpn installation. (It was installed on the host previously.) I found them by running ifconfig command:

...
tun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
      inet addr:10.8.0.2  P-t-P:10.8.0.2  Mask:255.255.255.0
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:75 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:100 
      RX bytes:84304 (84.3 KB)  TX bytes:0 (0.0 B)

tun1  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
      inet addr:10.8.0.2  P-t-P:10.8.0.2  Mask:255.255.255.0
      UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
      RX packets:200496 errors:0 dropped:0 overruns:0 frame:0
      TX packets:148828 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:100 
      RX bytes:211583838 (211.5 MB)  TX bytes:9568906 (9.5 MB)
...

I've found that I can remove them with a couple of commands:

ip link delete tun0
ip link delete tun1

After this the problem has disappeared.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

I just experienced this issue while using the Windows Subsystem for Linux (WSL2), so I will also share this solution.

My objective was to render the output from webpack both at wsl:3000 and localhost:3000, thereby creating an alternate local endpoint.

As you might expect, this initially caused the "Invalid Host header" error to arise. Nothing seemed to help until I added the devServer config option shown below.


module.exports = {
  //...
  devServer: {
    proxy: [
      {
        context: ['http://wsl:3000'],
        target: 'http://localhost:3000',
      },
    ],
  },
}

This fixed the "bug" without introducing any security risks.

Reference: webpack DevServer docs

Visual Studio Code pylint: Unable to import 'protorpc'

For your case, add the following code to vscode's settings.json.

"python.linting.pylintArgs": [
    "--init-hook='import sys; sys.path.append(\"~/google-cloud-sdk/platform/google_appengine/lib\")'"
]

For the other who got troubles with pip packages, you can go with

"python.linting.pylintArgs": [
    "--init-hook='import sys; sys.path.append(\"/usr/local/lib/python3.7/dist-packages\")'"
]

You should replace python3.7 above with your python version.

How can I manually set an Angular form field as invalid?

I was trying to call setErrors() inside a ngModelChange handler in a template form. It did not work until I waited one tick with setTimeout():

template:

<input type="password" [(ngModel)]="user.password" class="form-control" 
 id="password" name="password" required (ngModelChange)="checkPasswords()">

<input type="password" [(ngModel)]="pwConfirm" class="form-control"
 id="pwConfirm" name="pwConfirm" required (ngModelChange)="checkPasswords()"
 #pwConfirmModel="ngModel">

<div [hidden]="pwConfirmModel.valid || pwConfirmModel.pristine" class="alert-danger">
   Passwords do not match
</div>

component:

@ViewChild('pwConfirmModel') pwConfirmModel: NgModel;

checkPasswords() {
  if (this.pwConfirm.length >= this.user.password.length &&
      this.pwConfirm !== this.user.password) {
    console.log('passwords do not match');
    // setErrors() must be called after change detection runs
    setTimeout(() => this.pwConfirmModel.control.setErrors({'nomatch': true}) );
  } else {
    // to clear the error, we don't have to wait
    this.pwConfirmModel.control.setErrors(null);
  }
}

Gotchas like this are making me prefer reactive forms.

Error: the entity type requires a primary key

Make sure you have the following condition:

  1. Use [key] if your primary key name is not Id or ID.
  2. Use the public keyword.
  3. Primary key should have getter and setter.

Example:

public class MyEntity {
   [key]
   public Guid Id {get; set;}
}

How to Install Font Awesome in Laravel Mix

I have recently written a blog about it for the Laravel5.6. Link to blog is https://www.samundra.com.np/integrating-font-awesome-with-laravel-5.x-using-webpack/1574

The steps are similar to above description. But in my case, I had to do extra steps like configuring the webfonts path to font-awesome in "public" directory. Setting the resource root in Laravel mix etc. You can find the details in the blog.

I am leaving the link here so it helps people for whom the mentioned solutions don't work.

How to scroll to an element?

Here is my solution:

I put an invisible div inside main div and made its position absolute. Then set the top value to -(header height) and set the ref on this div. Or you can just react that div with children method.

It's working great so far!

<div className="position-relative">
        <div style={{position:"absolute", top:"-80px", opacity:0, pointerEvents:'none'}}  ref={ref}></div>

Async/Await Class Constructor

If you can avoid extend, you can avoid classes all together and use function composition as constructors. You can use the variables in the scope instead of class members:

async function buildA(...) {
  const data = await fetch(...);
  return {
    getData: function() {
      return data;
    }
  }
}

and simple use it as

const a = await buildA(...);

If you're using typescript or flow, you can even enforce the interface of the constructors

Interface A {
  getData: object;
}

async function buildA0(...): Promise<A> { ... }
async function buildA1(...): Promise<A> { ... }
...

Is Visual Studio Community a 30 day trial?

I had this problem. Signing in or pressing the "Check for an updated license" link did not work for me. My solution was to restart Visual Studio, try again (sign in and check for license). Restart Visual Studio, try again. I had to do this several times and then it worked! (I also tried pressing the "File" menu that is available for a short period of time before the annoying request window appears again.) Maybe you just don't get connected to the server or the server itself doesn't update its database fast enough.

Error message "Linter pylint is not installed"

I also had this problem. If you also have Visual Studio installed with the Python extension, the system will want to use Studio's version of Python. Set the Environment Path to the version in Studio's Shared folder. For me, that was:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\

After that, run

python -m pip install pylint

from a command prompt with Administrator rights.

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

--
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
---

@NgModule({
  declarations: [   --   ],
  imports: [BrowserAnimationsModule],
  providers: [],
  bootstrap: []
})

How to use Redirect in the new react-router-dom of Reactjs

To navigate to another component you can use this.props.history.push('/main');

import React, { Component, Fragment } from 'react'

class Example extends Component {

  redirect() {
    this.props.history.push('/main')
  }

  render() {
    return (
      <Fragment>
        {this.redirect()}
      </Fragment>
    );
   }
 }

 export default Example

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

As I have noticed this error occurs under two circumstances,

  1. If you have used train_test_split() to split your data, you have to make sure that you reset the index of the data (specially when taken using a pandas series object): y_train, y_test indices should be resetted. The problem is when you try to use one of the scores from sklearn.metrics such as; precision_score, this will try to match the shuffled indices of the y_test that you got from train_test_split().

so use, either np.array(y_test) for y_true in scores or y_test.reset_index(drop=True)

  1. Then again you can still have this error if your predicted 'True Positives' is 0, which is used for precision, recall and f1_scores. You can visualize this using a confusion_matrix. If the classification is multilabel and you set param: average='weighted'/micro/macro you will get an answer as long as the diagonal line in the matrix is not 0

Hope this helps.

Vertical Text Direction

rotation, like you did, is the way to go - but note that not all browsers support that. if you wan't to get a cross-browser solution, you'll have to generate pictures for that.

Name does not exist in the current context

In case someone being a beginner who tried all of the above and still didn't manage to get the project to work. Check your namespace. In an instance where you copy code from one project to another and you forget to change the namespace of the project then it will also give you this error.

Hope it helps someone.

What is the default value for Guid?

To extend answers above, you cannot use Guid default value with Guid.Empty as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid) or new Guid() instead.

Displaying the Indian currency symbol on a website

It's possible with simple HTML entity code.

_x000D_
_x000D_
.ex{_x000D_
color:green;_x000D_
font-size:20px;_x000D_
}
_x000D_
Example 1 : <span class="ex">&#x20b9;1200/-</span><br>_x000D_
Example 2 : <span class="ex">&#8377;3545/-</span><br>_x000D_
Example 3 : <span class="ex">&#2352;134/-</span> *Is not the exact Rupee symbol
_x000D_
_x000D_
_x000D_

Correct way to synchronize ArrayList in java

Yes it is the correct way, but the synchronised block is required if you want all the removals together to be safe - unless the queue is empty no removals allowed. My guess is that you just want safe queue and dequeue operations, so you can remove the synchronised block.

However, there are far advanced concurrent queues in Java such as ConcurrentLinkedQueue

RegEx for Javascript to allow only alphanumeric

Instead of checking for a valid alphanumeric string, you can achieve this indirectly by checking the string for any invalid characters. Do so by checking for anything that matches the complement of the valid alphanumeric string.

/[^a-z\d]/i    

Here is an example:

var alphanumeric = "someStringHere";
var myRegEx  = /[^a-z\d]/i;
var isValid = !(myRegEx.test(alphanumeric));

Notice the logical not operator at isValid, since I'm testing whether the string is false, not whether it's valid.

How can I filter a date of a DateTimeField in Django?

Here are the results I got with ipython's timeit function:

from datetime import date
today = date.today()

timeit[Model.objects.filter(date_created__year=today.year, date_created__month=today.month, date_created__day=today.day)]
1000 loops, best of 3: 652 us per loop

timeit[Model.objects.filter(date_created__gte=today)]
1000 loops, best of 3: 631 us per loop

timeit[Model.objects.filter(date_created__startswith=today)]
1000 loops, best of 3: 541 us per loop

timeit[Model.objects.filter(date_created__contains=today)]
1000 loops, best of 3: 536 us per loop

contains seems to be faster.

Angular 2: 404 error occur when I refresh through the browser

If you're running Angular 2 through ASP.NET Core 1 in Visual Studio 2015, you might find this solution from Jürgen Gutsch helpful. He describes it in a blog post. It was the best solution for me. Place the C# code provided below in your Startup.cs public void Configure() just before app.UseStaticFiles();

app.Use( async ( context, next ) => {
    await next();

    if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
        context.Request.Path = "/index.html";
        await next();
    }
});

Hiding and Showing TabPages in tabControl

There are at least two ways to code a solution in software... Thanks for posting answers. Just wanted to update this with another version. A TabPage array is used to shadow the Tab Control. During the Load event, the TabPages in the TabControl are copied to the shadow array. Later, this shadow array is used as the source to copy the TabPages into the TabControl...and in the desired presentation order.

    Private tabControl1tabPageShadow() As TabPage = Nothing

    Private Sub Form2_DailyReportPackageViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
        LoadTabPageShadow()
    End Sub


    Private Sub LoadTabPageShadow()
        ReDim tabControl1tabPageShadow(TabControl1.TabPages.Count - 1)
        For Each tabPage In TabControl1.TabPages
            tabControl1tabPageShadow(tabPage.TabIndex) = tabPage
        Next
    End Sub

    Private Sub ViewAllReports(sender As Object, e As EventArgs) Handles Button8.Click
        TabControl1.TabPages.Clear()
        For Each tabPage In tabControl1tabPageShadow
            TabControl1.TabPages.Add(tabPage)
        Next
    End Sub


    Private Sub ViewOperationsReports(sender As Object, e As EventArgs) Handles Button10.Click
        TabControl1.TabPages.Clear()

        For tabCount As Integer = 0 To 9
            For Each tabPage In tabControl1tabPageShadow
                Select Case tabPage.Text
                    Case "Overview"
                        If tabCount = 0 Then TabControl1.TabPages.Add(tabPage)
                    Case "Production Days Under 110%"
                        If tabCount = 1 Then TabControl1.TabPages.Add(tabPage)
                    Case "Screening Status"
                        If tabCount = 2 Then TabControl1.TabPages.Add(tabPage)
                    Case "Rework Status"
                        If tabCount = 3 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary by Machine"
                        If tabCount = 4 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Set Ups"
                        If tabCount = 5 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Run Times"
                        If tabCount = 6 Then TabControl1.TabPages.Add(tabPage)
                    Case "Primary Set Ups"
                        If tabCount = 7 Then TabControl1.TabPages.Add(tabPage)
                    Case "Variance"
                        If tabCount = 8 Then TabControl1.TabPages.Add(tabPage)
                    Case "Schedule Changes"
                        If tabCount = 9 Then TabControl1.TabPages.Add(tabPage)
                End Select
            Next
        Next


Rails ActiveRecord date between

there are several ways. You can use this method:

start = @selected_date.beginning_of_day
end = @selected_date.end_of_day
@comments = Comment.where("DATE(created_at) BETWEEN ? AND ?", start, end)

Or this:

@comments = Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

How do I run a Python program?

I have tried many of the commands listed above, however none worked, even after setting my path to include the directory where I installed Python.

The command py -3 file.py always works for me, and if I want to run Python 2 code, as long as Python 2 is in my path, just changing the command to py -2 file.py works perfectly.

I am using Windows, so I'm not too sure if this command will work on Linux, or Mac, but it's worth a try.

Accessing the index in 'for' loops?

Here's what you get when you're accessing index in for loops:

for i in enumerate(items): print(i)

items = [8, 23, 45, 12, 78]

for i in enumerate(items):
    print("index/value", i)

Result:

# index/value (0, 8)
# index/value (1, 23)
# index/value (2, 45)
# index/value (3, 12)
# index/value (4, 78)

for i, val in enumerate(items): print(i, val)

items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i, "for value", val)

Result:

# index 0 for value 8
# index 1 for value 23
# index 2 for value 45
# index 3 for value 12
# index 4 for value 78

for i, val in enumerate(items): print(i)

items = [8, 23, 45, 12, 78]

for i, val in enumerate(items):
    print("index", i)

Result:

# index 0
# index 1
# index 2
# index 3
# index 4

Regular expression to match a line that doesn't contain a word

If you want the regex test to only fail if the entire string matches, the following will work:

^(?!hede$).*

e.g. -- If you want to allow all values except "foo" (i.e. "foofoo", "barfoo", and "foobar" will pass, but "foo" will fail), use: ^(?!foo$).*

Of course, if you're checking for exact equality, a better general solution in this case is to check for string equality, i.e.

myStr !== 'foo'

You could even put the negation outside the test if you need any regex features (here, case insensitivity and range matching):

!/^[a-f]oo$/i.test(myStr)

The regex solution at the top of this answer may be helpful, however, in situations where a positive regex test is required (perhaps by an API).

PowerShell: Comparing dates

I wanted to show how powerful it can be aside from just checking "-lt".

Example: I used it to calculate time differences take from Windows event view Application log:

Get the difference between the two date times:

PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))

Object created:

PS> $Obj


Days              : 0
Hours             : 0
Minutes           : 31
Seconds           : 0
Milliseconds      : 0
Ticks             : 18600000000
TotalDays         : 0.0215277777777778
TotalHours        : 0.516666666666667
TotalMinutes      : 31
TotalSeconds      : 1860
TotalMilliseconds : 1860000

Access an item directly:

PS> $Obj.Minutes
31

How to change the color of an image on hover

An alternative solution would be to use the new CSS mask image functionality which works in everything apart from IE (still not supported in IE11). This would be more versatile and maintainable than some of the other solutions suggested here. You could also more generally use SVG. e.g.

item { mask: url('/mask-image.png'); }

There is an example of using a mask image here:

http://codepen.io/zerostyle/pen/tHimv

and lots of examples here:

http://codepen.io/yoksel/full/fsdbu/

What is a tracking branch?

The ProGit book has a very good explanation:

Tracking Branches

Checking out a local branch from a remote branch automatically creates what is called a tracking branch. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push, Git automatically knows which server and branch to push to. Also, running git pull while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch.

When you clone a repository, it generally automatically creates a master branch that tracks origin/master. That’s why git push and git pull work out of the box with no other arguments. However, you can set up other tracking branches if you wish — ones that don’t track branches on origin and don’t track the master branch. The simple case is the example you just saw, running git checkout -b [branch] [remotename]/[branch]. If you have Git version 1.6.2 or later, you can also use the --track shorthand:

$ git checkout --track origin/serverfix
Branch serverfix set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "serverfix"

To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:

$ git checkout -b sf origin/serverfix
Branch sf set up to track remote branch refs/remotes/origin/serverfix.
Switched to a new branch "sf"

Now, your local branch sf will automatically push to and pull from origin/serverfix.

BONUS: extra git status info

With a tracking branch, git status will tell you whether how far behind your tracking branch you are - useful to remind you that you haven't pushed your changes yet! It looks like this:

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

or

$ git status
On branch dev
Your branch and 'origin/dev' have diverged,
and have 3 and 1 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

Sorting table rows according to table header column using javascript or jquery

I found @naota's solution useful, and extended it to use dates as well

//taken from StackOverflow:
//https://stackoverflow.com/questions/3880615/how-can-i-determine-whether-a-given-string-represents-a-date
function isDate(val) {
    var d = new Date(val);
    return !isNaN(d.valueOf());
}

var getVal = function(elm, n){
  var v = $(elm).children('td').eq(n).text().toUpperCase();
  if($.isNumeric(v)){
    v = parseFloat(v,10);
    return v;
  }
  if (isDate(v)) {
    v = new Date(v);
    return v;
  }
  return v;
}

Hive External Table Skip First Row

skip.header.line.count will skip the header line.

However, if you have some external tool accessing accessing the table, it will still see that actual data without skipping those lines

Is there a .NET/C# wrapper for SQLite?

sqlite-net is an open source, minimal library to allow .NET and Mono applications to store data in SQLite 3 databases. More information at the wiki page.

It is written in C# and is meant to be simply compiled in with your projects. It was first designed to work with MonoTouch on the iPhone, but has grown up to work on all the platforms (Mono for Android, .NET, Silverlight, WP7, WinRT, Azure, etc.).

It is available as a Nuget package, where it is the 2nd most popular SQLite package with over 60,000 downloads as of 2014.

sqlite-net was designed as a quick and convenient database layer. Its design follows from these goals:

  • Very easy to integrate with existing projects and with MonoTouch projects.
  • Thin wrapper over SQLite and should be fast and efficient. (The library should not be the performance bottleneck of your queries.)
  • Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.
  • Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)
  • 0 dependencies aside from a compiled form of the sqlite2 library.

Non-goals include:

  • Not an ADO.NET implementation. This is not a full SQLite driver. If you need that, use System.Data.SQLite.

Can constructors be async?

if you make constructor asynchronous, after creating an object, you may fall into problems like null values instead of instance objects. For instance;

MyClass instance = new MyClass();
instance.Foo(); // null exception here

That's why they don't allow this i guess.

Gradle - Could not find or load main class

I resolved it by adding below code to my application.

// enter code here this is error I was getting when I run build.gradle. main class name has not been configured and it could not be resolved

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

Ruby replace string with captured regex pattern

def get_code(str)
  str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

Check if an object exists

the boolean value of an empty QuerySet is also False, so you could also just do...

...
if not user_object:
   do insert or whatever etc.

Remove Rows From Data Frame where a Row matches a String

I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --

df <- df [(!(df$A=="no") & !(df$A=="unknown")),]

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Oracle client and networking components were not found

1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to

 F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;

change your drive and folder depending on your requirement...

Easy way to write contents of a Java InputStream to an OutputStream

I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.

byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}

Corrupted Access .accdb file: "Unrecognized Database Format"

Sometimes it might depend on whether you are using code to access the database or not. If you are using "DriverJet" in your code instead of "DriverACE" (or an older version of the DAO library) such a problem is highly probable to happen. You just need to replace "DriverJet" with "DriverACE" and test.

Make an Android button change background on click through XML

I used this to change the background for my button

            button.setBackground(getResources().getDrawable(R.drawable.primary_button));

"button" is the variable holding my Button, and the image am setting in the background is primary_button

How to properly override clone method?

Do you absolutely have to use clone? Most people agree that Java's clone is broken.

Josh Bloch on Design - Copy Constructor versus Cloning

If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. [...] It's a shame that Cloneable is broken, but it happens.

You may read more discussion on the topic in his book Effective Java 2nd Edition, Item 11: Override clone judiciously. He recommends instead to use a copy constructor or copy factory.

He went on to write pages of pages on how, if you feel you must, you should implement clone. But he closed with this:

Is all this complexities really necessary? Rarely. If you extend a class that implements Cloneable, you have little choice but to implement a well-behaved clone method. Otherwise, you are better off providing alternative means of object copying, or simply not providing the capability.

The emphasis was his, not mine.


Since you made it clear that you have little choice but to implement clone, here's what you can do in this case: make sure that MyObject extends java.lang.Object implements java.lang.Cloneable. If that's the case, then you can guarantee that you will NEVER catch a CloneNotSupportedException. Throwing AssertionError as some have suggested seems reasonable, but you can also add a comment that explains why the catch block will never be entered in this particular case.


Alternatively, as others have also suggested, you can perhaps implement clone without calling super.clone.

How to convert an object to a byte array in C#

I found another way to convert an object to a byte[], here is my solution:

IEnumerable en = (IEnumerable) myObject;
byte[] myBytes = en.OfType<byte>().ToArray();

Regards

Amazon S3 exception: "The specified key does not exist"

Note that this may happen even if the file path is correct due to s3's eventual consistency model. Basically, there may be some latency in being able to read an object after it's written. See this documentation for more information.

Executable directory where application is running from?

Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
P = New Uri(P).LocalPath

Change DataGrid cell colour based on values

This may be of help to you. It isn't the stock WPF datagrid however.

I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.

Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.

Example

Viewmodel.cs

namespace ViewModel
{
    [POCOViewModel]
    public class Table2DViewModel
    {
        public ITable2DView Table2DView { get; set; }

        public DataTable ItemsTable { get; set; }


        public Table2DViewModel()
        {
        }

        public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
        {
            Table2DView = table2DView;   
            CreateTable();
        }

        private void CreateTable()
        {
            var dt = new DataTable();
            var xAxisStrings = new string[]{"X1","X2","X3"};
            var yAxisStrings = new string[]{"Y1","Y2","Y3"};

            //TODO determine your min, max number for your colours
            var minValue = 0;
            var maxValue = 100;
            Table2DView.SetColorFormatter(minValue,maxValue, null);

            //Add the columns
            dt.Columns.Add(" ", typeof(string));
            foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

            //Add all the values
            double z = 0;
            for (var y = 0; y < yAxisStrings.Length; y++)
            {
                var dr = dt.NewRow();
                dr[" "] = yAxisStrings[y];
                for (var x = 0; x < xAxisStrings.Length; x++)
                {
                    //TODO put your actual values here!
                    dr[xAxisStrings[x]] = z++; //Add a random values
                }
                dt.Rows.Add(dr);
            }
            ItemsTable = dt;
        }


        public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
        {
            var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
            return factory(mainViewModel, table2DView);
        }
    }

}

IView.cs

namespace Interfaces
    {
        public interface ITable2DView
        {
            void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
        }
    }

View.xaml.cs

namespace View
{
    public partial class Table2DView : ITable2DView
    {
        public Table2DView()
        {
            InitializeComponent();
        }

        static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
        {
            ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
            ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
            ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
        };

        public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
        {
            if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
            ConditionBehavior.MinValue = minValue;
            ConditionBehavior.MaxValue = maxValue;
            ConditionBehavior.ColorScaleFormat = colorScaleFormat;
        }
    }
}

DynamicConditionBehavior.cs

namespace Behaviors
{
    public class DynamicConditionBehavior : Behavior<GridControl>
    {
        GridControl Grid => AssociatedObject;

        protected override void OnAttached()
        {
            base.OnAttached();
            Grid.ItemsSourceChanged += OnItemsSourceChanged;
        }

        protected override void OnDetaching()
        {
            Grid.ItemsSourceChanged -= OnItemsSourceChanged;
            base.OnDetaching();
        }

        public ColorScaleFormat ColorScaleFormat { get; set;}
        public float MinValue { get; set; }
        public float MaxValue { get; set; }

        private void OnItemsSourceChanged(object sender, EventArgs e)
        {
            var view = Grid.View as TableView;

            if (view == null) return;

            view.FormatConditions.Clear();

            foreach (var col in Grid.Columns)
            {
                view.FormatConditions.Add(new ColorScaleFormatCondition
                {
                    MinValue = MinValue,
                    MaxValue = MaxValue,
                    FieldName = col.FieldName,
                    Format = ColorScaleFormat,
                });
            }

        }
    }
}

View.xaml

<UserControl x:Class="View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm" 
             xmlns:ViewModels="clr-namespace:ViewModel"
             xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
             xmlns:behaviors="clr-namespace:Behaviors"
             xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
             DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

    <UserControl.Resources>
        <Style TargetType="{x:Type dxg:GridColumn}">
            <Setter Property="Width" Value="50"/>
            <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
        </Style>

        <Style TargetType="{x:Type dxg:HeaderItemsControl}">
            <Setter Property="FontWeight" Value="DemiBold"/>
        </Style>
    </UserControl.Resources>

        <!--<dxmvvm:Interaction.Behaviors>
            <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
        </dxmvvm:Interaction.Behaviors>-->
        <dxg:GridControl ItemsSource="{Binding ItemsTable}"
                     AutoGenerateColumns="AddNew"
                     EnableSmartColumnsGeneration="True">

        <dxmvvm:Interaction.Behaviors >
            <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
            </dxmvvm:Interaction.Behaviors>
            <dxg:GridControl.View>
                <dxg:TableView ShowGroupPanel="False"
                           AllowPerPixelScrolling="True"/>
            </dxg:GridControl.View>
        </dxg:GridControl>
  </UserControl>

How to add comments into a Xaml file in WPF?

Found a nice solution by Laurent Bugnion, it can look something like this:

<UserControl xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:comment="Tag to add comments"
             mc:Ignorable="d comment" d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Button Width="100"
                comment:Width="example comment on Width, will be ignored......">
        </Button>
    </Grid>
</UserControl>

Here's the link: http://blog.galasoft.ch/posts/2010/02/quick-tip-commenting-out-properties-in-xaml/

A commenter on the link provided extra characters for the ignore prefix in lieu of highlighting:

mc:Ignorable=”ØignoreØ”

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

Step 1:
1.Open the Preferences, by clicking File > Settings (on Mac, Android Studio > Preferences).
2.In the left pane, click Build, Execution, Deployment >> Gradle.
3.Uncheck/disable the Offline work checkbox.
4.Click Apply or OK.

Step 2:
downgrade the gradle-wrapper.properties content which you can access this 
file directory by clicking on CTRL + SHFT +R KEY 
e.g from
    distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

to 
    distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-all.zip

or to any lower version like /gradle-3.9-all.zip or /gradle-3.8-all.zip

Remove all whitespace in a string

An alternative is to use regular expressions and match these strange white-space characters too. Here are some examples:

Remove ALL spaces in a string, even between words:

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the BEGINNING of a string:

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)

Remove spaces in the END of a string:

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)

Remove spaces both in the BEGINNING and in the END of a string:

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)

Remove ONLY DUPLICATE spaces:

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))

(All examples work in both Python 2 and Python 3)

How to run JUnit tests with Gradle?

If you set up your project with the default gradle package structure, i.e.:

src/main/java
src/main/resources
src/test/java
src/test/resources

then you won't need to modify sourceSets to run your tests. Gradle will figure out that your test classes and resources are in src/test. You can then run as Oliver says above. One thing to note: Be careful when setting property files and running your test classes with both gradle and you IDE. I use Eclipse, and when running JUnit from it, Eclipse chooses one classpath (the bin directory) whereas gradle chooses another (the build directory). This can lead to confusion if you edit a resource file, and don't see your change reflected at test runtime.

Merging two images with PHP

Merger two image png and jpg/png [Image Masking]

//URL or Local path
$src_url = '1.png';
$dest_url = '2.jpg';
$src = imagecreatefrompng($src_url);
$dest1 = imagecreatefromjpeg($dest_url);

//if you want to make same size
list($width, $height) = getimagesize($dest_url);
list($newWidth, $newHeight) = getimagesize($src_url);
$dest = imagecreatetruecolor($newWidth, $newHeight);

imagecopyresampled($dest, $dest1, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

list($src_w, $src_h) = getimagesize($src_url);

//merger with same size
$this->imagecopymerge_alpha($dest, $src, 0, 0, 0, 0, $src_w, $src_h, 100);

//show output on browser
header('Content-Type: image/png');
imagejpeg($dest);

imagecopymerge_alpha

function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
    {
        $cut = imagecreatetruecolor($src_w, $src_h);
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

Extract a single (unsigned) integer from a string

other way(unicode string even):

$res = array();
$str = 'test 1234 555 2.7 string ..... 2.2 3.3';
$str = preg_replace("/[^0-9\.]/", " ", $str);
$str = trim(preg_replace('/\s+/u', ' ', $str));
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++) {
    if (is_numeric($arr[$i])) {
        $res[] = $arr[$i];
    }
}
print_r($res); //Array ( [0] => 1234 [1] => 555 [2] => 2.7 [3] => 2.2 [4] => 3.3 ) 

Array inside a JavaScript Object?

In regards to multiple arrays in an object. For instance, you want to record modules for different courses

var course = {
    InfoTech:["Information Systems","Internet Programming","Software Eng"],
    BusComm:["Commercial Law","Accounting","Financial Mng"],
    Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);

Difference between left join and right join in SQL Server

Your two statements are equivalent.

Most people only use LEFT JOIN since it seems more intuitive, and it's universal syntax - I don't think all RDBMS support RIGHT JOIN.

'was not declared in this scope' error

Here's a simplified example based on of your problem:

if (test) 
{//begin scope 1
    int y = 1; 
}//end scope 1
else 
{//begin scope 2
    int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if, and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y;
if (test) 
{
    y = 1; 
}
else 
{
    y = 2;
}
int x = y;

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

Validating email addresses using jQuery and regex

Native method:

$("#myform").validate({
 // options...
});

$.validator.methods.email = function( value, element ) {
  return this.optional( element ) || /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}/.test( value );
}

Source: https://jqueryvalidation.org/jQuery.validator.methods/

Dependency injection with Jersey 2.0

First just to answer a comment in the accepts answer.

"What does bind do? What if I have an interface and an implementation?"

It simply reads bind( implementation ).to( contract ). You can alternative chain .in( scope ). Default scope of PerLookup. So if you want a singleton, you can

bind( implementation ).to( contract ).in( Singleton.class );

There's also a RequestScoped available

Also, instead of bind(Class).to(Class), you can also bind(Instance).to(Class), which will be automatically be a singleton.


Adding to the accepted answer

For those trying to figure out how to register your AbstractBinder implementation in your web.xml (i.e. you're not using a ResourceConfig), it seems the binder won't be discovered through package scanning, i.e.

<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
    <param-name>jersey.config.server.provider.packages</param-name>
    <param-value>
        your.packages.to.scan
    </param-value>
</init-param>

Or this either

<init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>
        com.foo.YourBinderImpl
    </param-value>
</init-param>

To get it to work, I had to implement a Feature:

import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;

@Provider
public class Hk2Feature implements Feature {

    @Override
    public boolean configure(FeatureContext context) {
        context.register(new AppBinder());
        return true;
    }
}

The @Provider annotation should allow the Feature to be picked up by the package scanning. Or without package scanning, you can explicitly register the Feature in the web.xml

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            com.foo.Hk2Feature
        </param-value>
    </init-param>
    ...
    <load-on-startup>1</load-on-startup>
</servlet>

See Also:

and for general information from the Jersey documentation


UPDATE

Factories

Aside from the basic binding in the accepted answer, you also have factories, where you can have more complex creation logic, and also have access to request context information. For example

public class MyServiceFactory implements Factory<MyService> {
    @Context
    private HttpHeaders headers;

    @Override
    public MyService provide() {
        return new MyService(headers.getHeaderString("X-Header"));
    }

    @Override
    public void dispose(MyService service) { /* noop */ }
}

register(new AbstractBinder() {
    @Override
    public void configure() {
        bindFactory(MyServiceFactory.class).to(MyService.class)
                .in(RequestScoped.class);
    }
});

Then you can inject MyService into your resource class.

Make a VStack fill the width of the screen in SwiftUI

This is a useful bit of code:

extension View {
    func expandable () -> some View {
        ZStack {
            Color.clear
            self
        }
    }
}

Compare the results with and without the .expandable() modifier:

Text("hello")
    .background(Color.blue)

-

Text("hello")
    .expandable()
    .background(Color.blue)

enter image description here

Getting return value from stored procedure in C#

There are multiple problems here:

  1. It is not possible. You are trying to return a varchar. Stored procedure return values can only be integer expressions. See official RETURN documentation: https://msdn.microsoft.com/en-us/library/ms174998.aspx.
  2. Your sqlcomm was never executed. You have to call sqlcomm.ExecuteNonQuery(); in order to execute your command.

Here is a solution using OUTPUT parameters. This was tested with:

  • Windows Server 2012
  • .NET v4.0.30319
  • C# 4.0
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Validate]
    @a varchar(50),
    @b varchar(50) OUTPUT
AS
BEGIN
    DECLARE @b AS varchar(50) = (SELECT Password FROM dbo.tblUser WHERE Login = @a)
    SELECT @b;
END
SqlConnection SqlConn = ...
var sqlcomm = new SqlCommand("Validate", SqlConn);

string returnValue = string.Empty;

try
{
    SqlConn.Open();
    sqlcomm.CommandType = CommandType.StoredProcedure;

    SqlParameter param = new SqlParameter("@a", SqlDbType.VarChar);
    param.Direction = ParameterDirection.Input;
    param.Value = Username;
    sqlcomm.Parameters.Add(param);

    SqlParameter output = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
    ouput.Direction = ParameterDirection.Output;

    sqlcomm.ExecuteNonQuery(); // This line was missing

    returnValue = output.Value.ToString();

    // ... the rest of code

} catch (SqlException ex) {
    throw ex;
}

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

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

plugin version Plugin version

Required Gradle version is here

Required gradle version

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

if you have the android studio version 4.0.1 android studio version

then your top level gradle file must be like this

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

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

and the gradle version should be

gradle version must be like this

and your app gradle look like this

app gradle file

How to make a div with no content have a width?

Use CSS to add a zero-width-space to your div. The content of the div will take no room but will force the div to display

.test1::before{
   content: "\200B";
}

Fastest way to set all values of an array?

   /**
     * Assigns the specified char value to each element of the specified array
     * of chars.
     *
     * @param a the array to be filled
     * @param val the value to be stored in all elements of the array
     */
    public static void fill(char[] a, char val) {
        for (int i = 0, len = a.length; i < len; i++)
            a[i] = val;
    }

That's the way Arrays.fill does it.

(I suppose you could drop into JNI and use memset.)

how to compare two elements in jquery

Random AirCoded example of testing "set equality" in jQuery:

$.fn.isEqual = function($otherSet) {
  if (this === $otherSet) return true;
  if (this.length != $otherSet.length) return false;
  var ret = true;
  this.each(function(idx) { 
    if (this !== $otherSet[idx]) {
       ret = false; return false;
    }
  });
  return ret;
};

var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];

console.log($(b).isEqual(a));

How do I write out a text file in C# with a code page other than UTF-8?

using System.IO;
using System.Text;

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

An alternate way of getting your encoding:

using System.IO;
using System.Text;

using (var sw  = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
    sw.WriteLine("my text...");             
}

Check out the docs for the StreamWriter constructor.

How to make the web page height to fit screen height

you can use css to set the body tag to these settings:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

Why doesn't Java offer operator overloading?

Check out Boost.Units: link text

It provides zero-overhead Dimensional analysis through operator overloading. How much clearer can this get?

quantity<force>     F = 2.0*newton;
quantity<length>    dx = 2.0*meter;
quantity<energy>    E = F * dx;
std::cout << "Energy = " << E << endl;

would actually output "Energy = 4 J" which is correct.

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

WebApiConfig is the place where you can configure whether you want to output in json or xml. By default, it is xml. In the register function, we can use HttpConfiguration Formatters to format the output.

System.Net.Http.Headers => MediaTypeHeaderValue("text/html") is required to get the output in the json format.

enter image description here

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

ValueError: unsupported format character while forming strings

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")


A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)

How to add a “readonly” attribute to an <input>?

Use the setAttribute property. Note in example that if select 1 apply the readonly attribute on textbox, otherwise remove the attribute readonly.

http://jsfiddle.net/baqxz7ym/2/

document.getElementById("box1").onchange = function(){
  if(document.getElementById("box1").value == 1) {
    document.getElementById("codigo").setAttribute("readonly", true);
  } else {
    document.getElementById("codigo").removeAttribute("readonly");
  }
};

<input type="text" name="codigo" id="codigo"/>

<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>

How to convert a single char into an int

You can make use of atoi() function

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
    int num ;
    num = atoi(argv[1]);
    printf("\n%d", num);
}

Executing multi-line statements in the one-line command-line?

The problem is not with the import statement. The problem is that the control flow statements don't work inlined in a python command. Replace that import statement with any other statement and you'll see the same problem.

Think about it: python can't possibly inline everything. It uses indentation to group control-flow.

Android: How to Programmatically set the size of a Layout

my sample code

wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen

How to apply an XSLT Stylesheet in C#

Here is a tutorial about how to do XSL Transformations in C# on MSDN:

http://support.microsoft.com/kb/307322/en-us/

and here how to write files:

http://support.microsoft.com/kb/816149/en-us

just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):

http://support.microsoft.com/kb/307379/en-us/

i added this just to provide some more information.

Java List.contains(Object with field value equal to x)

Eclipse Collections

If you're using Eclipse Collections, you can use the anySatisfy() method. Either adapt your List in a ListAdapter or change your List into a ListIterable if possible.

ListIterable<MyObject> list = ...;

boolean result =
    list.anySatisfy(myObject -> myObject.getName().equals("John"));

If you'll do operations like this frequently, it's better to extract a method which answers whether the type has the attribute.

public class MyObject
{
    private final String name;

    public MyObject(String name)
    {
        this.name = name;
    }

    public boolean named(String name)
    {
        return Objects.equals(this.name, name);
    }
}

You can use the alternate form anySatisfyWith() together with a method reference.

boolean result = list.anySatisfyWith(MyObject::named, "John");

If you cannot change your List into a ListIterable, here's how you'd use ListAdapter.

boolean result = 
    ListAdapter.adapt(list).anySatisfyWith(MyObject::named, "John");

Note: I am a committer for Eclipse ollections.

sscanf in Python

You could install pandas and use pandas.read_fwf for fixed width format files. Example using /proc/net/arp:

In [230]: df = pandas.read_fwf("/proc/net/arp")

In [231]: print(df)
       IP address HW type Flags         HW address Mask Device
0   141.38.28.115     0x1   0x2  84:2b:2b:ad:e1:f4    *   eth0
1   141.38.28.203     0x1   0x2  c4:34:6b:5b:e4:7d    *   eth0
2   141.38.28.140     0x1   0x2  00:19:99:ce:00:19    *   eth0
3   141.38.28.202     0x1   0x2  90:1b:0e:14:a1:e3    *   eth0
4    141.38.28.17     0x1   0x2  90:1b:0e:1a:4b:41    *   eth0
5    141.38.28.60     0x1   0x2  00:19:99:cc:aa:58    *   eth0
6   141.38.28.233     0x1   0x2  90:1b:0e:8d:7a:c9    *   eth0
7    141.38.28.55     0x1   0x2  00:19:99:cc:ab:00    *   eth0
8   141.38.28.224     0x1   0x2  90:1b:0e:8d:7a:e2    *   eth0
9   141.38.28.148     0x1   0x0  4c:52:62:a8:08:2c    *   eth0
10  141.38.28.179     0x1   0x2  90:1b:0e:1a:4b:50    *   eth0

In [232]: df["HW address"]
Out[232]:
0     84:2b:2b:ad:e1:f4
1     c4:34:6b:5b:e4:7d
2     00:19:99:ce:00:19
3     90:1b:0e:14:a1:e3
4     90:1b:0e:1a:4b:41
5     00:19:99:cc:aa:58
6     90:1b:0e:8d:7a:c9
7     00:19:99:cc:ab:00
8     90:1b:0e:8d:7a:e2
9     4c:52:62:a8:08:2c
10    90:1b:0e:1a:4b:50

In [233]: df["HW address"][5]
Out[233]: '00:19:99:cc:aa:58'

By default it tries to figure out the format automagically, but there are options you can give for more explicit instructions (see documentation). There are also other IO routines in pandas that are powerful for other file formats.

Drop columns whose name contains a specific string from pandas DataFrame

the shortest way to do is is :

resdf = df.filter(like='Test',axis=1)

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

jQuery Screen Resolution Height Adjustment

Here is an example on how to center an object vertically with jQuery:

var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2  + 'px');

But you could easily change that to whatever your needs are.

insert datetime value in sql database with c#

using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
    cmd.ExecuteNonQuery();
}

It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.

WARNING: this is unsanitized. You should use parameters to avoid injection attacks.

EDIT: Since Jon insists.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

Change button background color using swift language

U can also play around the tintcolor and button image to indirectly change the color.

Prompt for user input in PowerShell

Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)] above your mandatory parameters), but it's also the only option that you won't hate yourself for later.

More below:

[Console]::ReadLine is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.

Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.

You're trying to ask for parameters.

You should use the [Parameter(Mandatory=$true)] attribute, and correct typing, to ask for the parameters.

If you use this on a [SecureString], it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]) then it will become help text for the prompt.

Matching an empty input box using CSS

There is no selector in CSS which does this. Attribute selectors match attribute values, not computed values.

You would have to use JavaScript.

how to insert date and time in oracle?

Just use TO_DATE() function to convert string to DATE.

For Example:

create table Customer(
       CustId int primary key,
       CustName varchar(20),
       DOB date);

insert into Customer values(1,'Vishnu', TO_DATE('1994/12/16 12:00:00', 'yyyy/mm/dd hh:mi:ss'));

Why does PEP-8 specify a maximum line length of 79 characters?

Since whitespace has semantic meaning in Python, some methods of word wrapping could produce incorrect or ambiguous results, so there needs to be some limit to avoid those situations. An 80 character line length has been standard since we were using teletypes, so 79 characters seems like a pretty safe choice.

Printing a char with printf

In C, character constant expressions such as '\n' or 'a' have type int (thus sizeof '\n' == sizeof (int)), whereas in C++ they have type char.

The statement printf("%d", '\0'); should simply print 0; the type of the expression '\0' is int, and its value is 0.

The statement printf("%d", ch); should print the integer encoding for the value in ch (for ASCII, 'a' == 97).

For each row return the column name of the largest value

A simple for loop can also be handy:

> df<-data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
> df
  V1 V2 V3
1  2  7  9
2  8  3  6
3  1  5  4
> df2<-data.frame()
> for (i in 1:nrow(df)){
+   df2[i,1]<-colnames(df[which.max(df[i,])])
+ }
> df2
  V1
1 V3
2 V1
3 V2

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

How do I set the selected item in a drop down box

If you have a big drop down. it's much easier to use jQuery with PHP.

This is how to do it:

<script>
$(document).ready(function () {
    $('select[name="country"]').val('<?=$data[0]['Country']?>');
});
</script>

How do I get the last four characters from a string in C#?

assuming you wanted the strings in between a string which is located 10 characters from the last character and you need only 3 characters.

Let's say StreamSelected = "rtsp://72.142.0.230:80/SMIL-CHAN-273/4CIF-273.stream"

In the above, I need to extract the "273" that I will use in database query

        //find the length of the string            
        int streamLen=StreamSelected.Length;

        //now remove all characters except the last 10 characters
        string streamLessTen = StreamSelected.Remove(0,(streamLen - 10));   

        //extract the 3 characters using substring starting from index 0
        //show Result is a TextBox (txtStreamSubs) with 
        txtStreamSubs.Text = streamLessTen.Substring(0, 3);

How do I write to the console from a Laravel Controller?

I haven't tried this myself, but a quick dig through the library suggests you can do this:

$output = new Symfony\Component\Console\Output\ConsoleOutput();
$output->writeln("<info>my message</info>");

I couldn't find a shortcut for this, so you would probably want to create a facade to avoid duplication.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on

SELECT column_name, position
  FROM all_cons_columns
 WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

Once you know what column(s) are affected, you can compare the data you're trying to INSERT or UPDATE against the data already in the table to determine why the constraint is being violated.

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

UPDATE 2020: SQL Server 2016+ JSON Serialization and De-serialization Examples

The data provided by the OP inserted into a temporary table called #project_members

drop table if exists #project_members;
create table #project_members(
  empName        varchar(20) not null,
  projID         varchar(20) not null);
go
insert #project_members(empName, projID) values
('ANDY', 'A100'),
('ANDY', 'B391'),
('ANDY', 'X010'),
('TOM', 'A100'),
('TOM', 'A510');

How to serialize this data into a single JSON string with a nested array containing projID's

select empName, (select pm_json.projID 
                 from #project_members pm_json 
                 where pm.empName=pm_json.empName 
                 for json path, root('projList')) projJSON
from #project_members pm
group by empName
for json path;

Result

'[
  {
    "empName": "ANDY",
    "projJSON": {
      "projList": [
        { "projID": "A100" },
        { "projID": "B391" },
        { "projID": "X010" }
      ]
    }
  },
  {
    "empName": "TOM",
    "projJSON": {
      "projList": [
        { "projID": "A100" },
        { "projID": "A510" }
      ]
    }
  }
]'

How to de-serialize this data from a single JSON string back to it's original rows and columns

declare @json           nvarchar(max)=N'[{"empName":"ANDY","projJSON":{"projList":[{"projID":"A100"},
                                         {"projID":"B391"},{"projID":"X010"}]}},{"empName":"TOM","projJSON":
                                         {"projList":[{"projID":"A100"},{"projID":"A510"}]}}]';

select oj.empName, noj.projID 
from openjson(@json) with (empName        varchar(20),
                           projJSON       nvarchar(max) as json) oj
     cross apply openjson(oj.projJSON, '$.projList') with (projID    varchar(20)) noj;

Results

empName projID
ANDY    A100
ANDY    B391
ANDY    X010
TOM     A100
TOM     A510

How to persist the unique empName to a table and store the projID's in a nested JSON array

drop table if exists #project_members_with_json;
create table #project_members_with_json(
  empName        varchar(20) unique not null,
  projJSON       nvarchar(max) not null);
go
insert #project_members_with_json(empName, projJSON) 
select empName, (select pm_json.projID 
                 from #project_members pm_json 
                 where pm.empName=pm_json.empName 
                 for json path, root('projList')) 
from #project_members pm
group by empName;

Results

empName projJSON
ANDY    {"projList":[{"projID":"A100"},{"projID":"B391"},{"projID":"X010"}]}
TOM     {"projList":[{"projID":"A100"},{"projID":"A510"}]}

How to de-serialize from a table with unique empName and nested JSON array column containing projID's

select wj.empName, oj.projID
from
  #project_members_with_json wj
 cross apply
  openjson(wj.projJSON, '$.projList') with (projID    varchar(20)) oj;

Results

empName projID
ANDY    A100
ANDY    B391
ANDY    X010
TOM     A100
TOM     A510

Open application after clicking on Notification

Thanks to above posts, here's the main lines - distilled from the longer code answers - that are necessary to connect a notification with click listener set to open some app Activity.

private Notification getNotification(String messageText) {

    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentText(messageText);
    // ...

    Intent appActivityIntent = new Intent(this, SomeAppActivity.class);

    PendingIntent contentAppActivityIntent =
            PendingIntent.getActivity(
                            this,  // calling from Activity
                            0,
                            appActivityIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(contentAppActivityIntent);

    return builder.build();
}

Sort Pandas Dataframe by Date

@JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

(Note: You almost certainly will want it, because your date columns should be dates, not strings!)

In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

First, get the index from your sorted Date column:

In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')

Then use it to index your original DataFrame, leaving it untouched:

In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]: 
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Magic!

Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

Full width layout with twitter bootstrap

Update:

Bootstrap 3 has been released since this question was originally answered in January, so if you are a BS3 user, please refer to the BS3 documentation. For those still on BS2, the original answer still applies. If you are interested in switching from 2 to 3, see the migration guide.

Original answer:

From the bootstrap 2 docs:

Make any row "fluid" by changing .row to .row-fluid. The column classes stay the exact same, making it easy to flip between fixed and fluid grids.

Code

<div class="row-fluid">
  <div class="span4">...</div>
  <div class="span8">...</div>
</div>

This, in conjunction with setting the width of your container to a fluid value, should allow you to get your desired layout.

Strings and character with printf

The name of an array is the address of its first element, so name is a pointer to memory containing the string "siva".

Also you don't need a pointer to display a character; you are just electing to use it directly from the array in this case. You could do this instead:

char c = *name;
printf("%c\n", c);

How do I open a new window using jQuery?

It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:

window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');

That's it.

The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener later if there was no window name specified (just a little FYI), and the last two params are width/height.

EDIT: Full specification can be found in the link mmmshuddup provided.

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

add @method('PUT') on the form

exp:

<form action="..." method="POST">

@csrf  

@method('PUT')



</form>

How to move Docker containers between different hosts?

What eventually worked for me, after lot's of confusing manuals and confusing tutorials, since Docker is obviously at time of my writing at peek of inflated expectations, is:

  1. Save the docker image into archive:
    docker save image_name > image_name.tar
  2. copy on another machine
  3. on that other docker machine, run docker load in a following way:
    cat image_name.tar | docker load

Export and import, as proposed in another answers does not export ports and variables, which might be required for your container to run. And you might end up with stuff like "No command specified" etc... When you try to load it on another machine.

So, difference between save and export is that save command saves whole image with history and metadata, while export command exports only files structure (without history or metadata).

Needless to say is that, if you already have those ports taken on the docker hyper-visor you are doing import, by some other docker container, you will end-up in conflict, and you will have to reconfigure exposed ports.

Note: In order to move data with docker, you might be having persistent storage somewhere, which should also be moved alongside with containers.

Simple way to count character occurrences in a string

Something a bit more functional, without Regex:

public static int count(String s, char c) {
    return s.length()==0 ? 0 : (s.charAt(0)==c ? 1 : 0) + count(s.substring(1),c);
}

It's no tail recursive, for the sake of clarity.

What are the advantages of NumPy over regular Python lists?

All have highlighted almost all major differences between numpy array and python list, I will just brief them out here:

  1. Numpy arrays have a fixed size at creation, unlike python lists (which can grow dynamically). Changing the size of ndarray will create a new array and delete the original.

  2. The elements in a Numpy array are all required to be of the same data type (we can have the heterogeneous type as well but that will not gonna permit you mathematical operations) and thus will be the same size in memory

  3. Numpy arrays are facilitated advances mathematical and other types of operations on large numbers of data. Typically such operations are executed more efficiently and with less code than is possible using pythons build in sequences

JavaScript to get rows count of a HTML table

$('tableName').find('tr').length

How can I count the number of matches for a regex?

If you want to use Java 8 streams and are allergic to while loops, you could try this:

public static int countPattern(String references, Pattern referencePattern) {
    Matcher matcher = referencePattern.matcher(references);
    return Stream.iterate(0, i -> i + 1)
            .filter(i -> !matcher.find())
            .findFirst()
            .get();
}

Disclaimer: this only works for disjoint matches.

Example:

public static void main(String[] args) throws ParseException {
    Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
    System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
    System.out.println(countPattern("[  ]", referencePattern));
}

This prints out:

2
0
1
0

This is a solution for disjoint matches with streams:

public static int countPattern(String references, Pattern referencePattern) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            new Iterator<Integer>() {
                Matcher matcher = referencePattern.matcher(references);
                int from = 0;

                @Override
                public boolean hasNext() {
                    return matcher.find(from);
                }

                @Override
                public Integer next() {
                    from = matcher.start() + 1;
                    return 1;
                }
            },
            Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}

Add a column to existing table and uniquely number them on MS SQL Server

Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick

Check out this MSDN article http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx on the ALTER TABLE syntax

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

Proper usage of Optional.ifPresent()

You can use method reference like this:

user.ifPresent(ClassNameWhereMethodIs::doSomethingWithUser);

Method ifPresent() get Consumer object as a paremeter and (from JavaDoc): "If a value is present, invoke the specified consumer with the value." Value it is your variable user.

Or if this method doSomethingWithUser is in the User class and it is not static, you can use method reference like this:

user.ifPresent(this::doSomethingWithUser);

:touch CSS pseudo-class or something similar?

There is no such thing as :touch in the W3C specifications, http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors

:active should work, I would think.

Order on the :active/:hover pseudo class is important for it to function correctly.

Here is a quote from that above link

Interactive user agents sometimes change the rendering in response to user actions. CSS provides three pseudo-classes for common cases:

  • The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
  • The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
  • The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).

Writing a Python list of lists to a csv file

If for whatever reason you wanted to do it manually (without using a module like csv,pandas,numpy etc.):

with open('myfile.csv','w') as f:
    for sublist in mylist:
        for item in sublist:
            f.write(item + ',')
        f.write('\n')

Of course, rolling your own version can be error-prone and inefficient ... that's usually why there's a module for that. But sometimes writing your own can help you understand how they work, and sometimes it's just easier.

How to place object files in separate subdirectory

For all those working with implicit rules (and GNU MAKE). Here is a simple makefile which supports different directories:

#Start of the makefile

VPATH = ./src:./header:./objects

OUTPUT_OPTION = -o objects/$@

CXXFLAGS += -Wall -g -I./header

Target = $(notdir $(CURDIR)).exe

Objects := $(notdir $(patsubst %.cpp,%.o,$(wildcard src/*.cpp)))



all: $(Target)

$(Target): $(Objects)
     $(CXX) $(CXXFLAGS) -o $(Target) $(addprefix objects/,$(Objects))


#Beware of -f. It skips any confirmation/errors (e.g. file does not exist)

.PHONY: clean
clean:
     rm -f $(addprefix objects/,$(Objects)) $(Target)

Lets have a closer look (I will refer to the current Directory with curdir):

This line is used to get a list of the used .o files which are in curdir/src.

Objects := $(notdir $(patsubst %.cpp,%.o,$(wildcard src/*.cpp)))
#expands to "foo.o myfoo.o otherfoo.o"

Via variable the output is set to a different directory (curdir/objects).

OUTPUT_OPTION = -o objects/$@
#OUTPUT_OPTION will insert the -o flag into the implicit rules

To make sure the compiler finds the objects in the new objects folder, the path is added to the filename.

$(Target): $(Objects)
     $(CXX) $(CXXFLAGS) -o $(Target) $(addprefix objects/,$(Objects))
#                                    ^^^^^^^^^^^^^^^^^^^^    

This is meant as an example and there is definitly room for improvement.

For additional Information consult: Make documetation. See chapter 10.2

Or: Oracle: Programming Utilities Guide

Android, How to read QR code in my application?

if user doesn't have any qr reader, what will happen to the application? if it crashes, may i ask user to download for example QrDroid and after that use it?

Interestingly, Google now introduced Mobile Vision APIs, they are integrated in play services itself.

In your Gradle file just add:

compile 'com.google.android.gms:play-services-vision:11.4.0'

Taken from this QR code tutorial.

UPDATE 2020:

Now QR code scanning is also a part of ML Kit, so you can bundle the model inside the app and use it by integrating the following gradle dependency:

dependencies {
  // ...
  // Use this dependency to bundle the model with your app
  implementation 'com.google.mlkit:barcode-scanning:16.0.3'
}

Or you can use the following gradle dependency to dynamically download the models from Google Play Services:

dependencies {
  // ...
  // Use this dependency to use the dynamically downloaded model in Google Play Services
  implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:16.1.2'
}

Taken from this link.

See whether an item appears more than once in a database column

try this:

select salesid,count (salesid) from AXDelNotesNoTracking group by salesid having count (salesid) >1

How is the default submit button on an HTML form determined?

Andrezj's pretty much got it nailed... but here's an easy cross-browser solution.

Take a form like this:

<form>
    <input/>
    <button type="submit" value="some non-default action"/>
    <button type="submit" value="another non-default action"/>
    <button type="submit" value="yet another non-default action"/>

    <button type="submit" value="default action"/>
</form>

and refactor to this:

<form>
    <input/>

    <button style="overflow: visible !important; height: 0 !important; width: 0 !important; margin: 0 !important; border: 0 !important; padding: 0 !important; display: block !important;" type="submit" value="default action"/>

    <button type="submit" value="some non-default action"/>
    <button type="submit" value="another non-default action"/>
    <button type="submit" value="yet another non-default action"/>
    <button type="submit" value="still another non-default action"/>

    <button type="submit" value="default action"/>
</form>

Since the W3C spec indicates multiple submit buttons are valid, but omits guidance as to how the user-agent should handle them, the browser manufacturers are left to implement as they see fit. I've found they'll either submit the first submit button in the form, or submit the next submit button after the form field that currently has focus.

Unfortunately, simply adding a style of display: none; won't work because the W3C spec indicates any hidden element should be excluded from user interactions. So hide it in plain sight instead!

Above is an example of the solution I ended up putting into production. Hitting the enter key triggers the default form submission is behavior as expected, even when other non-default values are present and precede the default submit button in the DOM. Bonus for mouse/keyboard interaction with explicit user inputs while avoiding javascript handlers.

Note: tabbing through the form will not display focus for any visual element yet will still cause the invisible button to be selected. To avoid this issue, simply set tabindex attributes accordingly and omit a tabindex attribute on the invisible submit button. While it may seem out of place to promote these styles to !important, they should prevent any framework or existing button styles from interfering with this fix. Also, those inline styles are definitely poor form, but we're proving concepts here... not writing production code.

How can I calculate the number of years between two dates?

getAge(month, day, year) {
    let yearNow = new Date().getFullYear();
    let monthNow = new Date().getMonth() + 1;
    let dayNow = new Date().getDate();
    if (monthNow === month && dayNow < day || monthNow < month) {
      return yearNow - year - 1;
    } else {
      return yearNow - year;
    }
  }

How can I get CMake to find my alternative Boost installation?

I just added the environment variable Boost_INCLUDE_DIR or add it to the cmake command -DBoost_INCLUDE_DIR and point to the include folder.

Passing parameters on button action:@selector

I think the correct method should be : - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents

UIControl Reference

Where do you get your method from?

I see that your selector has an argument, that argument will be filled by the runtime system. It will send you back the button through that argument.

Your method should look like:

- (void)buttonPressed:(id)BUTTON_HERE { }

How to create windows service from java jar?

With procrun you need to copy prunsrv to the application directory (download), and create an install.bat like this:

set PR_PATH=%CD%
SET PR_SERVICE_NAME=MyService
SET PR_JAR=MyService.jar
SET START_CLASS=org.my.Main
SET START_METHOD=main
SET STOP_CLASS=java.lang.System
SET STOP_METHOD=exit
rem ; separated values
SET STOP_PARAMS=0
rem ; separated values
SET JVM_OPTIONS=-Dapp.home=%PR_PATH%
prunsrv.exe //IS//%PR_SERVICE_NAME% --Install="%PR_PATH%\prunsrv.exe" --Jvm=auto --Startup=auto --StartMode=jvm --StartClass=%START_CLASS% --StartMethod=%START_METHOD% --StopMode=jvm --StopClass=%STOP_CLASS% --StopMethod=%STOP_METHOD% ++StopParams=%STOP_PARAMS% --Classpath="%PR_PATH%\%PR_JAR%" --DisplayName="%PR_SERVICE_NAME%" ++JvmOptions=%JVM_OPTIONS%

I presume to

  • run this from the same directory where the jar and prunsrv.exe is
  • the jar has its working MANIFEST.MF
  • and you have shutdown hooks registered into JVM (for example with context.registerShutdownHook() in Spring)...
  • not using relative paths for files outside the jar (for example log4j should be used with log4j.appender.X.File=${app.home}/logs/my.log or something alike)

Check the procrun manual and this tutorial for more information.

Using python's mock patch.object to change the return value of a method called within another method

To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:

Given the following function to test, located in module.a_function.to_test.py:

from some_other.module import SomeOtherClass

def add_results():
    my_object = SomeOtherClass('some_contextual_parameters')
    result_a = my_object.method_a()
    result_b = my_object.method_b()
    
    return result_a + result_b

To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass by using patch.object() in combination with sys.modules:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  mocked_other_class().method_a.return_value = 4
  mocked_other_class().method_b.return_value = 7

  self.assertEqual(add_results(), 11)

This works no matter the number of methods of SomeOtherClass you need to patch, with independent results.

Also, using the same patching method, an actual instance of SomeOtherClass can be returned if need be:

@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
  other_class_instance = SomeOtherClass('some_controlled_parameters')
  mocked_other_class.return_value = other_class_instance 
  ...

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

 switch(KEYEVENT.getKeyCode()){
      case KeyEvent.VK_ENTER:
           // I was trying to use case 13 from the ascii table.
           //Krewn Generated method stub... 
           break;
 }

python multithreading wait till all threads finished

I prefer using list comprehension based on an input list:

inputs = [scriptA + argumentsA, scriptA + argumentsB, ...]
threads = [Thread(target=call_script, args=(i)) for i in inputs]
[t.start() for t in threads]
[t.join() for t in threads]

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Force file download with php using header()

Here is a snippet from me in testing... obviously passing via get to the script may not be the best... should post or just send an id and grab guid from db... anyhow.. this worked. I take the URL and convert it to a path.

// Initialize a file URL to the variable
$file = $_GET['url'];
$file = str_replace(Polepluginforrvms_Plugin::$install_url, $DOC_ROOT.'/pole-permitter/', $file );

$quoted = sprintf('"%s"', addcslashes(basename($file), '"\\'));
$size   = filesize($file);

header( "Content-type: application/octet-stream" );
header( "Content-Disposition: attachment; filename={$quoted}" );
header( "Content-length: " . $size );
header( "Pragma: no-cache" );
header( "Expires: 0" );
readfile( "{$file}" );

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

Very simple verison of the rebase solution:

Go to the folder where git is installed, such as:

C:\Program Files (x86)\Git\bin

By holding shift and right clicking in the folder, you should be able to open a command prompt as administrator from there (thanks to https://stackoverflow.com/users/355389/darren-lewis for that comment),

Then run:

rebase.exe -b 0x50000000 msys-1.0.dll

This fixed it for me when the restart approach didn't work.

Hope it helps.

How to pass params with history.push/Link/Redirect in react-router v4?

It is not necessary to use withRouter. This works for me:

In your parent page,

<BrowserRouter>
   <Switch>
        <Route path="/routeA" render={(props)=> (
          <ComponentA {...props} propDummy={50} />
        )} />

        <Route path="/routeB" render={(props)=> (
          <ComponentB {...props} propWhatever={100} />
          )} /> 
      </Switch>
</BrowserRouter>

Then in ComponentA or ComponentB you can access

this.props.history

object, including the this.props.history.push method.

encapsulation vs abstraction real world example

Abstration which hide internal detail to outside world for example you create a class(like calculator one of the class) but for end use you provide object of class ,With the help of object they will play and perform operation ,He does't aware what type of mechanism use internally .Object of class in abstract form .

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.For example class calculator which contain private methods getAdd,getMultiply .

Mybe above answer will help you to understand the concept .

Getting msbuild.exe without installing Visual Studio

It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760

To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.

A html space is showing as %2520 instead of %20

The following code snippet resolved my issue. Thought this might be useful to others.

_x000D_
_x000D_
var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");
_x000D_
_x000D_
_x000D_

Rather using default encodeURIComponent my first line of code is converting all spaces into hyphens using regex pattern /\s\g and the following line just does the reverse, i.e. converts all hyphens back to spaces using another regex pattern /-/g. Here /g is actually responsible for finding all matching characters.

When I am sending this value to my Ajax call, it traverses as normal spaces or simply %20 and thus gets rid of double-encoding.

ng: command not found while creating new project using angular-cli

I've solved the same issue with adding an alias like:

alias ng="path-to-your-global-node-modules/angular-cli/bin/ng"

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

In my case.. following steps resolved:

There was a column value which was set to "Update" - replaced it with Edit (non sql keyword) There was a space in one of the column names (removed the extra space or trim)

Return first N key:value pairs from dict

For Python 3.8 the correct answer should be:

import more_itertools

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

first_n = more_itertools.take(3, d.items())
print(len(first_n))
print(first_n)

Whose output is:

3
[('a', 3), ('b', 2), ('c', 3)]

After pip install more-itertools of course.

org.xml.sax.SAXParseException: Content is not allowed in prolog

First clean project, then rebuild project. I was also facing the same issue. Everything came alright after this.

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

Changing :hover to touch/click for mobile devices

Well I agree with above answers but still there can be an another way to do this and it is by using media queries.

Suppose this is what you want to do :

body.nontouch nav a:hover {
    background: yellow;
}

then you can do this by media query as :

@media(hover: hover) and (pointer: fine) {
    nav a:hover {
        background: yellow;
    }
}

And for more details you can visit this page.

Pycharm does not show plot

For beginners, you might also want to make sure you are running your script in the console, and not as regular Python code. It is fairly easy to highlight a piece of code and run it.

Verify object attribute value with mockito

I think the easiest way for verifying an argument object is to use the refEq method:

Mockito.verify(mockedObject).someMethodOnMockedObject(ArgumentMatchers.refEq(objectToCompareWith));

It can be used even if the object doesn't implement equals(), because reflection is used. If you don't want to compare some fields, just add their names as arguments for refEq.

AngularJs event to call after content is loaded

I use setInterval to wait for the content loaded. I hope this can help you to solve that problem.

var $audio = $('#audio');
var src = $audio.attr('src');
var a;
a = window.setInterval(function(){
    src = $audio.attr('src');
    if(src != undefined){
        window.clearInterval(a);
        $('audio').mediaelementplayer({
            audioWidth: '100%'
        });
    }
}, 0);

How to automatically insert a blank row after a group of data

Just an idea, if you know the categories, as small, medium, and large mentioned above...

At the bottom of the sheet, make 3 rows that only say small, medium, and large, change the font to white, and then sort so that it alphabetizes, placing a blank row between each section.

What causes this error? "Runtime error 380: Invalid property value"

Many really silly things can cause this error. The one I've encountered is a font no longer included with Windows 8 by default - Courier New. The VB6 application had its name hard-coded in one of the forms, hence the message on start-up.

How do I remove all .pyc files from a project?

find . -name "*.pyc" -exec rm -f {} \;

Attach the Java Source Code

enter image description here

if you are add jre and jkd path, remove jre install path, keep jdk path is work

How to reverse apply a stash?

How to reverse apply a stash?

Apart from what others have mentioned, easiest way is first do

git reset HEAD

and then checkout all local changes

git checkout . 

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

I have Samsung Galaxy S3 and it was not showing in the "Remote devices" tab nor in chrome://inspect. The device did show in Windows's Device Manager as GT-I9300, though. What worked for me was:

  1. Plug the mobile phone to the front USB port
  2. On my phone, click the notification about successful connection
  3. Make sure the connection type is Camera (PTP)
  4. On my Windows machine, download installer from https://github.com/koush/UniversalAdbDriver
  5. Run it :)
  6. Open cmd.exe
  7. cd "C:\Program Files (x86)\ClockworkMod\Universal Adb Driver"
  8. adb devices
  9. Open Chrome in both mobile phone and Windows machine
  10. On Windows's machine navigate to chrome://inspect - there, after a while you should see the target phone :)

I'm not sure if it affected the whole flow somehow, but at some point I've installed, and later uninstalled the drivers from Samsung: http://www.samsung.com/us/support/downloads/ > Mobile > Phones > Galaxy S > S III > Unlocked > http://www.samsung.com/us/support/owners/product/galaxy-s-iii-unlocked#downloads

T-SQL Cast versus Convert

CAST is standard SQL, but CONVERT is only for the dialect T-SQL. We have a small advantage for convert in the case of datetime.

With CAST, you indicate the expression and the target type; with CONVERT, there’s a third argument representing the style for the conversion, which is supported for some conversions, like between character strings and date and time values. For example, CONVERT(DATE, '1/2/2012', 101) converts the literal character string to DATE using style 101 representing the United States standard.

How do I make a relative reference to another workbook in Excel?

What works for me was with one dot. Mine Office is 365. =HYPERLINK(".\Name_of_folder\","DisplayLinkName") =HYPERLINK(".\Name_of_file","DisplayLinkName")

C++ calling base class constructors

In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.

According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.

In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

Try mapping it. Try placing this code in your UserControl:

public event EventHandler ValueChanged {
  add { numericUpDown1.ValueChanged += value; }
  remove { numericUpDown1.ValueChanged -= value; }
}

then your UserControl will have the ValueChanged event you normally see with the NumericUpDown control.

Is there a better way to refresh WebView?

try this :

mWebView.loadUrl(mWebView.getUrl().toString());

Insert into a MySQL table or update if exists

In my case i created below queries but in the first query if id 1 is already exists and age is already there, after that if you create first query without age than the value of age will be none

REPLACE into table SET `id` = 1, `name` = 'A', `age` = 19

for avoiding above issue create query like below

INSERT INTO table SET `id` = '1', `name` = 'A', `age` = 19 ON DUPLICATE KEY UPDATE `id` = "1", `name` = "A",`age` = 19

may it will help you ...

Convert Difference between 2 times into Milliseconds?

If you just want to display a message box at 12:02, use a timer control with delay of, say, 250ms, that keeps checking if the current time is 12:02. When it is, display the message and stop the timer. Note this does not require a start time field (although you may be using that for something else -- I don't know -- in which case the other code provided to you here will be helpful).

Get current URL from IFRAME

For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:

document.getElementById("iframe_id").contentWindow.location.href

If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.

See also answers to a similar question.

how do I loop through a line from a csv file in powershell

Import-Csv $path | Foreach-Object { 

    foreach ($property in $_.PSObject.Properties)
    {
        doSomething $property.Name, $property.Value
    } 

}

Completely Remove MySQL Ubuntu 14.04 LTS

This is what saved me. Apparently the depackager tries to put things in the wrong tmp folder.

https://askubuntu.com/a/248860

Scroll to bottom of div?

Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:

//get the div that contains all the messages
let div = document.getElementById('message-container');

//make the last element (a message) to scroll into view, smoothly!
div.lastElementChild.scrollIntoView({ behavior: 'smooth' });

Impersonate tag in Web.Config

Put the identity element before the authentication element

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

I made a really silly mistake for this. When I was getting same error every time i could not figure out what was wrong. then it clicked me that once I have closed all the projects in my work space and that was the time since all the problems started. SO just check whether your "appcompat_v7" is not closed. If it is then open the project by double click and then clean and build your project again. In my case the errors were gone. Happy coding!

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

Collision resolution in Java HashMap

There is difference between collision and duplication. Collision means hashcode and bucket is same, but in duplicate, it will be same hashcode,same bucket, but here equals method come in picture.

Collision detected and you can add element on existing key. but in case of duplication it will replace new value.

How do I check if I'm running on Windows in Python?

Python os module

Specifically for Python 3.6/3.7:

os.name: The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.

In your case, you want to check for 'nt' as os.name output:

import os

if os.name == 'nt':
     ...

There is also a note on os.name:

See also sys.platform has a finer granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

Declaring variables inside loops, good practice or bad practice?

This is excellent practice.

By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.

This way:

  • If the name of the variable is a bit "generic" (like "i"), there is no risk to mix it with another variable of same name somewhere later in your code (can also be mitigated using the -Wshadow warning instruction on GCC)

  • The compiler knows that the variable scope is limited to inside the loop, and therefore will issue a proper error message if the variable is by mistake referenced elsewhere.

  • Last but not least, some dedicated optimization can be performed more efficiently by the compiler (most importantly register allocation), since it knows that the variable cannot be used outside of the loop. For example, no need to store the result for later re-use.

In short, you are right to do it.

Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time. You can also create a larger block, encompassing the loop, whose sole purpose is to declare variables which must retain their value from one loop to another. This typically includes the loop counter itself.

{
    int i, retainValue;
    for (i=0; i<N; i++)
    {
       int tmpValue;
       /* tmpValue is uninitialized */
       /* retainValue still has its previous value from previous loop */

       /* Do some stuff here */
    }
    /* Here, retainValue is still valid; tmpValue no longer */
}

For question #2: The variable is allocated once, when the function is called. In fact, from an allocation perspective, it is (nearly) the same as declaring the variable at the beginning of the function. The only difference is the scope: the variable cannot be used outside of the loop. It may even be possible that the variable is not allocated, just re-using some free slot (from other variable whose scope has ended).

With restricted and more precise scope come more accurate optimizations. But more importantly, it makes your code safer, with less states (i.e. variables) to worry about when reading other parts of the code.

This is true even outside of an if(){...} block. Typically, instead of :

    int result;
    (...)
    result = f1();
    if (result) then { (...) }
    (...)
    result = f2();
    if (result) then { (...) }

it's safer to write :

    (...)
    {
        int const result = f1();
        if (result) then { (...) }
    }
    (...)
    {
        int const result = f2();
        if (result) then { (...) }
    }

The difference may seem minor, especially on such a small example. But on a larger code base, it will help : now there is no risk to transport some result value from f1() to f2() block. Each result is strictly limited to its own scope, making its role more accurate. From a reviewer perspective, it's much nicer, since he has less long range state variables to worry about and track.

Even the compiler will help better : assuming that, in the future, after some erroneous change of code, result is not properly initialized with f2(). The second version will simply refuse to work, stating a clear error message at compile time (way better than run time). The first version will not spot anything, the result of f1() will simply be tested a second time, being confused for the result of f2().

Complementary information

The open-source tool CppCheck (a static analysis tool for C/C++ code) provides some excellent hints regarding optimal scope of variables.

In response to comment on allocation: The above rule is true in C, but might not be for some C++ classes.

For standard types and structures, the size of variable is known at compilation time. There is no such thing as "construction" in C, so the space for the variable will simply be allocated into the stack (without any initialization), when the function is called. That's why there is a "zero" cost when declaring the variable inside a loop.

However, for C++ classes, there is this constructor thing which I know much less about. I guess allocation is probably not going to be the issue, since the compiler shall be clever enough to reuse the same space, but the initialization is likely to take place at each loop iteration.

Android scale animation on view

In XML, this what I use for achieving the same result. May be this is more intuitive.

scale_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<scale
    android:duration="200"
    android:fromXScale="1.0"
    android:fromYScale="0.0"
    android:pivotX="50%"
    android:pivotY="100%"
    android:toXScale="1.0"
    android:toYScale="1.0" />

</set>

scale_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

<scale
    android:duration="200"
    android:fromXScale="1.0"
    android:fromYScale="1.0"
    android:pivotX="50%"
    android:pivotY="100%"
    android:toXScale="1.0"
    android:toYScale="0.0" />

</set>

See the animation on the X axis is from 1.0 -> 1.0 which means you don't have any scaling up in that direction and stays at the full width while, on the Y axis you get 0.0 -> 1.0 scaling, as shown in the graphic in the question. Hope this helps someone.

Some might want to know the java code as we see one requested.

Place the animation files in anim folder and then load and set animation files something like.

Animation scaleDown = AnimationUtils.loadAnimation(youContext, R.anim.scale_down);
ImagView v = findViewById(R.id.your_image_view);
v.startAnimation(scaleDown);

Create a Cumulative Sum Column in MySQL

select id,count,sum(count)over(order by count desc) as cumulative_sum from tableName;

I have used the sum aggregate function on the count column and then used the over clause. It sums up each one of the rows individually. The first row is just going to be 100. The second row is going to be 100+50. The third row is 100+50+10 and so forth. So basically every row is the sum of it and all the previous rows and the very last one is the sum of all the rows. So the way to look at this is each row is the sum of the amount where the ID is less than or equal to itself.

GZIPInputStream reading line by line

BufferedReader in = new BufferedReader(new InputStreamReader(
        new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"))));

String content;

while ((content = in.readLine()) != null)

   System.out.println(content);

Incrementing a variable inside a Bash loop

Incrementing a variable can be done like that:

  _my_counter=$[$_my_counter + 1]

Counting the number of occurrence of a pattern in a column can be done with grep

 grep -cE "^([^ ]* ){2}US"

-c count

([^ ]* ) To detect a colonne

{2} the colonne number

US your pattern

Press any key to continue

Check out the ReadKey() method on the System.Console .NET class. I think that will do what you're looking for.

http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

Example:

Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

How can I get a collection of keys in a JavaScript dictionary?

If you can use jQuery then

var keys = [];
$.each(driversCounter, function(key, value) {
    keys.push(key);
});

console.log(JSON.stringify(keys));

Here follows the answer:

["one", "two", "three", "four", "five"]

And this way you wouldn't have to worry if the browser supports the Object.keys method or not.

How to asynchronously call a method in Java

You can use @Async annotation from jcabi-aspects and AspectJ:

public class Foo {
  @Async
  public void save() {
    // to be executed in the background
  }
}

When you call save(), a new thread starts and executes its body. Your main thread continues without waiting for the result of save().

How to delete a record by id in Flask-SQLAlchemy

Just want to share another option:

# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)

# commit (or flush)
session.commit()

http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting

In this example, the following codes shall works fine:

obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()

Go to beginning of line without opening new line in VI

Type "^". And get a good "Vi" tutorial :)

How to remove a field completely from a MongoDB document?

In the beginning, I did not get why the question has a bounty (I thought that the question has a nice answer and there is nothing to add), but then I noticed that the answer which was accepted and upvoted 15 times was actually wrong!

Yes, you have to use $unset operator, but this unset is going to remove the words key which does not exist for a document for a collection. So basically it will do nothing.

So you need to tell Mongo to look in the document tags and then in the words using dot notation. So the correct query is.

db.example.update(
  {},
  { $unset: {'tags.words':1}},
  false, true
)

Just for the sake of completion, I will refer to another way of doing it, which is much worse, but this way you can change the field with any custom code (even based on another field from this document).

TCPDF output without saving file

Use I for "inline" to send the PDF to the browser, opposed to F to save it as a file.

$pdf->Output('name.pdf', 'I');

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. then sudo nano idlemain.py, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

Copying from one text file to another using Python

Just a slightly cleaned up way of doing this. This is no more or less performant than ATOzTOA's answer, but there's no reason to do two separate with statements.

with open(path_1, 'a') as file_1, open(path_2, 'r') as file_2:
    for line in file_2:
        if 'tests/file/myword' in line:
            file_1.write(line)

Adobe Reader Command Line Reference

I found this:

http://www.robvanderwoude.com/commandlineswitches.php#Acrobat

Open a PDF file with navigation pane active, zoom out to 50%, and search for and highlight the word "batch":

AcroRd32.exe /A "zoom=50&navpanes=1=OpenActions&search=batch" PdfFile

How do I set up CLion to compile and run?

You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.

Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)

follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html

How to square all the values in a vector in R?

Try this (faster and simpler):

newData <- data^2

Saving timestamp in mysql table using php

Check field type in table just save time stamp value in datatype like bigint etc.

Not datetime type

Five equal columns in twitter bootstrap

A solution that do not require a lot of CSS, nor tweaking bootstrap default 12col layout:

http://jsfiddle.net/0ufdyeur/1/

HTML:

<div class="stretch">
  <div class="col-lg-2"></div>
  <div class="col-lg-2"></div>
  <div class="col-lg-2"></div>
  <div class="col-lg-2"></div>
  <div class="col-lg-2"></div>
</div>

CSS:

@media (min-width: 1200px) { /*if not lg, change this criteria*/
  .stretch{
    width: 120%; /*the actual trick*/
  }
}

Display unescaped HTML in Vue.js

Starting with Vue2, the triple braces were deprecated, you are to use v-html.

<div v-html="task.html_content"> </div>

It is unclear from the documentation link as to what we are supposed to place inside v-html, your variables goes inside v-html.

Also, v-html works only with <div> or <span> but not with <template>.

If you want to see this live in an app, click here.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

gradle.properties:

theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6

settings.gradle:

rootProject.name = theName

build.gradle:

apply plugin: "java"

group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility

Fastest Way to Find Distance Between Two Lat/Long Points

  • Create your points using Point values of Geometry data types in MyISAM table. As of Mysql 5.7.5, InnoDB tables now also support SPATIAL indices.

  • Create a SPATIAL index on these points

  • Use MBRContains() to find the values:

    SELECT  *
    FROM    table
    WHERE   MBRContains(LineFromText(CONCAT(
            '('
            , @lon + 10 / ( 111.1 / cos(RADIANS(@lon)))
            , ' '
            , @lat + 10 / 111.1
            , ','
            , @lon - 10 / ( 111.1 / cos(RADIANS(@lat)))
            , ' '
            , @lat - 10 / 111.1 
            , ')' )
            ,mypoint)
    

, or, in MySQL 5.1 and above:

    SELECT  *
    FROM    table
    WHERE   MBRContains
                    (
                    LineString
                            (
                            Point (
                                    @lon + 10 / ( 111.1 / COS(RADIANS(@lat))),
                                    @lat + 10 / 111.1
                                  ),
                            Point (
                                    @lon - 10 / ( 111.1 / COS(RADIANS(@lat))),
                                    @lat - 10 / 111.1
                                  ) 
                            ),
                    mypoint
                    )

This will select all points approximately within the box (@lat +/- 10 km, @lon +/- 10km).

This actually is not a box, but a spherical rectangle: latitude and longitude bound segment of the sphere. This may differ from a plain rectangle on the Franz Joseph Land, but quite close to it on most inhabited places.

  • Apply additional filtering to select everything inside the circle (not the square)

  • Possibly apply additional fine filtering to account for the big circle distance (for large distances)

Android: How to turn screen on and off programmatically?

Simply add

android:keepScreenOn="true" 

or call

setKeepScreenOn(true) 

on parent view.

JavaScript and getElementById for multiple elements with the same ID

You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.

Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.

How to terminate a Python script

from sys import exit
exit()

As a parameter you can pass an exit code, which will be returned to OS. Default is 0.

angularjs getting previous route path

modification for the code above:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('prev path: ' + absOldUrl.$$route.originalPath);
});

Custom method names in ASP.NET Web API

Web APi 2 and later versions support a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

For example:

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

Will perfect and you don't need any extra code for example in WebApiConfig.cs. Just you have to be sure web api routing is enabled or not in WebApiConfig.cs , if not you can activate like below:

        // Web API routes
        config.MapHttpAttributeRoutes();

You don't have to do something more or change something in WebApiConfig.cs. For more details you can have a look this article.

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Problem solved!

I was having all my website set up first in XAMMP, then I had to transfer it to LAMP, in a SUSE installation of LAMP, where I got this error.

The problem is that these parameters in the database.php file should not be initialised. Just leave username and password blank. That's just it.

(My first and lame guess would be that's because of old version of mysql, as built-in installations come with older versions.

How do I clear/delete the current line in terminal?

Just to summarise all the answers:

  • Clean up the line: You can use Ctrl+U to clear up to the beginning.
  • Clean up the line: Ctrl+E Ctrl+U to wipe the current line in the terminal
  • Clean up the line: Ctrl+A Ctrl+K to wipe the current line in the terminal
  • Cancel the current command/line: Ctrl+C.
  • Recall the deleted command: Ctrl+Y (then Alt+Y)
  • Go to beginning of the line: Ctrl+A
  • Go to end of the line: Ctrl+E
  • Remove the forward words for example, if you are middle of the command: Ctrl+K
  • Remove characters on the left, until the beginning of the word: Ctrl+W
  • To clear your entire command prompt: Ctrl + L
  • Toggle between the start of line and current cursor position: Ctrl + XX

How do I make a file:// hyperlink that works in both IE and Firefox?

Paste following link to directly under link button click event, otherwise use javascript to call code behind function

Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs) 
    System.Diagnostics.Process.Start(FilePath)
End Sub

Bootstrap Alert Auto Close

For a smooth slideup:

$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").slideUp(500);
});

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("#success-alert").hide();_x000D_
  $("#myWish").click(function showAlert() {_x000D_
    $("#success-alert").fadeTo(2000, 500).slideUp(500, function() {_x000D_
      $("#success-alert").slideUp(500);_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
<div class="product-options">_x000D_
  <a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>_x000D_
  <a href="" class="btn btn-mini"> Purchase </a>_x000D_
</div>_x000D_
<div class="alert alert-success" id="success-alert">_x000D_
  <button type="button" class="close" data-dismiss="alert">x</button>_x000D_
  <strong>Success! </strong> Product have added to your wishlist._x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Hibernate Delete query

To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -

Hibernate Object States

Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.

Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Detached - A detached instance is an object that has been persistent, but its Session has been closed.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview

Transaction Write-Behind

The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.

  • To perform batch inserts and updates.
  • To propagate only the last change. If an object is updated more than once, it still fires only one update statement.

http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html

First Level Cache

Hibernate has something called 'First Level Cache'. Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. This is where it tracks changes to various objects.

Hibernate Intercepters and Object Lifecycle Listeners -

The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069


This section Updated

Cascading

Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete' from parent to child association will result in deletion of all children when a parent is deleted.

So, why are these important.

To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.

That's why hibernate (sometimes) issues a 'SELECT' statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.

Why does hibernate issue the 'SELECT' statement only sometimes?

Hibernate issues a 'SELECT' statement to determine what state the object is in. If the select statement returns an object, the object is in detached state and if it does not return an object, the object is in transient state.

Coming to your scenario -

Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached and then re-attches it to the session and processes delete lifecycle.

Update - Since you are explicitly calling 'Update' instead of 'SaveOrUpdate', hibernate blindly assumes that the object is in detached state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.

SaveOrUpdate - If you call 'SaveOrUpdate', hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached state. If the object is in transient state, it processes the 'insert' lifecycle and if the object is in detached state, it processes the 'Update' lifecycle.

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

My problem is related to many of the other answers, but a little bit different reason for needing to make the change... I was trying to convert an Activity to a Fragment. So I moved the inflate code from onCreate to onCreateView, but I forgot to convert from setContentView to the inflate method, and the same IllegalStateException brought me to this page.

I changed this:

binding = DataBindingUtil.setContentView(requireActivity(), R.layout.my_fragment)

to this:

binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)

That solved the problem.

How to assert two list contain the same elements in Python?

Slightly faster version of the implementation (If you know that most couples lists will have different lengths):

def checkEqual(L1, L2):
    return len(L1) == len(L2) and sorted(L1) == sorted(L2)

Comparing:

>>> timeit(lambda: sorting([1,2,3], [3,2,1]))
2.42745304107666
>>> timeit(lambda: lensorting([1,2,3], [3,2,1]))
2.5644469261169434 # speed down not much (for large lists the difference tends to 0)

>>> timeit(lambda: sorting([1,2,3], [3,2,1,0]))
2.4570400714874268
>>> timeit(lambda: lensorting([1,2,3], [3,2,1,0]))
0.9596951007843018 # speed up

Get names of all keys in the collection

I know this question is 10 years old but there is no C# solution and this took me hours to figure out. I'm using the .NET driver and System.Linq to return a list of the keys.

var map = new BsonJavaScript("function() { for (var key in this) { emit(key, null); } }");
var reduce = new BsonJavaScript("function(key, stuff) { return null; }");
var options = new MapReduceOptions<BsonDocument, BsonDocument>();
var result = await collection.MapReduceAsync(map, reduce, options);
var list = result.ToEnumerable().Select(item => item["_id"].ToString());

Identifier is undefined

Are you missing a function declaration?

void ac_search(uint num_patterns, uint pattern_length, const char *patterns, 
               uint num_records, uint record_length, const char *records, int *matches, Node* trie);

Add it just before your implementation of ac_benchmark_search.

DLL and LIB files - what and why?

There are static libraries (LIB) and dynamic libraries (DLL) - but note that .LIB files can be either static libraries (containing object files) or import libraries (containing symbols to allow the linker to link to a DLL).

Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.

Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.

As an example, almost every program written in 'C' will need functions from a library called the 'C runtime library, though few programs will need all of the functions. The C runtime comes in both static and dynamic versions, so you can determine which version your program uses depending on particular needs.

Spring Boot - Handle to Hibernate SessionFactory

You can accomplish this with:

SessionFactory sessionFactory = 
    entityManagerFactory.unwrap(SessionFactory.class);

where entityManagerFactory is an JPA EntityManagerFactory.

package net.andreaskluth.hibernatesample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SomeService {

  private SessionFactory hibernateFactory;

  @Autowired
  public SomeService(EntityManagerFactory factory) {
    if(factory.unwrap(SessionFactory.class) == null){
      throw new NullPointerException("factory is not a hibernate factory");
    }
    this.hibernateFactory = factory.unwrap(SessionFactory.class);
  }

}

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

Make the console wait for a user input to close

I've put in what x4u said. Eclipse wanted a try catch block around it so I let it generate it for me.

try {
        System.in.read();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It can probably have all sorts of bells and whistles on it but I think for beginners that want a command line window not quitting this should be fine.

Also I don't know how common this is (this is my first time making jar files), but it wouldn't run by itself, only via a bat file.

java.exe -jar mylibrary.jar

The above is what the bat file had in the same folder. Seems to be an install issue.

Eclipse tutorial came from: http://eclipsetutorial.sourceforge.net/index.html

Some of the answer also came from: Oracle Thread

CSV in Python adding an extra carriage return, on Windows

You have to add attribute newline="\n" to open function like this:

with open('file.csv','w',newline="\n") as out:
    csv_out = csv.writer(out, delimiter =';')

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

CSS performance relative to translateZ(0)

CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and z-index values are likely to get screwed with.

If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.

So basically, don't do that. Apply a 3D transformation only when you need the optimization. -webkit-font-smoothing: antialiased; is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.

How to make a drop down list in yii2?

This is about generating data, and so is more properly done from the model. Imagine if you ever wanted to change the way data is displayed in the drop-down box, say add a surname or something. You'd have to find every drop-down box and change the arrayHelper. I use a function in my models to return the data for a dropdown, so I don't have to repeat code in views. It also has the advantage that I can specify filter here and have them apply to every dropdown created from this model;

/* Model Standard.php */

public function getDropdown(){
      return ArrayHelper::map(self::find()->all(), 's_id', 'name'));
}

You can use this in your view file like this;

echo $form->field($model, 'attribute')
        ->dropDownList(
            $model->dropDown
        );

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You have an error in you script tag construction, this:

<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

Should look like this:

<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.

UPDATE

But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

Setting the correct encoding when piping stdout in Python

I could "automate" it with a call to:

def __fix_io_encoding(last_resort_default='UTF-8'):
  import sys
  if [x for x in (sys.stdin,sys.stdout,sys.stderr) if x.encoding is None] :
      import os
      defEnc = None
      if defEnc is None :
        try:
          import locale
          defEnc = locale.getpreferredencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.getfilesystemencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.stdin.encoding
        except: pass
      if defEnc is None :
        defEnc = last_resort_default
      os.environ['PYTHONIOENCODING'] = os.environ.get("PYTHONIOENCODING",defEnc)
      os.execvpe(sys.argv[0],sys.argv,os.environ)
__fix_io_encoding() ; del __fix_io_encoding

Yes, it's possible to get an infinite loop here if this "setenv" fails.

Convert float to std::string in C++

This tutorial gives a simple, yet elegant, solution, which i transcribe:

#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline std::string stringify(double x)
{
  std::ostringstream o;
  if (!(o << x))
    throw BadConversion("stringify(double)");
  return o.str();
}
...
std::string my_val = stringify(val);