Programs & Examples On #Setting

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

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

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

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

vagrant primary box defined but commands still run against all boxes

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

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

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

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.

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

After upgrading to Xcode 12 I was still able to build for a real device, but not the simulator. The Podfile build was working only for the real device.

I deleted VALID_ARCHS under Build Settings > User-Defined and it worked! Bashing my head for some time before finding this.

IntelliJ: Error:java: error: release version 5 not supported

I've done most things you are proposing with Java compiler and bytecode and solved the problem in the past. It's been almost 1 month since I ran my Java code (and back then everything was fixed), but now the problem appeared again. Don't know why, pretty annoyed though!

This time the solution was: Right click to project name -> Open module settings F4 -> Language level ...and there you can define the language level your project/pc is.

No maven/pom configuration worked for me both in the past and now and I've already set the Java compiler and bytecode at 12.

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

Make sure You have the latest version of webdriver-manager. You can install the same using npm i webdriver-manager@latest --save

Then run the following

command.webdriver-manager update

How to use callback with useState hook in react

setState(updater, callback) for useState

Following implementation comes really close to the original setState callback from classes.

Additions made to Robin's solution:

  1. Callback execution is omitted on initial render (we want to call it only on state updates)
  2. Callback can be dynamic for each setState invocation, like with classes

Usage

const App = () => {
  const [state, setState] = useStateCallback(0); // same API as useState + setState with cb

  const handleClick = () => {
    setState(
      prev => prev + 1,
      // 2nd argument is callback , `s` is *updated* state
      s => console.log("I am called after setState, state:", s)
    );
  };

  return <button onClick={handleClick}>Increment</button>;
}

useStateCallback

function useStateCallback(initialState) {
  const [state, setState] = useState(initialState);
  const cbRef = useRef(null); // mutable ref to store current callback

  const setStateCallback = useCallback((state, cb) => {
    cbRef.current = cb; // store passed callback to ref
    setState(state);
  }, []);

  useEffect(() => {
    // cb.current is `null` on initial render, so we only execute cb on state *updates*
    if (cbRef.current) {
      cbRef.current(state);
      cbRef.current = null; // reset callback after execution
    }
  }, [state]);

  return [state, setStateCallback];
}

Further info: React Hooks FAQ: Is there something like instance variables?

Working example

_x000D_
_x000D_
const App = () => {
  const [state, setState] = useStateCallback(0);

  const handleClick = () =>
    setState(
      prev => prev + 1,
      // important: use `s`, not the stale/old closure value `state`
      s => console.log("I am called after setState, state:", s)
    );

  return (
    <div>
      <p>Hello Comp. State: {state} </p>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

function useStateCallback(initialState) {
  const [state, setState] = useState(initialState);
  const cbRef = useRef(null);

  const setStateCallback = useCallback((state, cb) => {
    cbRef.current = cb; 
    setState(state);
  }, []);

  useEffect(() => {
    if (cbRef.current) {
      cbRef.current(state);
      cbRef.current = null;
    }
  }, [state]);

  return [state, setStateCallback];
}

ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Error: Java: invalid target release: 11 - IntelliJ IDEA

I added these two lines to build.gradle file

compileJava.options.fork = true
                                              
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk-11.0.8'

and it works

I am using windows and my project based on gradle

my jdk path -> 'C:\Program Files\Java\jdk-11.0.8'

please provide your jdk path

Git fatal: protocol 'https' is not supported

Just use double quotes with URL, like: git clone "https://yourRepoUrl"

(It somehow sees that you are using 2 quote marks on start, don't know why).

I was getting the same error => fatal: protocol ''https' is not supported (you can see 2 quote marks on https).

Pylint "unresolved import" error in Visual Studio Code

I have one library which errs out when trying to include it using the Jedi language service and works fine without it (i.e. the C# one).

The library is jsonslicer and it does depend on an external C library I installed into /usr/local/lib. Could that have something to do with it?

I installed the Jedi service and the library in my Conda environment and used that environment within Visual Studio. It works fine at runtime and in my terminal, but not when checking for problems in my source files and it shows up as an error.

React hooks useState Array

Try to keep your state minimal. There is no need to store

   const initialValue = [
    { id: 0,value: " --- Select a State ---" }];

as state. Separate the permanent from the changing

const ALL_STATE_VALS = [
    { id: 0,value: " --- Select a State ---" }
    { id: 1, value: "Alabama" },
    { id: 2, value: "Georgia" },
    { id: 3, value: "Tennessee" }
];

Then you can store just the id as your state:

const StateSelector = () =>{
  const [selectedStateOption, setselectedStateOption] = useState(0);

  return (
    <div>
      <label>Select a State:</label>
      <select>
        {ALL_STATE_VALS.map((option, index) => (
          <option key={option.id} selected={index===selectedStateOption}>{option.value}</option>
        ))}
      </select>
    </div>);
   )
}

HTTP Error 500.30 - ANCM In-Process Start Failure

If you are using Visual Studio, and have any instances of it running, close them all.

You should find a .vs sub folder where your Visual Studio solution (.sln file) resides.
Delete the .vs folder and try again with the in-process hosting model.

ImageMagick security policy 'PDF' blocking conversion

Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:

sudo apt install img2pdf

Convert one or more images to pdf:

img2pdf img.jpg -o output.pdf

It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

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

I hope it will help someone else.

This error seems to occur also when you UNintentionally send an object to React child components.

Example of it is passing to child component new Date('....') as follows:

 const data = {name: 'ABC', startDate: new Date('2011-11-11')}
 ...
 <GenInfo params={data}/>

If you send it as value of a child component parameter you would be sending a complex Object and you may get the same error as stated above.

Check if you are passing something similar (that generates Object under the hood).

Xcode 10: A valid provisioning profile for this executable was not found

Make sure the provisionning profile comes from the same team in both your target and your targetTests.

Support for the experimental syntax 'classProperties' isn't currently enabled

First install the: @babel/plugin-proposal-class-properties as dev dependency:

npm install @babel/plugin-proposal-class-properties --save-dev

Then edit your .babelrc so it will be exact like this:

{
  "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
  ],
  "plugins": [
      [
        "@babel/plugin-proposal-class-properties"
      ]
  ]
}

.babelrc file located in the root directory, where package.json is.

Note that you should re-start your webpack dev server to changes take affect.

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(...);
}

Xcode couldn't find any provisioning profiles matching

Try to check Signing settings in Build settings for your project and target. Be sure that code signing identity section has correct identities for Debug and Release.

image description here

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

For spring boot version 2.X.X below configuration worked for me.

spring.datasource.url=jdbc:mysql://localhost:3306/rest
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update 

Old jdbc driver is deprecated. The new one is mentioned on above configuration. Please use the same and restart the project.

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

Flutter: Setting the height of the AppBar

You can use PreferredSize and flexibleSpace for it:

appBar: PreferredSize(
  preferredSize: Size.fromHeight(100.0),
  child: AppBar(
    automaticallyImplyLeading: false, // hides leading widget
    flexibleSpace: SomeWidget(),
  )
),

This way you can keep the elevation of AppBar for keeping its shadow visible and have custom height, which is what I was just looking for. You do have to set the spacing in SomeWidget, though.

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

In react native, I had the error not show maps and close app, run adb logcat and show error within console:

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

fix it by adding within androidManifest.xml

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

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

The connection string format must be mongodb://user:password@host:port/db

For example:

MongoClient.connect('mongodb://user:[email protected]:27017/yourDB', { useNewUrlParser: true } )

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

If the ALTER USER ... command line doesn't work for you AND if you are using Windows 10 then try to follow those steps:

1) Type MySQL in the windows search bar

2) Open the MySQL Windows Installer - Community

3) Look for "MySQL server" and click on Reconfigure step 3

4) Click on "Next" until you reach the "Authentification Method" phase

5) On the "Authentification Method" phase check the second option "Use Legacy Authentication Method" step 5

6) Then follow the steps given by the Windows installer until the end

7) When it's done, go into "Services" from the Windows search bar, click on "start" MySql81".

Now, try again, the connection between MySQL and Node.js should work!

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

In my case there was a need for:

@Injectable({
    providedIn: 'root'  // <- ADD THIS
})
export class FooService { ...

instead of just:

@Injectable()
export class FooService { ...

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

For those who are looking for an explanation about jest --runInBand, you can go to the documentation.

Running Puppeteer in CI environments

GitHub - smooth-code/jest-puppeteer: Run your tests using Jest & Puppeteer

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

I ran into this problem when I simply mistyped my jdbc url in application.properties. Hope this helps someone: before:

spring.datasource.url=jdbc://localhost:3306/test

after:

spring.datasource.url=jdbc:mysql://localhost:3306/test

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

Had the same issue while working on an application with several modules, check to make sure as you increase the compileSdkVersion and targetSdkVersion to 28+ values in a module you also do for the others.

A module was running on compileSdkVersion 29 and targetSdkVersion 29 while a second module of the application was running on compileSdkVersion 27 and targetSdkVersion 27.

Changing the second module to also compile for and target SDK version 29 resolved my issue. Hope this helps someone.

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

I am using php7.2 and the size is set to memory_limit = 512M by default. to increase the size, you need to locate php.ini.

In Wamp, it is located in C:\wamp64\bin\php\php7.2.23\php.ini. Please watch out for the PHP version as it is the name folder, in my case I have php7.2.23

In Laragon, it is located in C:\laragon\bin\php\php-7.2.23-Win32-VC15-x64\php.ini as was in my case.

If you don't want to allow unlimited space, you can set whatever size that is convenient to you, in my case I did memory_limit = 2G

if you want to allow unlimited space, you can change to memory_limit = -1

error: resource android:attr/fontVariationSettings not found

try to change the compileSdkVersion to:

compileSdkVersion 28

fontVariationSettings added in api level 28. Api doc here

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I'm using Studio 3.3.1 Build from Jan 28.

For me I was getting the "error android resource linking failed" pointing to a line in a layout file using ConstraintLayout that had been working correctly until today when the only change to my app level gradle file was to update the versions of:

android.arch.navigation:navigation-fragment
android.arch.navigation:navigation-ui

from 1.0.0-rc01 to 1.0.0-rc02.

The error message said something about not recognizing layout_constraintTop_toTopOf which of course is silly because it had been compiling quite happily for months.

I am already on 28.0.3 of build tools and compileSdkVersion of 28. I've been using androidx.appcompat everywhere for a while now (converted this project months back to androidx).

I first went through a project clean (no help), and invalidating cache/restart (no help). The layout in question had been originally defined using

<TextView>, <EditText> and <ImageView> components (which had been working fine until today).

But after reading the above answers I thought maybe somehow there was confusion being caused here so I changed the layout to use:

<androidx.appcompat.widget

versions of all the various components. No change - still got the error.

I then deleted the <androidx.appcompat.widget.AppCompatTextView block that was causing the compilation error. I changed all references to it in the other widgets to refer to "parent" instead. Did a Make. This time the compile completed without error.

So something strange in that widget definition I thought....here is what it was:

<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/contact_firstname_label"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="@string/contact_fname_label"
    android:gravity="end"
    android:textAppearance="@android:style/TextAppearance.Material.Small"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/contact_detail_fname"
    app:layout_constraintBaseline_toBaselineOf="@+id/contact_detail_fname"/>

I then pasted back the block I had Ctrl-V cut previously and changed the references back to that ID in the other components that reference it in the layout. Compile failed.

I cut the block again and pasted it to WordPad. Then reading from the WordPad paste, I actually typed it back in (i.e. I didn't copy/paste this time) - line by line, doing a make on the project after I typed in the minimal definition, and then again thereafter when I put in each new line. Each time the project compiled cleanly!

I don't know what to make of this. Perhaps some spurious invisible character was in the file originally?

How to remove whitespace from a string in typescript?

Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

This helped my project to build, add this to module build.gradle file:

compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
        kotlinOptions {
            jvmTarget = "1.8"
        }
    }

VSCode single to double quote automatic replace

Correct solution :

I add .prettierrc.js file in my main root project and write

module.exports = {
    singleQuote: true
  };

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

You must use a .ts file - e.g. test.ts to get Typescript validation, intellisense typing of vars, return types, as well as "typed" error checking (e.g. passing a string to a method that expects an number param will error out).

It will be transpiled into (standard) .js via tsc.


Update (11/2018):

Clarification needed based on down-votes, very helpful comments and other answers.

types

  • Yes, you can do type checking in VS Code in .js files with @ts-check - as shown in the animation

  • What I originally was referring to for Typescript types is something like this in .ts which isn't quite the same thing:

    hello-world.ts

    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    This will not compile. Error: Type "1" is not assignable to String

  • if you tried this syntax in a Javascript hello-world.js file:

    //@ts-check
    
    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file

If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.

where is create-react-app webpack config and files?

Try ejecting the config files, by running:

npm run eject

then you'll find a config folder created in your project. You will find your webpack config files init.

Issue in installing php7.2-mcrypt

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

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

$ sudo apt-get install php-pear

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

sh: phpize: not found

ERROR: `phpize’ failed

$ sudo apt-get install php7.2-dev

  • Install mcrypt using pecl:

$ sudo pecl install mcrypt-1.0.1

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

$ sudo php -i | grep 'Configuration File'

Stylesheet not loaded because of MIME-type

If you are setting Styles in JavaScript as:

    var cssLink = document.createElement("link");
    cssLink.href = "./content.component.scss";
    cssLink.rel = "stylesheet";
   --> cssLink.type = "html/css";
    (iframe as HTMLIFrameElement).contentDocument.head.appendChild(cssLink);

Then just change cssLint.type (denoted by arrow in above description) to "MIME":

   cssLink.type = "MIME";

It will help you to get rid of the error.

How to configure "Shorten command line" method for whole project in IntelliJ

Thanks to Rajesh Goel in Android Studio:

Run > Edit Configurations...

enter image description here

Select a test (better to select a parent test class) and set a Shorten command line: option to classpath file. Then OK (or Apply, OK).

enter image description here

How to access Anaconda command prompt in Windows 10 (64-bit)

To create Anaconda Prompt using Command Prompt, just create a shortcut file of Command Prompt and modify the shortcut target to:

%windir%\System32\cmd.exe "/K" <Anaconda Location>\anaconda3\Scripts\activate.bat

Example:

%windir%\system32\cmd.exe "/K" C:\Users\user_1\AppData\Local\Continuum\anaconda3\Scripts\activate.bat

"Could not get any response" response when using postman with subdomain

You mentioned you are using a CER certificate.

According to the Postman page on certificates.

Choose your client certificate file in the CRT file field. Currently, we only support the CRT format. Support for other formats (like PFX) will come soon.

The name of the extension CER, CRT doesn't make the certificate that type of certificate but, these are the excepted extensions names.

CER is an X.509 certificate in binary form, DER encoded.

CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.

You can use OpenSSL to change a CER file into a CRT file. I have not had good luck with it but it looks like this.

openssl x509 -inform PEM -in certificate.cer -out certificate.crt

or

openssl x509 -inform DER -in certificate.cer -out certificate.crt

axios post request to send form data

i needed to calculate the content length aswell

const formHeaders = form.getHeaders();
formHeaders["Content-Length"] = form.getLengthSync()

const config = {headers: formHeaders}

return axios.post(url, form, config)
.then(res => {
    console.log(`form uploaded`)
})

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

I installed System.Configuration.ConfigurationManager from Nuget into my .net core 2.2 application.

I then reference using System.Configuration;

Next, I changed

WebConfigurationManager.AppSettings

to ..

ConfigurationManager.AppSettings

So far I believe this is correct. 4.5.0 is typical with .net core 2.2

I have not had any issues with this.

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

Your android studio may be forgot to put : buildToolsVersion "26.0.0" you need 'buildTools' to develop related design and java file. And if there is no any buildTools are installed in Android->sdk->build-tools directory then download first.

Angular Material: mat-select not selecting default

My solution is little tricky and simpler.

<div>
    <mat-select
        [placeholder]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

I just made use of the placeholder. The default color of material placeholder is light gray. To make it look like the option is selected, I just manipulated the CSS as follows:

::ng-deep .mat-select-placeholder {
    color: black;
}

Angular 5 Service to read local .json file

I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".

Just call require:

const content = require('../../path_of_your.json');

The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl property by template and the value by a require call to the actual HTML resource.

If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json:

"compilerOptions": {
  "types": ["node"],
  ...
},
...

Getting value from appsettings.json in .net core

In the constructor of Startup class, you can access appsettings.json and many other settings using the injected IConfiguration object:

Startup.cs Constructor

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;

        //here you go
        var myvalue = Configuration["Grandfather:Father:Child"];

    }

public IConfiguration Configuration { get; }

Contents of appsettings.json

  {
  "Grandfather": {
    "Father": {
      "Child": "myvalue"
    }
  }

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

In terminal, log into MySQL as root. You may have created a root password when you installed MySQL for the first time or the password could be blank, in which case you can just press ENTER when prompted for a password.

 sudo mysql -p -u root

Now add a new MySQL user with the username of your choice. In this example we are calling it pmauser (for phpmyadmin user). Make sure to replace password_here with your own. You can generate a password here. The % symbol here tells MySQL to allow this user to log in from anywhere remotely. If you wanted heightened security, you could replace this with an IP address.

CREATE USER 'pmauser'@'%' IDENTIFIED BY 'password_here';

Now we will grant superuser privilege to our new user.

GRANT ALL PRIVILEGES ON *.* TO 'pmauser'@'%' WITH GRANT OPTION;

Then go to config.inc.php ( in ubuntu, /etc/phpmyadmin/config.inc.php )

/* User for advanced features */

$cfg['Servers'][$i]['controluser'] = 'pmauser'; 
$cfg['Servers'][$i]['controlpass'] = 'password_here';

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

Hello If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

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

You can make use of environment variables and the ConfigurationBuilder class in your Startup constructor like this:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();
    this.configuration = builder.Build();
}

Then you create an appsettings.xxx.json file for every environment you need, with "xxx" being the environment name. Note that you can put all global configuration values in your "normal" appsettings.json file and only put the environment specific stuff into these new files.

Now you only need an environment variable called ASPNETCORE_ENVIRONMENT with some specific environment value ("live", "staging", "production", whatever). You can specify this variable in your project settings for your development environment, and of course you need to set it in your staging and production environments also. The way you do it there depends on what kind of environment this is.

UPDATE: I just realized you want to choose the appsettings.xxx.json based on your current build configuration. This cannot be achieved with my proposed solution and I don't know if there is a way to do this. The "environment variable" way, however, works and might as well be a good alternative to your approach.

Xcode 9 Swift Language Version (SWIFT_VERSION)

This Solution works when nothing else works:

I spent more than a week to convert the whole project and came to a solution below:

First, de-integrate the cocopods dependency from the project and then start converting the project to the latest swift version.

Go to Project Directory in the Terminal and Type:

pod deintegrate

This will de-integrate cocopods from the project and No traces of CocoaPods will be left in the project. But at the same time, it won't delete the xcworkspace and podfiles. It's ok if they are present.

Now you have to open xcodeproj(not xcworkspace) and you will get lots of errors because you have called cocoapods dependency methods in your main projects.

So to remove those errors you have two options:

  1. Comment down all the code you have used from cocoapods library.
  2. Create a wrapper class which has dummy methods similar to cocopods library, and then call it.

Once all the errors get removed you can convert the code to the latest swift version.

Sometimes if you are getting weird errors then try cleaning derived data and try again.

Set cookies for cross origin requests

For express, upgrade your express library to 4.17.1 which is the latest stable version. Then;

In CorsOption: Set origin to your localhost url or your frontend production url and credentials to true e.g

  const corsOptions = {
    origin: config.get("origin"),
    credentials: true,
  };

I set my origin dynamically using config npm module.

Then , in res.cookie:

For localhost: you do not need to set sameSite and secure option at all, you can set httpOnly to true for http cookie to prevent XSS attack and other useful options depending on your use case.

For production environment, you need to set sameSite to none for cross-origin request and secure to true. Remember sameSite works with express latest version only as at now and latest chrome version only set cookie over https, thus the need for secure option.

Here is how I made mine dynamic

 res
    .cookie("access_token", token, {
      httpOnly: true,
      sameSite: app.get("env") === "development" ? true : "none",
      secure: app.get("env") === "development" ? false : true,
    })

How do you set the document title in React?

Simply you can create a function in a js file and export it for usages in components

like below:

export default function setTitle(title) {
  if (typeof title !== "string") {
     throw new Error("Title should be an string");
  }
  document.title = title;
}

and use it in any component like this:

import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end

class App extends Component {
  componentDidMount() {
    setTitle("i am a new title");
  }

  render() {
    return (
      <div>
        see the title
      </div>
    );
  }
}

export default App

Angular 4 setting selected option in Dropdown

Remove [selected] from option tag:

<option *ngFor="let opt of question.options" [value]="opt.key">
  {{opt.selected+opt.value}}
</option>

And in your form builder add:

key: this.question.options.filter(val => val.selected === true).map(data => data.key)

How to specify credentials when connecting to boto3 S3?

I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI to create a config file. The reason is, with the config file, the CLI or the SDK will automatically look for credentials in the ~/.aws folder. And the good thing is that AWS CLI is written in python.

You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After this you can access boto and any of the api without having to specify keys (unless you want to use a different credentials).

Android 8: Cleartext HTTP traffic not permitted

adding this paramter in header resolved my issue in apiSauce React Native

"Content-Type": "application/x-www-form-urlencoded",
  Accept: "application/json"

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

  1. Add the following code into startup.cs file.

    public void ConfigureServices(IServiceCollection services)
    {
        string con = Configuration.GetConnectionString("DBConnection");
        services.AddMvc();
        GlobalProperties.DBConnection = con;//DBConnection is a user defined static property of GlobalProperties class
    }
    
  2. Use GlobalProperties.DBConnection property in Context class.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {  
              optionsBuilder.UseSqlServer(GlobalProperties.DBConnection);
        }
    }
    

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

You will need to add external Repository to your pom, since this is using Mulsoft-Release repository not Maven Central

<project>
   ...
    <repositories>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>
  ...
</project>

Dependency

Apache Maven - Setting up Multiple Repositories

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

$cfg['Servers'][$i]['auth_type'] = 'HTTP';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '1234';

This solves my problem too. It just logs in automatically.

ESLint not working in VS Code?

In my case, I had the .eslintrc.json file inside the .vscode folder. Once I moved it out to the root folder, ESLint started working correctly.

Using app.config in .Net Core

  1. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.

    Note: don't be confused when someone says that config file should be appsettings.json. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.

    But, as the real world is complicated, there are a lot of different configuration providers:

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables

    and so on. You even could use/write a custom provider.

  3. Actually, app.config configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

With Hooks and useState

Use defaultValue to select the default value.

    const statusOptions = [
        { value: 1, label: 'Publish' },
        { value: 0, label: 'Unpublish' }
    ];
    const [statusValue, setStatusValue] = useState('');
    const handleStatusChange = e => {
        setStatusValue(e.value);
    }

return(
<>
<Select options={statusOptions} 
    defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]} 
    onChange={handleStatusChange} 
    value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

Hide header in stack navigator React navigation

 <Stack.Screen
    name="SignInScreen"
    component={Screens.SignInScreen}
    options={{ headerShown: false }}
  />

options={{ headerShown: false }} works for me.

** "@react-navigation/native": "^5.0.7", "@react-navigation/stack": "^5.0.8",

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

My JDK is installed at C:\Program Files\Java\jdk1.8.0_144\.
I had set JAVA_HOME= C:\Program Files\Java\jdk1.8.0_144\, and I was getting this error:

The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

When I changed the JAVA_HOME to C:\Program Files\Java\jdk1.8.0_144\jre, the issue got fixed.
I am not sure how.

What is a 'workspace' in Visual Studio Code?

If the Visual Studio Code is a fresh installation;

  1. Click on extensions, Search for "python" and click on install

  2. Click on view -> explorer If there in no folder added a folder to the Workspace (File->Add folder to Workspace)

  3. If you want to use a virtual python environment, Click on File -> Preference -> settings

Click on "{} open settings JSON" which is in top right corner of the window, then add the path to python.exe file which is in the virtual environment

{
    "python.pythonPath": "C:\\PathTo\\VirtualENV\\python.exe"
}
  1. Start a new terminal and check the correct python interpreter is selected

How to assign more memory to docker container

Allocate maximum memory to your docker machine from (docker preference -> advance )

Screenshot of advance settings: Screenshot of advance settings.

This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.

docker run -m=4g {imageID}

Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

Setting up Gradle for api 26 (Android)

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.keshav.retroft2arrayinsidearrayexamplekeshav"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
 compile 'com.android.support:appcompat-v7:26.0.1'
    compile 'com.android.support:recyclerview-v7:26.0.1'
    compile 'com.android.support:cardview-v7:26.0.1'

Show/hide widgets in Flutter programmatically

Update

Flutter now has a Visibility widget. To implement your own solution start with the below code.


Make a widget yourself.

show/hide

class ShowWhen extends StatelessWidget {
  final Widget child;
  final bool condition;
  ShowWhen({this.child, this.condition});

  @override
  Widget build(BuildContext context) {
    return Opacity(opacity: this.condition ? 1.0 : 0.0, child: this.child);
  }
}

show/remove

class RenderWhen extends StatelessWidget {
  final Widget child;
  final bool condition;
  RenderWhen({this.child, this.show});

  @override
  Widget build(BuildContext context) {
    return this.condition ? this.child : Container();
  }
}

By the way, does any one have a better name for the widgets above?

More Reads

  1. Article on how to make a visibility widget.

How to enable CORS in ASP.net Core WebAPI

The solution that worked for me in ASP.NET Core 3.1:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader());
            });
            services.AddControllersWithViews();
        }

and then change the following:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors("CorsPolicy");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Then program worked and error was solved.

Run bash command on jenkins pipeline

If you want to change your default shell to bash for all projects on Jenkins, you can do so in the Jenkins config through the web portal:

Manage Jenkins > Configure System (Skip this clicking if you want by just going to https://{YOUR_JENKINS_URL}/configure.)

Fill in the field marked 'Shell executable' with the value /bin/bash and click 'Save'.

How to send authorization header with axios

Rather than adding it to every request, you can just add it as a default config like so.

axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}` 

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

VirtualBox Cannot register the hard disk already exists

I found a solution

File -> Virtual Media Manager -> Removed existing images (note, I removed them only from the registry).

I followed these steps.

http://www.webdesignblog.asia/software/virtualbox-moving-vdi-file-re-linking-guest/#sthash.1QOHeiw5.dpbs

After that I could update the path in the VM settings.

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Since Django 2.0 the ForeignKey field requires two positional arguments:

  1. the model to map to
  2. the on_delete argument
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)

Here are some methods can used in on_delete

  1. CASCADE

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey

  1. PROTECT

Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

  1. DO_NOTHING

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

you can find more about on_delete by reading the documentation.

How to print a Groovy variable in Jenkins?

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

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

I k now the question has already been answered. But if this helps somebody save some time : I had the same error. I checked everything to find a very small and stupid mistake from my side. I imported a core data ManagedObject custom file in a view controller of my project. I accidentally imported the .m file instead of the .h file which was causing the duplicate symbol in architecture error (linker command failed) because my .m file of properties class imports the .h file of core data class and hence causing duplicate import.

So just check if u have imported the right files before you try multiple solutions.!

Visual Studio Code pylint: Unable to import 'protorpc'

I resolved this by adding the protorpc library to the $PYTHONPATH environment variable. Specifically, I pointed to the library installed in my App Engine directory:

export PYTHONPATH=$PYTHONPATH:/Users/jackwootton/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0

After adding this to ~/.bash_profile, restarting my machine and Visual Studio Code, the import errors went away.

For completeness, I did not modify any Visual Studio Code settings relating to Python. Full ~/.bash_profile file:

export PATH=/Users/jackwootton/protoc3/bin:$PATH

export PYTHONPATH=/Users/jackwootton/google-cloud-sdk/platform/google_appengine

export PYTHONPATH=$PYTHONPATH:/Users/jackwootton/google-cloud-sdk/platform/google_appengine/lib/protorpc-1.0

# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/jackwootton/google-cloud-sdk/path.bash.inc' ]; then source '/Users/jackwootton/google-cloud-sdk/path.bash.inc'; fi

# The next line enables shell command completion for gcloud.
if [ -f '/Users/jackwootton/google-cloud-sdk/completion.bash.inc' ]; then source '/Users/jackwootton/google-cloud-sdk/completion.bash.inc'; fi

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

in component:

formData.form.controls['email'].setErrors({'incorrect': true});

and in HTML:

<input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email"  #email="ngModel">
<div *ngIf="!email.valid">{{email.errors| json}}</div>

Trying to use fetch and pass in mode: no-cors

The simple solution: Add the following to the very top of the php file you are requesting the data from.

header("Access-Control-Allow-Origin: *");

App.settings - the Angular way?

I find this Angular How-to: Editable Config Files from Microsoft Dev blogs being the best solution. You can configure dev build settings or prod build settings.

CSS hide scroll bar, but have element scrollable

You can hide it :

html {
  overflow:   scroll;
}
::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* make scrollbar transparent */
}

For further information, see : Hide scroll bar, but while still being able to scroll

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Core-js did not work for me as it caused other issues, however, simply installing the latest version of npm i @types/es6-promise --save-dev got rid of the issues. The issues for me stemmed from compiling an sdk that was using rxjs. Here is the error I was getting:

`node_modules/rxjs/Observable.d.ts(59,60): error TS2693: Promise only refers to a type, but is being used as a value here.`

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

First of all, please remove the "{Not using Genymotion}" from the title. It distracts readers like me who don't know what Genymotion is. The absurd here is that you got the second highest voted answer with currently 90 points which says "go to GenyMotion settings"...

The main point that all the others have missed, is that you will get this error when you have a running adb process in the background. So the first step is to find it and kill it:

ps aux | grep adb
user          46803   0.0  0.0  2442020    816 s023  S+    5:07AM   0:00.00 grep adb
user          46636   0.0  0.0   651740   3084   ??  S     5:07AM   0:00.02 adb -P 5037 fork-server server

When you find it, you can kill it using kill -9 46636.

In my case, the problem was an old version of adb coming from GapDebug. If you got this with GapDebug, get out of it and then do

adb kill-server
adb start-server

because with GapDebug in the background, when you kill the adb server, GapDebug will start its own copy immediately, causing the start-server to be ignored

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

My system version: ubuntu 20.04 LTS.

  • I solved this by generate a new MOK and enroll it into shim.

  • Without disable of Secure Boot, although it also really works for me.

  • Simply execute this command and follow what it suggests:

    sudo update-secureboot-policy --enroll-key
    

According to ubuntu's wiki: How can I do non-automated signing of drivers

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

[Vue warn]: Property or method is not defined on the instance but referenced during render

Although some answers here maybe great, none helped my case (which is very similar to OP's error message).

This error needed fixing because even though my components rendered with their data (pulled from API), when deployed to firebase hosting, it did not render some of my components (the components that rely on data).

To fix it (and given you followed the suggestions in the accepted answer), in the Parent component (the ones pulling data and passing to child component), I did:

_x000D_
_x000D_
// pulled data in this life cycle hook, saving it to my store
created() {
  FetchData.getProfile()
    .then(myProfile => {
      const mp = myProfile.data;
      console.log(mp)
      this.$store.dispatch('dispatchMyProfile', mp)
      this.propsToPass = mp;
    })
    .catch(error => {
      console.log('There was an error:', error.response)
    })
}
// called my store here
computed: {
    menu() {
        return this.$store.state['myProfile'].profile
    }
},

// then in my template, I pass this "menu" method in child component
 <LeftPanel :data="menu" />
_x000D_
_x000D_
_x000D_

This cleared that error away. I deployed it again to firebase hosting, and viola!

Hope this bit helps you.

Unit Tests not discovered in Visual Studio 2017

For C++:

As there is no special question for C++ tests, but the topic is very much the same, here is what helped me when I had the trouble with test discovery.

If you have only installed Desktop development with C++, then the solution is to also install Universal Windows Platform development with the optional C++ Universal Windows Platform tools. You can select these in the visual studio web installer.

Afterwards, rebuild your test project and the test discovery should work.

Btw, I created the unit test project in VS2017. It might be important, because some users mentioned, that they had discovery issues in projects, that were migrated from VS2015 to VS2017.

How to set environment variables in PyCharm?

This is what you can do to source an .env (and .flaskenv) file in the pycharm flask/django console. It would also work for a normal python console of course.

  1. Do pip install python-dotenv in your environment (the same as being pointed to by pycharm).

  2. Go to: Settings > Build ,Execution, Deployment > Console > Flask/django Console

  3. In "starting script" include something like this near the top:

    from dotenv import load_dotenv load_dotenv(verbose=True)

The .env file can look like this: export KEY=VALUE

It doesn't matter if one includes export or not for dotenv to read it.

As an alternative you could also source the .env file in the activate shell script for the respective virtual environement.

eslint: error Parsing error: The keyword 'const' is reserved

If using Visual Code one option is to add this to the settings.json file:

"eslint.options": {
    "useEslintrc": false,
    "parserOptions": {
        "ecmaVersion": 2017
    },
    "env": {
        "es6": true
    }
}

How to solve SyntaxError on autogenerated manage.py?

The following could be the possible reasons,

1. The virtual environment is not enabled
2. The virtual environment is enabled but the python version is different

To create virtual environment

$ virtualenv --python=python3 venv

To activate the virtual environment

$ source venv/bin/activate

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.

package com.ajinkya.th.controller;

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  @Controller
  public class HomePageController {

      @RequestMapping("/")
      public String homePage() {
        return "home";
      }

  }

Thats it ! Now restart your gradle server. ./gradlew bootRun

Changing the git user inside Visual Studio Code

from within the vscode terminal,

git remote set-url origin https://<your github username>:<your password>@github.com/<your github username>/<your github repository name>.git

for the quickest, but not so encouraged way.

Job for mysqld.service failed See "systemctl status mysqld.service"

I met this problem today, and fix it with bellowed steps.

1, Check the log file /var/log/mysqld.log

tail -f /var/log/mysqld.log

 2017-03-14T07:06:53.374603Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 2 - No such file or directory)
 2017-03-14T07:06:53.374614Z 0 [ERROR] Can't start server: can't create PID file: No such file or directory

The log says that there isn't a file or directory /var/run/mysqld/mysqld.pid

2, Create the directory /var/run/mysqld

mkdir -p /var/run/mysqld/

3, Start the mysqld again service mysqld start, but still fail, check the log again /var/log/mysqld.log

2017-03-14T07:14:22.967667Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 13 - Permission denied)
2017-03-14T07:14:22.967678Z 0 [ERROR] Can't start server: can't create PID file: Permission denied

It saids permission denied.

4, Grant the permission to mysql chown mysql.mysql /var/run/mysqld/

5, Restart the mysqld

# service mysqld restart
Restarting mysqld (via systemctl):                         [  OK  ]

Color theme for VS Code integrated terminal

Add workbench.colorCustomizations to user settings

"workbench.colorCustomizations": {
  "terminal.background":"#FEFBEC",
  "terminal.foreground":"#6E6B5E",
  ...
}

Check https://glitchbone.github.io/vscode-base16-term for some presets.

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

Is it possible to return empty in react render function?

We can return like this,

return <React.Fragment />;

Could not connect to React Native development server on Android

My solution is modify or make new AndroidManifest.xml in android/app/src/debug:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
</manifest>

I am using React Native version: 0.61.5

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

For the people like myself, who started recently: The loaders keyword is replaced with rules; even though it still represents the concept of loaders. So my webpack.config.js, for a React app, is as follows:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
  entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module : {
    rules : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader'
      }
    ]
  }
};

module.exports = config;

`React/RCTBridgeModule.h` file not found

I ran into this issue after doing a manual react-native link of a dependency which didn't support auto link on RN 0.59+

The solution was to select the xcodeproj file under the Libraries folder in Xcode and then in Build Settings, change Header Search Paths to add these two (recursive):

$(SRCROOT)/../../../ios/Pods/Headers/Public/React-Core
$(SRCROOT)/../../../ios/Pods/Headers/Public

How can I convert a .py to .exe for Python?

The best and easiest way is auto-py-to-exe for sure, and I have given all the steps and red flags below which will take you just 5 mins to get a final .exe file as you don't have to learn anything to use it.

1.) It may not work for python 3.9 on some devices I guess.

2.) While installing python, if you had selected 'add python 3.x to path', open command prompt from start menu and you will have to type pip install auto-py-to-exe to install it. You will have to press enter on command prompt to get the result of the line that you are typing.

3.) Once it is installed, on command prompt itself, you can simply type just auto-py-to-exe to open it. It will open a new window. It may take up to a minute the first time. Also, closing command prompt will close auto-py-to-exe also so don't close it till you have your .exe file ready.

4.) There will be buttons for everything you need to make a .exe file and the screenshot of it is shared below. Also, for the icon, you need a .ico file instead of an image so to convert it, you can use https://convertio.co/

5.) If your script uses external files, you can add them through auto-py-to-exe and in the script, you will have to do some changes to their path. First, you have to write import sys if not written already, second, you have to make a variable for eg, location=getattr(sys,"_MEIPASS",".")+"/", third, the location of example.png would be location+"/example.png" if it is not in any folder.

6.) If it is showing any error, it may probably be because of a module called setuptools not being at the latest version. To upgrade it to the latest version, on command prompt, you will have to write pip install --upgrade setuptools. Also, in the script, writing import setuptools may help. If the version of setuptools is more than 50.0.0 then everything should be fine.

7.) After all these steps, in auto-py-to-exe, when the conversion is complete, the .exe file will be in the folder that you would have chosen (by default, it is 'c:/users/name/output') or it would have been removed by your antivirus if you have one. Every antivirus has different methods to restore a file so just experiment if you don't know.

Here is how the simple GUI of auto-py-to-exe can be used to make a .exe file.

enter image description here

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Other than the options mentioned above, there are a couple of other Solutions.

1. Modifying the project file (.CsProj) file

MSBuild supports the EnvironmentName Property which can help to set the right environment variable as per the Environment you wish to Deploy. The environment name would be added in the web.config during the Publish phase.

Simply open the project file (*.csProj) and add the following XML.

<!-- Custom Property Group added to add the Environment name during publish
  The EnvironmentName property is used during the publish for the Environment variable in web.config
  -->
  <PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
    <EnvironmentName>Development</EnvironmentName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
    <EnvironmentName>Production</EnvironmentName>
  </PropertyGroup>

Above code would add the environment name as Development for Debug configuration or if no configuration is specified. For any other Configuration the Environment name would be Production in the generated web.config file. More details here

2. Adding the EnvironmentName Property in the publish profiles.

We can add the <EnvironmentName> property in the publish profile as well. Open the publish profile file which is located at the Properties/PublishProfiles/{profilename.pubxml} This will set the Environment name in web.config when the project is published. More Details here

<PropertyGroup>
  <EnvironmentName>Development</EnvironmentName>
</PropertyGroup>

3. Command line options using dotnet publish

Additionaly, we can pass the property EnvironmentName as a command line option to the dotnet publish command. Following command would include the environment variable as Development in the web.config file.

dotnet publish -c Debug -r win-x64 /p:EnvironmentName=Development

Why is "npm install" really slow?

I had similar problems. I was also confused by some solutions leaving me with different versions displaying for different users. If you have any problems at all, I would first check every account your using any implementation of node

Finally, this solution appears to solve this issue 100%, giving me the confidence that my versions were universal no matter what user privileges I wanted to use:

    sudo yum update

    sudo yum install build-essential checkinstall libssl-dev

    curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash

    (sudo) nvm --version

    (sudo) nvm ls-remote

    (sudo) nvm install [version.number] 

1

If you're still having a problem, next try looking inside your /usr/local/bin directory. If you find either a large binary document named node or a folder named npm, delete them.

    rm /usr/local/bin/node

    rm -r /usr/local/bin/npm

Personally, before I deleted those, two of my user accounts were using the latest version of node/npm installed correctly via nvm, while a third account of mine remained stubborn by still using a far older installation of both node and npm apparently located inside my /usr/local/bin/ directory. As soon as I deleted both of them with the two above commands, that problematic user account implicitly began running the correct installation, having all three accounts mutually the intended versions.

(Implemented while using Centos 7 Blank x64. Some source code used above was originally supplied by 'phoenixNAP Global IT services' 1)

Using Axios GET with Authorization Header in React-Native App

Could not get this to work until I put Authorization in single quotes:

axios.get(URL, { headers: { 'Authorization': AuthStr } })

ASP.NET Core Get Json Array using IConfiguration

Kind of an old question, but I can give an answer updated for .NET Core 2.1 with C# 7 standards. Say I have a listing only in appsettings.Development.json such as:

"TestUsers": [
  {
    "UserName": "TestUser",
    "Email": "[email protected]",
    "Password": "P@ssw0rd!"
  },
  {
    "UserName": "TestUser2",
    "Email": "[email protected]",
    "Password": "P@ssw0rd!"
  }
]

I can extract them anywhere that the Microsoft.Extensions.Configuration.IConfiguration is implemented and wired up like so:

var testUsers = Configuration.GetSection("TestUsers")
   .GetChildren()
   .ToList()
    //Named tuple returns, new in C# 7
   .Select(x => 
         (
          x.GetValue<string>("UserName"), 
          x.GetValue<string>("Email"), 
          x.GetValue<string>("Password")
          )
    )
    .ToList<(string UserName, string Email, string Password)>();

Now I have a list of a well typed object that is well typed. If I go testUsers.First(), Visual Studio should now show options for the 'UserName', 'Email', and 'Password'.

How to set shadows in React Native for android?

Also i'd like to add that if one's trying to apply shadow in a TouchableHighlight Component in which child has borderRadius, the parent element (TouchableHighlight) also need the radius set in order to elevation prop work on Android.

Adding Lombok plugin to IntelliJ project

You need to Enable Annotation Processing on IntelliJ IDEA

> Settings > Build, Execution, Deployment > Compiler > Annotation Processors

enter image description here

How to correctly set Http Request Header in Angular 2

Angular 4 >

You can either choose to set the headers manually, or make an HTTP interceptor that automatically sets header(s) every time a request is being made.


Manually

Setting a header:

http
  .post('/api/items/add', body, {
    headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
  })
  .subscribe();

Setting headers:

this.http
.post('api/items/add', body, {
  headers: new HttpHeaders({
    'Authorization': 'my-auth-token',
    'x-header': 'x-value'
  })
}).subscribe()

Local variable (immutable instantiate again)

let headers = new HttpHeaders().set('header-name', 'header-value');
headers = headers.set('header-name-2', 'header-value-2');

this.http
  .post('api/items/add', body, { headers: headers })
  .subscribe()

The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.

From the Angular docs.


HTTP interceptor

A major feature of @angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.

From the Angular docs.

Make sure you use @angular/common/http throughout your application. That way your requests will be catched by the interceptor.

Step 1, create the service:

import * as lskeys from './../localstorage.items';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';

@Injectable()
export class HeaderInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (true) { // e.g. if token exists, otherwise use incomming request.
            return next.handle(req.clone({
                setHeaders: {
                    'AuthenticationToken': localStorage.getItem('TOKEN'),
                    'Tenant': localStorage.getItem('TENANT')
                }
            }));
        }
        else {
            return next.handle(req);
        }
    }
}

Step 2, add it to your module:

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HeaderInterceptor,
      multi: true // Add this line when using multiple interceptors.
    },
    // ...
  ]

Useful links:

CR LF notepad++ removal

The best and quick solution to the problem is first do this: View-> Show Symbol-> uncheck Show End of Line

This will solve problem for 90% of you and as in my case CR LF and its combinations still persist in the code. To fix this simply create a new tab using ctrl+n and copy whole file and paste in this new file. All CRLF gone, copy whole file again and go to original file delete whole code and paste the copied save and you rock!!!

Hope this helps.

Setting a checkbox as checked with Vue.js

To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules and each module has a checked property.

The following code will bind the checkbox with that property:

<input type="checkbox" v-model="module.checked" v-bind:id="module.id">

Notice that I removed v-bind:value="module.id". You shouldn't use v-model and v-bind:value on the same element. From the vue docs:

<input v-model="something">

is just syntactic sugar for:

<input v-bind:value="something" v-on:input="something = $event.target.value">

So, by using v-model and v-bind:value, you actually end up having v-bind:value twice, which could lead to undefined behavior.

I get conflicting provisioning settings error when I try to archive to submit an iOS app

For me change Code Signing Identity to all iOS Developer for both of Debug and Release.

And Code Signing Style to Automatic.

enter image description here

Setting and getting localStorage with jQuery

The localStorage can only store string content and you are trying to store a jQuery object since html(htmlString) returns a jQuery object.

You need to set the string content instead of an object. And use the setItem method to add data and getItem to get data.

window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));

Change language of Visual Studio 2017 RC

You need reinstall VS.

Language Pack Support in Visual Studio 2017 RC

Issue:

This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.

Workaround:

These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.

Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016

YouTube Autoplay not working

This code allows you to autoplay iframe video

<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1"  width="560" height="315"  frameborder="0" allowfullscreen></iframe>

Here Is working fiddle

docker cannot start on windows

I am using Windows 7 with Docker Toolbox and to fix it just open Docker Quickstart Terminal.

$ docker version Client: Version: 17.05.0-ce API version: 1.29 Go version: go1.7.5 Git commit: 89658be Built: Fri May 5 15:36:11 2017 OS/Arch: windows/amd64

Server: Version: 17.05.0-ce API version: 1.29 (minimum version 1.12) Go version: go1.7.5 Git commit: 89658be Built: Thu May 4 21:43:09 2017 OS/Arch: linux/amd64 Experimental: false

Selected tab's color in Bottom Navigation View

It's too late to answer but might be helpful for someone. I was doing a very silly mistake, I was using a selector file named as bottom_color_nav.xml for Select and unselect color change but still it was not reflecting any color change in BottomNavigationView.

Then I realize, I was returning false in onNavigationItemSelected method. It will work fine if you'll return true in this method.

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For those who are using xampp:

File -> Preferences -> Settings

"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"

How to set up Automapper in ASP.NET Core

I want to extend @theutz's answers - namely this line :

// services.AddAutoMapper(typeof(Startup));  // <-- newer automapper version uses this signature.

There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)

This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:

services.AddAutoMapper();

unless you explicitly specify which assemblies to search AutoMapper profiles for.

It can be done like this in your Startup.ConfigureServices:

services.AddAutoMapper(<assembies> or <type_in_assemblies>);

where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:

services.AddAutoMapper(typeof(ProfileInOtherAssembly), typeof(ProfileInYetAnotherAssembly));

I suppose (and I put emphasis on this word) that due to following implementation of parameterless overload (source code from GitHub) :

public static IServiceCollection AddAutoMapper(this IServiceCollection services)
{
     return services.AddAutoMapper(null, AppDomain.CurrentDomain.GetAssemblies());
}

we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more details in this StackOverflow question).

Django model "doesn't declare an explicit app_label"

I got this error on importing models in tests, i.e. given this Django project structure:

|-- myproject
    |-- manage.py
    |-- myproject
    |-- myapp
        |-- models.py  # defines model: MyModel
        |-- tests
            |-- test_models.py

in file test_models.py I imported MyModel in this way:

from models import MyModel

The problem was fixed if it is imported in this way:

from myapp.models import MyModel

Hope this helps!

PS: Maybe this is a bit late, but I not found in others answers how to solve this problem in my code and I want to share my solution.

How can I set a cookie in react?

By default, when you fetch your URL, React native sets the cookie.

To see cookies and make sure that you can use the https://www.npmjs.com/package/react-native-cookie package. I used to be very satisfied with it.

Of course, Fetch does this when it does

credentials: "include",// or "some-origin"

Well, but how to use it

--- after installation this package ----

to get cookies:

import Cookie from 'react-native-cookie';

Cookie.get('url').then((cookie) => {
   console.log(cookie);
});

to set cookies:

Cookie.set('url', 'name of cookies', 'value  of cookies');

only this

But if you want a few, you can do it

1- as nested:

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1')
        .then(() => {
            Cookie.set('url', 'name of cookies 2', 'value  of cookies 2')
            .then(() => {
                ...
            })
        })

2- as back together

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1');
Cookie.set('url', 'name of cookies 2', 'value  of cookies 2');
Cookie.set('url', 'name of cookies 3', 'value  of cookies 3');
....

Now, if you want to make sure the cookies are set up, you can get it again to make sure.

Cookie.get('url').then((cookie) => {
  console.log(cookie);
});

How to beautifully update a JPA entity in Spring Data?

I have encountered this issue!
Luckily, I determine 2 ways and understand some things but the rest is not clear.
Hope someone discuss or support if you know.

  1. Use RepositoryExtendJPA.save(entity).
    Example:
    List<Person> person = this.PersonRepository.findById(0) person.setName("Neo"); This.PersonReository.save(person);
    this block code updated new name for record which has id = 0;
  2. Use @Transactional from javax or spring framework.
    Let put @Transactional upon your class or specified function, both are ok.
    I read at somewhere that this annotation do a "commit" action at the end your function flow. So, every things you modified at entity would be updated to database.

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

If Ubuntu try opening All Settings > Network > Network proxy set the method to automatic and save.

Enable VT-x in your BIOS security settings (refer to documentation for your computer)

Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.

Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio I dont no how to do Bios Security

Visual Studio Code: How to show line endings

AFAIK there is no way to visually see line endings in the editor space, but in the bottom-right corner of the window there is an indicator that says "CLRF" or "LF" which will let you set the line endings for a particular file. Clicking on the text will allow you to change the line endings as well.

enter image description here

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

As of ES 7, mapping types have been removed. You can read more details here

If you are using Ruby On Rails this means that you may need to remove document_type from your model or concern.

As an alternative to mapping types one solution is to use an index per document type.

Before:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
    document_type self.name.downcase
  end
end

After:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
  end
end

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

I was having this issue on an Debian 8 VM that I was interacting with through Putty on my Windows 10 desktop.

I tried the various suggestions on here but nothing quite worked and I am running MariaDB on the Debian host. In the end I found that I couldn't start the db server in safe mode but I didn't need to and the following commands actually worked for me i.e. allowing a newly created MySql user to log into the MySql/MariaDB server:

sudo service mysql restart
sudo mysql # logs in automatically into MariaDB
use mysql;
update user set plugin='' where user='your_user_name';
flush privileges;
exit;
sudo service mysql restart # restarts the mysql service

If the above doesn't quite work for you, follow the steps outlined in zetacu's post above (zetacu) then follow my steps.

Now you should be able to use a remote terminal client and securely log into mysql using the command:

mysql -u your_user_name -p

*type in the password when prompted

"CSV file does not exist" for a filename with embedded quotes

Being on jupyter notebook it works for me including the relative path only. For example:

df = pd.read_csv ('file.csv')

But, for example, in vscode I have to put the complete path:

df = pd.read_csv ('/home/code/file.csv')

How do I access Configuration in any class in ASP.NET Core?

I know this is old but given the IOptions patterns is relatively simple to implement:

  1. Class with public get/set properties that match the settings in the configuration

    public class ApplicationSettings
    {
        public string UrlBasePath { get; set; }
    }
    
  2. register your settings

    public void ConfigureServices(IServiceCollection services)
    {
     ...
     services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
    ...
    }
    
  3. inject via IOptions

    public class HomeController
    {
       public HomeController(IOptions<ApplicationSettings> appSettings)
       { ...
        appSettings.Value.UrlBasePath
        ...
        // or better practice create a readonly private reference
        }
     }
    

I'm not sure why you wouldn't just do this.

Disable Chrome strict MIME type checking

Another solution when a file pretends another extension

I use php inside of var.js file with this .htaccess.

<Files var.js>
    AddType application/x-httpd-php .js
</Files>

Then I write php code in the .js file

<?php
// This is a `.js` file but works with php
echo "var js_variable = '$php_variable';";

When I got the MIME type warning on Chrome, I fixed it by adding a Content-Type header line in the .js(but php) file.

<?php
header('Content-Type: application/javascript');        // <- Add this line
// This is a `.js` file but works with php
...

A browser won't execute .js file because apache sends the Content-Type header of the file as application/x-httpd-php that is defined in .htaccess. That's a security reason. But apache won't execute php as far as htaccess commands the impersonation, it's necessary. So we need to overwrite apache's Content-Type header with the php function header(). I guess that apache stops sending its own header when php sends it instead of apache before.

No assembly found containing an OwinStartupAttribute Error

Check you have the correct startup project selected. I had a web api project as startup. That generated this error.

Setting a backgroundImage With React Inline Styles

For a local File in case of ReactJS. Try

import Image from "../../assets/image.jpg";

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
>Hello
</div>

This is the case of ReactJS with inline styling where Image is a local file that you must have imported with a path.

How to register multiple implementations of the same interface in Asp.Net Core?

I didn't have time to read through them all but it seemed everyone was providing solutions to problems that shouldn't exist in the first place.

If you need all of the registered IService implementations then you need them all. But DO NOT inject them all with IEnumerable and then use logic to select one based on some type of key. Problem with doing that is you need a key and the logic should not need to change if the key changes ie; different implementation of IService so typeof doesn't work any more.

The Real Problem

There is business logic here that should be in an engine service. Something like IServiceDecisionEngine is needed. The implementation of the IServiceDecisionEngine gets ONLY the needed IService implementations from DI. Like

public class ServiceDecisionEngine<SomeData>: IServiceDecisionEngine<T> 
{
    public ServiceDecisionEngine(IService serviceA, IService serviceB) { }

    public IService ResolveService(SomeData dataNeededForLogic)
    {
        if (dataNeededForLogic.someValue == true) 
        { 
            return serviceA;
        } 
        return serviceB;
    }
}

Now in your DI, you can do .AddScoped<IServiceDecisionEngine<SomeData>, new ServiceDecisionEngine(new ServiceA(), new ServiceB()) and the managerService that needs an IService will get it by injecting and using IServiceDecisionEngine.

How to read connection string in .NET Core?

ASP.NET Core (in my case 3.1) provides us with Constructor injections into Controllers, so you may simply add following constructor:

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    private readonly IConfiguration m_config;

    public TestController(IConfiguration config)
    {
        m_config = config;
    }

    [HttpGet]
    public string Get()
    {
        //you can get connection string as follows
        string connectionString = m_config.GetConnectionString("Default")
    }
}

Here what appsettings.json may look like:

{
    "ConnectionStrings": {
        "Default": "YOUR_CONNECTION_STRING"
        }
}

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

<create-report-card-form [currentReportCardCount]="providerData.reportCards.length" ...
                         ^^^^^^^^^^^^^^^^^^^^^^^^

In your HomeComponent template, you are trying to bind to an input on the CreateReportCardForm component that doesn't exist.

In CreateReportCardForm, these are your only three inputs:

@Input() public reportCardDataSourcesItems: SelectItem[];
@Input() public reportCardYearItems: SelectItem[];
@Input() errorMessages: Message[];

Add one for currentReportCardCount and you should be good to go.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

For this particular case looks like using a directive to dynamically create the component would be a better option. Example:

In the HTML where you want to create the component

<ng-container dynamicComponentDirective [someConfig]="someConfig"></ng-container>

I would approach and design the directive in the following way.

const components: {[type: string]: Type<YourConfig>} = {
    text : TextEditorComponent,
    numeric: NumericComponent,
    string: StringEditorComponent,
    date: DateComponent,
    ........
    .........
};

@Directive({
    selector: '[dynamicComponentDirective]'
})
export class DynamicComponentDirective implements YourConfig, OnChanges, OnInit {
    @Input() yourConfig: Define your config here //;
    component: ComponentRef<YourConfig>;

    constructor(
        private resolver: ComponentFactoryResolver,
        private container: ViewContainerRef
    ) {}

    ngOnChanges() {
        if (this.component) {
            this.component.instance.config = this.config;
            // config is your config, what evermeta data you want to pass to the component created.
        }
    }

    ngOnInit() {
        if (!components[this.config.type]) {
            const supportedTypes = Object.keys(components).join(', ');
            console.error(`Trying to use an unsupported type ${this.config.type} Supported types: ${supportedTypes}`);
        }

        const component = this.resolver.resolveComponentFactory<yourConfig>(components[this.config.type]);
        this.component = this.container.createComponent(component);
        this.component.instance.config = this.config;
    }
}

So in your components text, string, date, whatever - whatever the config you have been passing in the HTML in the ng-container element would be available.

The config, yourConfig, can be the same and define your metadata.

Depending on your config or input type the directive should act accordingly and from the supported types, it would render the appropriate component. If not it will log an error.

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

How do I filter date range in DataTables?

Here is my solution, there is no way to use momemt.js.Here is DataTable with Two DatePickers for DateRange (To and From) Filter.

$.fn.dataTable.ext.search.push(
  function (settings, data, dataIndex) {
    var min = $('#min').datepicker("getDate");
    var max = $('#max').datepicker("getDate");
    var startDate = new Date(data[4]);
    if (min == null && max == null) { return true; }
    if (min == null && startDate <= max) { return true; }
    if (max == null && startDate >= min) { return true; }
    if (startDate <= max && startDate >= min) { return true; }
    return false;
  }
);
  

    

React eslint error missing in props validation

I know this answer is ridiculous, but consider just disabling this rule until the bugs are worked out or you've upgraded your tooling:

/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling

Or disable project-wide in your eslintrc:

"rules": {
  "react/prop-types": "off"
}

How do I get an OAuth 2.0 authentication token in C#

In Postman, click Generate Code and then in Generate Code Snippets dialog you can select a different coding language, including C# (RestSharp).

Also, you should only need the access token URL. The form parameters are then:

grant_type=client_credentials
client_id=abc    
client_secret=123

Code Snippet:

/* using RestSharp; // https://www.nuget.org/packages/RestSharp/ */

var client = new RestClient("https://service.endpoint.com/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=abc&client_secret=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

From the response body you can then obtain your access token. For instance for a Bearer token type you can then add the following header to subsequent authenticated requests:

request.AddHeader("authorization", "Bearer <access_token>");

Setting selected option in laravel form

If anyone is still here, here is my simple version.

<select name="status" class="js-example-basic-single w-100">
              <option value="" @if($brand->status == '') ? selected : null @endif disabled>Choose what to be seen on brand section</option>
              <option value="TA" @if($brand->status == 'TA') ? selected : null @endif>Title Active</option>
              <option value="ITA" @if($brand->status == 'ITA') ? selected : null @endif>Image Title Active</option>
             
            </select>

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I know this is old but this answer still applies to newer Core releases.

If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

Both -s and -p are optionals that default to the current folder.

Experimental decorators warning in TypeScript compilation

"javascript.implicitProjectConfig.experimentalDecorators": true

Will solve this problem.

ImportError: No module named 'encodings'

Because this is the first result in google I just want to add the following information for anybody else having problems with jails:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f079b16d740 (most recent call first):
Aborted (core dumped)

When attempting to import python into your jail you both need to link the dependencies and /usr/lib/pythonX.Y to [JAIL]/usr/lib/. Hope this helps.

How to set <iframe src="..."> without causing `unsafe value` exception?

I ran into this issue as well, but in order to use a safe pipe in my angular module, I installed the safe-pipe npm package, which you can find here. FYI, this worked in Angular 9.1.3, I haven't tried this in any other versions of Angular. Here's how you add it step by step:

  1. Install the package via npm install safe-pipe or yarn add safe-pipe. This will store a reference to it in your dependencies in the package.json file, which you should already have from starting a new Angular project.

  2. Add SafePipeModule module to NgModule.imports in your Angular module file like so:

    import { SafePipeModule } from 'safe-pipe';
    
    @NgModule({
        imports: [ SafePipeModule ]
    })
    export class AppModule { }
    
    
  3. Add the safe pipe to an element in the template for the Angular component you are importing into your NgModule this way:

<element [property]="value | safe: sanitizationType"></element>
  1. Here are some specific examples of the safePipe in an html element:
<div [style.background-image]="'url(' + pictureUrl + ')' | safe: 'style'" class="pic bg-pic"></div>
<img [src]="pictureUrl | safe: 'url'" class="pic" alt="Logo">
<iframe [src]="catVideoEmbed | safe: 'resourceUrl'" width="640" height="390"></iframe>
<pre [innerHTML]="htmlContent | safe: 'html'"></pre>

How to set UICollectionViewCell Width and Height programmatically

So you need to setting from storyboard for attribute for collectionView in cell section estimate Size to none, and in your ViewController you need had delegate method for implementing this method : optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize

Error: Module not specified (IntelliJ IDEA)

For IntelliJ IDEA 2019.3.4 (Ultimate Edition), the following worked for me:

  1. Find the Environment variables for your project.
  2. Specify, from the dropdowns, the values of "Use class path of module:" and "JRE" as in the attached screenshot.

enter image description here

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

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -Uri $url -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

Angular 2 - Setting selected value on dropdown list

I would like to add, [ngValue]="..." support strings, but you need to add simple quotes if it represents a number, like [ngValue]="'...'". It was to complement the Günter Zöchbauer answer.

How to destroy JWT Tokens on logout?

The JWT is stored on browser, so remove the token deleting the cookie at client side

If you need also to invalidate the token from server side before its expiration time, for example account deleted/blocked/suspended, password changed, permissions changed, user logged out by admin, take a look at Invalidating JSON Web Tokens for some commons techniques like creating a blacklist or rotating tokens

No notification sound when sending notification from firebase in android

try this....

  public  void buildPushNotification(Context ctx, String content, int icon, CharSequence text, boolean silent) {
    Intent intent = new Intent(ctx, Activity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1410, intent, PendingIntent.FLAG_ONE_SHOT);

    Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), //large drawable);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(icon)
            .setLargeIcon(bm)
            .setContentTitle(content)
            .setContentText(text)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    if(!silent)
       notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1410, notificationBuilder.build());
    }

and in onMessageReceived, call it

 @Override
public void onMessageReceived(RemoteMessage remoteMessage) {


    Log.d("Msg", "Message received [" + remoteMessage.getNotification().getBody() + "]");

    buildPushNotification(/*your param*/);
}

or follow KongJing, Is also correct as he says, but you can use a Firebase Console.

Registering for Push Notifications in Xcode 8/Swift 3.0?

Take a look at this commented code:

import Foundation
import UserNotifications
import ObjectMapper

class AppDelegate{

    let center = UNUserNotificationCenter.current()
}

extension AppDelegate {

    struct Keys {
        static let deviceToken = "deviceToken"
    }

    // MARK: - UIApplicationDelegate Methods
    func application(_: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

        if let tokenData: String = String(data: deviceToken, encoding: String.Encoding.utf8) {
            debugPrint("Device Push Token \(tokenData)")
        }

        // Prepare the Device Token for Registration (remove spaces and < >)
        setDeviceToken(deviceToken)
    }

    func application(_: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        debugPrint(error.localizedDescription)
    }

    // MARK: - Private Methods
    /**
     Register remote notification to send notifications
     */
    func registerRemoteNotification() {

        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in

            // Enable or disable features based on authorization.
            if granted  == true {

                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            } else {
                debugPrint("User denied the permissions")
            }
        }
    }

    /**
     Deregister remote notification
     */
    func deregisterRemoteNotification() {
        UIApplication.shared.unregisterForRemoteNotifications()
    }

    func setDeviceToken(_ token: Data) {
        let token = token.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
        UserDefaults.setObject(token as AnyObject?, forKey: “deviceToken”)
    }

    class func deviceToken() -> String {
        let deviceToken: String? = UserDefaults.objectForKey(“deviceToken”) as? String

        if isObjectInitialized(deviceToken as AnyObject?) {
            return deviceToken!
        }

        return "123"
    }

    func isObjectInitialized(_ value: AnyObject?) -> Bool {
        guard let _ = value else {
                return false
         }
            return true
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping(UNNotificationPresentationOptions) -> Swift.Void) {

        ("\(notification.request.content.userInfo) Identifier: \(notification.request.identifier)")

        completionHandler([.alert, .badge, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Swift.Void) {

        debugPrint("\(response.notification.request.content.userInfo) Identifier: \(response.notification.request.identifier)")

    }
}

Let me know if there is any problem!

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

You can try these some steps:

Stop Mysql Service 1st sudo /etc/init.d/mysql stop

Login as root without password sudo mysqld_safe --skip-grant-tables &

After login mysql terminal you should need execute commands more:

use mysql;

UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';

flush privileges;

sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown

After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04

Hide strange unwanted Xcode logs

A tweet had the answer for me - https://twitter.com/rustyshelf/status/775505191160328194

To stop the Xcode 8 iOS Simulator from logging like crazy, set an environment variable OS_ACTIVITY_MODE = disable in your debug scheme.

It worked.

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Setting the default active profile in Spring-boot

you can also have multiple listings in the @Profile annotation

@Profile({"dev","default"})

If you set "default" as an additional value, you don't have to specify spring.profiles.active

Connecting to Postgresql in a docker container from outside

To connect from the localhost you need to add '--net host':

docker run --name some-postgres --net host -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres

You can access the server directly without using exec from your localhost, by using:

psql -h localhost -p 5432 -U postgres

How to return a specific status code and no contents from Controller?

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

Use virtualenv with Python with Visual Studio Code in Ubuntu

On Mac OS X using Visual Studio Code version 1.34.0 (1.34.0) I had to do the following to get Visual Studio Code to recognise the virtual environments:

Location of my virtual environment (named ml_venv):

/Users/auser/.pyvenv/ml_venv

auser@HOST:~/.pyvenv$ tree -d -L 2
.
+-- ml_venv
    +-- bin
    +-- include
    +-- lib

I added the following entry in Settings.json: "python.venvPath": "/Users/auser/.pyvenv"

I restarted the IDE, and now I could see the interpreter from my virtual environment:

Enter image description here

Adb install failure: INSTALL_CANCELED_BY_USER

I tried all the steps described above but failed.

Like, connect to the internet with Data connection, Turning off the MIUI optimization and reboot, Turning on Install via USB from Security settings etc.

Then I found a solution.

Steps:

  • Install PlexVPN.
  • set China-Shanghai server
  • Try turning on Install via USB from Developer option.

That's all.

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

Setting width and height

In my case, passing responsive: false under options solved the problem. I'm not sure why everybody is telling you to do the opposite, especially since true is the default.

Set width to match constraints in ConstraintLayout

From the official doc:

Important: MATCH_PARENT is not recommended for widgets contained in a ConstraintLayout. Similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".

So if you want achieve MATCH_PARENT effect, you can do this:

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="TextView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

Visual Studio Code includePath

For everybody that falls off google, in here, this is the fix for VSCode 1.40 (2019):

Open the global settings.json: File > Preferences > Settings

Open the global settings.json: File > Preferences > Settings

Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.

Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.

Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME to your correct system (my case windows) username)
(edit info: There is a problem with the recursion of my approach. VSCode doesn't like multiple definitions for the same thing. I solved it with "C_Cpp.intelliSenseEngine": "Tag Parser" )

Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME to your correct system (my case windows) username)

the code before line 7, on the settings.json has nothing to do with arduino or includePath. You may not copy that...

JSON section to add to settings.json:

"C_Cpp.default.includePath": [
        "C:/Program Files (x86)/Arduino/libraries/**",
        "C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino/**",
        "C:/Program Files (x86)/Arduino/hardware/tools/avr/avr/include/**",
        "C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/5.4.0/include/**",
        "C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard/**",
        "C:/Users/<YOUR USERNAME>/.platformio/packages/framework-arduinoavr/**",
        "C:/Users/<YOUR USERNAME>/Documents/Arduino/libraries/**",
        "{$workspaceFolder}/libraries/**",
        "{$workspaceFolder}/**"
    ],
"C_Cpp.intelliSenseEngine": "Tag Parser"

Firebase Permission Denied

  1. Open firebase, select database on the left hand side.
  2. Now on the right hand side, select [Realtime database] from the drown and change the rules to:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

React.js: Set innerHTML vs dangerouslySetInnerHTML

Yes there is a difference!

The immediate effect of using innerHTML versus dangerouslySetInnerHTML is identical -- the DOM node will update with the injected HTML.

However, behind the scenes when you use dangerouslySetInnerHTML it lets React know that the HTML inside of that component is not something it cares about.

Because React uses a virtual DOM, when it goes to compare the diff against the actual DOM, it can straight up bypass checking the children of that node because it knows the HTML is coming from another source. So there's performance gains.

More importantly, if you simply use innerHTML, React has no way to know the DOM node has been modified. The next time the render function is called, React will overwrite the content that was manually injected with what it thinks the correct state of that DOM node should be.

Your solution to use componentDidUpdate to always ensure the content is in sync I believe would work but there might be a flash during each render.

Content Security Policy: The page's settings blocked the loading of a resource

I managed to allow all my requisite sites with this header:

header("Content-Security-Policy: default-src *; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' stackexchange.com");                    

Add Favicon with React and Webpack

Here is how I did.

public/index.html

I have added the generated favicon links.

...
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/path/to/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/path/to/favicon-16x16.png" />
<link rel="shortcut icon" href="%PUBLIC_URL%/path/to/favicon.ico" type="image/png/ico" />

webpack.config.js

new HTMLWebpackPlugin({
   template: '/path/to/index.html',
   favicon: '/path/to/favicon.ico',
})

Note

I use historyApiFallback in dev mode, but I didn't need to have any extra setup to get the favicon work nor on the server side.

Can't Load URL: The domain of this URL isn't included in the app's domains

Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.

I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.

Could not find method android() for arguments

My issue was inside of my app.gradle. I ran into this issue when I moved

apply plugin: "com.android.application"

from the top line to below a line with

apply from:

I switched the plugin back to the top and violá

My exact error was

Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1@5d9d91a5] on project ':app' of type org.gradle.api.Project.

The top of my app.gradle now looks like this

project.ext.envConfigFiles = [
        debug: ".env",
        release: ".env",
        anothercustombuild: ".env",
]


apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"

HTML5 event handling(onfocus and onfocusout) using angular 2

I've created a little directive that bind with the tabindex attribute. It adds/removes the has-focus class dynamically.

@Directive({
    selector: "[tabindex]"
})
export class TabindexDirective {
    constructor(private elementHost: ElementRef) {}

    @HostListener("focus")
    setInputFocus(): void {
        this.elementHost.nativeElement.classList.add("has-focus");
    }

    @HostListener("blur")
    setInputFocusOut(): void {
        this.elementHost.nativeElement.classList.remove("has-focus");
    }
}

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

Go to Phone Settings --> Developer Options --> Simulate Secondary Displays and turn it to None. If you don't see Developer Options in the settings menu (it should be at the bottom, go Settings ==> About phone and tap on the Build number a lot of times)

Facebook OAuth "The domain of this URL isn't included in the app's domain"

first step: use all https://example.in or ssl certificate URL , dont use http://example.in

second step: faceboook application setting->basic setting->add your domain or subdomain

third step: faceboook application login setting->Valid OAuth Redirect URIs->add your all redirect url after login

fourth step: faceboook application setting->advance setting->Domain Manager->add your domain name

do all this step then use your application id, application version ,app secret for setup

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

These steps worked for me on several Systems using Ubuntu 16.04, Apache 2.4, MariaDB, PDO

  1. log into MYSQL as root

    mysql -u root
    
  2. Grant privileges. To a new user execute:

    CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
    GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost';
    FLUSH PRIVILEGES;
    

    UPDATE for Google Cloud Instances

    MySQL on Google Cloud seem to require an alternate command (mind the backticks).

    GRANT ALL PRIVILEGES ON `%`.* TO 'newuser'@'localhost';
    
  3. bind to all addresses:

    The easiest way is to comment out the line in your /etc/mysql/mariadb.conf.d/50-server.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf file, depending on what system you are running:

    #bind-address = 127.0.0.1 
    
  4. exit mysql and restart mysql

    exit
    service mysql restart
    

By default it binds only to localhost, but if you comment the line it binds to all interfaces it finds. Commenting out the line is equivalent to bind-address=*.

To check the binding of mysql service execute as root:

netstat -tupan | grep mysql

ERROR Android emulator gets killed

None of these answers worked for me. I just created a new Virtual Device with the same exact settings and deleted the old one. New one worked fine.

Visual Studio Code - Convert spaces to tabs

If you want to change tabs to spaces in a lot of files, but don't want to open them individually, I have found that it works equally as well to just use the Find and Replace option from the left-most tools bar.

In the first box (Find), copy and paste a tab from the source code.

In the second box (Replace), enter the number of spaces that you wish to use (i.e. 2 or 4).

If you press the ... button, you can specify directories to include or ignore (i.e. src/Data/Json).

Finally, inspect the result preview and press Replace All. All files in the workspace may be affected.

SyntaxError: Use of const in strict mode?

Update your node and it will resolve this problem.

Resetting a form in Angular 2 after submit

If you call only reset() function, the form controls will not set to pristine state. android.io docs have a solution for this issue.

component.ts

  active = true; 

  resetForm() {
      this.form.reset();
      this.active = false;
      setTimeout(() => this.active = true, 0);
  }

component.html

<form *ngIf="active">

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

I don't think this is your case, but I'll post it if it helps anyone. I had the same issue and the problem was that Node didn't respond at all (I had a condition that when failed didn't do anything - so no response) - So if increasing all your timeouts didn't solve it, make sure all scenarios get a response.

pip install - locale.Error: unsupported locale setting

[This answer is target on linux platform only]

The first thing you should know is most of the locale config file located path can be get from localedef --help :

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

See the last /usr/share/i18n ? This is where your xx_XX.UTF-8 config file located:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE, I can add it into compile list, i.e. /etc/locale-gen file:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

And compile it to binary with sudo locale-gen:

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

And now update the system default locale with desired LANG, LC_ALL ...etc with this update-locale:

sudo update-locale LANG=en_LOVE.UTF-8

update-locale actually also means to update this /etc/default/locale file which will source by system on login to setup environment variables:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:

$ . /etc/default/locale

How about sudo dpkg-reconfigure locales ? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen -> sudo locale-gen -> sudo update-locale LANG=en_LOVE.UTF-8

For python, as long as /etc/locale.gen contains that locale candidate and locale.gen get compiled, setlocale(category, locale) should work without throws locale.Error: unsupoorted locale setting. You can check the correct string en_US.UTF-8/en_US/....etc to be set in setlocale(), by observing /etc/locale.gen file, and then uncomment and compile it as desired. zh_CN GB2312 without dot in that file means the correct string is zh_CN and zh_CN.GB2312.

Django download a file

If you hafe upload your file in media than:

media
example-input-file.txt

views.py

def download_csv(request):    
    file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')    
    if os.path.exists(file_path):    
        with open(file_path, 'rb') as fh:    
            response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")    
            response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)    
            return response

urls.py

path('download_csv/', views.download_csv, name='download_csv'),

download.html

a href="{% url 'download_csv' %}" download=""

Error in MySQL when setting default value for DATE or DATETIME

Just add the line: sql_mode = "NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

inside file: /etc/mysql/mysql.conf.d/mysqld.cnf

then sudo service mysql restart

How to make inline plots in Jupyter Notebook larger?

I have found that %matplotlib notebook works better for me than inline with Jupyter notebooks.

Note that you may need to restart the kernel if you were using %matplotlib inline before.

Update 2019: If you are running Jupyter Lab you might want to use %matplotlib widget

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Either you experienced database connection issue or you missed any of the hibernate configurations to connect to database such as database DIALECT.

Happens if your database server was disconnected due to network related issue.

If you're using spring boot along with hibernate connected to Oracle Db, use

hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true
entitymanager.packagesToScan: com

ssh : Permission denied (publickey,gssapi-with-mic)

Setting 700 to .ssh and 600 to authorized_keys solved the issue.

chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys

React native text going off my screen, refusing to wrap. What to do?

this worked for me

<View style={{flexShrink:1}}>
  <Text>some long random text...</Text>
  </View>

Visual Studio Code: format is not using indent settings

If @Maleki's answer isn't working for you, check and see if you have an .editorconfig file in your project folder.

For example the Angular CLI generates one with a new project that looks like this

# Editor configuration, see http://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
max_line_length = off
trim_trailing_whitespace = false

Changing the indent_size here is required as it seems it will override anything in your .vscode workspace or user settings.

CORS with POSTMAN

Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.

Android Whatsapp/Chat Examples

Check out yowsup
https://github.com/tgalal/yowsup

Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.

A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.

Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.

How to echo xml file in php

This works:

<?php
$XML = "<?xml version='1.0' encoding='UTF-8'?>
<!-- Your XML -->
";

header('Content-Type: application/xml; charset=utf-8');
echo ($XML);
?>

Date Format in Swift

Swift - 5.0

let date = Date()
let formate = date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss") // Set output formate

extension Date {
   func getFormattedDate(format: String) -> String {
        let dateformat = DateFormatter()
        dateformat.dateFormat = format
        return dateformat.string(from: self)
    }
}

Swift - 4.0

2018-02-01T19:10:04+00:00 Convert Feb 01,2018

extension Date {
    static func getFormattedDate(string: String , formatter:String) -> String{
        let dateFormatterGet = DateFormatter()
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

        let dateFormatterPrint = DateFormatter()
        dateFormatterPrint.dateFormat = "MMM dd,yyyy"

        let date: Date? = dateFormatterGet.date(from: "2018-02-01T19:10:04+00:00")
        print("Date",dateFormatterPrint.string(from: date!)) // Feb 01,2018
        return dateFormatterPrint.string(from: date!);
    }
}

How to reset settings in Visual Studio Code?

This may be overkill, but it seemed to work for me:

#!/bin/sh

rm -rfv "$HOME/.vscode"
rm -rfv "$HOME/Library/Application Support/Code"
rm -rfv "$HOME/Library/Caches/com.microsoft.VSCode"
rm -rfv "$HOME/Library/Saved Application State/com.microsoft.VSCode.savedState"

After I ran that, and restarted VSC, it showed the the "Welcome" screen, which I took to mean that it was starting from scratch.

Declare variable in SQLite and use it

Try using Binding Values. You cannot use variables as you do in T-SQL but you can use "parameters". I hope the following link is usefull.Binding Values

What's the fastest way to read a text file line-by-line?

If you're using .NET 4, simply use File.ReadLines which does it all for you. I suspect it's much the same as yours, except it may also use FileOptions.SequentialScan and a larger buffer (128 seems very small).

how to delete a specific row in codeigniter?

You are using an $id variable in your model, but your are plucking it from nowhere. You need to pass the $id variable from your controller to your model.

Controller

Lets pass the $id to the model via a parameter of the row_delete() method.

function delete_row()
{
   $this->load->model('mod1');

   // Pass the $id to the row_delete() method
   $this->mod1->row_delete($id);


   redirect($_SERVER['HTTP_REFERER']);  
}

Model

Add the $id to the Model methods parameters.

function row_delete($id)
{
   $this->db->where('id', $id);
   $this->db->delete('testimonials'); 
}

The problem now is that your passing the $id variable from your controller, but it's not declared anywhere in your controller.

Automatic HTTPS connection/redirect with node.js/express

If your app is behind a trusted proxy (e.g. an AWS ELB or a correctly configured nginx), this code should work:

app.enable('trust proxy');
app.use(function(req, res, next) {
    if (req.secure){
        return next();
    }
    res.redirect("https://" + req.headers.host + req.url);
});

Notes:

  • This assumes that you're hosting your site on 80 and 443, if not, you'll need to change the port when you redirect
  • This also assumes that you're terminating the SSL on the proxy. If you're doing SSL end to end use the answer from @basarat above. End to end SSL is the better solution.
  • app.enable('trust proxy') allows express to check the X-Forwarded-Proto header

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Why is super.super.method(); not allowed in Java?

I think Jon Skeet has the correct answer. I'd just like to add that you can access shadowed variables from superclasses of superclasses by casting this:

interface I { int x = 0; }
class T1 implements I { int x = 1; }
class T2 extends T1 { int x = 2; }
class T3 extends T2 {
        int x = 3;
        void test() {
                System.out.println("x=\t\t"          + x);
                System.out.println("super.x=\t\t"    + super.x);
                System.out.println("((T2)this).x=\t" + ((T2)this).x);
                System.out.println("((T1)this).x=\t" + ((T1)this).x);
                System.out.println("((I)this).x=\t"  + ((I)this).x);
        }
}

class Test {
        public static void main(String[] args) {
                new T3().test();
        }
}

which produces the output:

x=              3
super.x=        2
((T2)this).x=   2
((T1)this).x=   1
((I)this).x=    0

(example from the JLS)

However, this doesn't work for method calls because method calls are determined based on the runtime type of the object.

Dynamically adding HTML form field using jQuery

You can add any type of HTML with methods like append and appendTo (among others):

jQuery manipulation methods

Example:

$('form#someform').append('<input type="text" name="something" id="something" />');

Trigger Change event when the Input value changed programmatically?

Vanilla JS solution:

var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));

Note that dispatchEvent doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).

So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for: typeof document.body.dispatchEvent === 'function'.

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

Angular 8 HttpClient Service example with Error Handling and Custom Header

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
    import { Student } from '../model/student';
    import { Observable, throwError } from 'rxjs';
    import { retry, catchError } from 'rxjs/operators';

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

      // API path
      base_path = 'http://localhost:3000/students';

      constructor(private http: HttpClient) { }

      // Http Options
      httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      }

      // Handle API errors
      handleError(error: HttpErrorResponse) {
        if (error.error instanceof ErrorEvent) {
          // A client-side or network error occurred. Handle it accordingly.
          console.error('An error occurred:', error.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.error(
            `Backend returned code ${error.status}, ` +
            `body was: ${error.error}`);
        }
        // return an observable with a user-facing error message
        return throwError(
          'Something bad happened; please try again later.');
      };


      // Create a new item
      createItem(item): Observable<Student> {
        return this.http
          .post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
          .pipe(
            retry(2),
            catchError(this.handleError)
          )
      }

      ....
      ....

enter image description here

Check complete example tutorial here

How to set a:link height/width with css?

Your problem is probably that a elements are display: inline by nature. You can't set the width and height of inline elements.

You would have to set display: block on the a, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left so they line up side by side anyway.

How to resize html canvas element?

This worked for me just now:

<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>

angularjs: allows only numbers to be typed into a text box

Simply use HTML5

<input type="number" min="0"/>

Initialize a long in Java

  1. You need to add the L character to the end of the number to make Java recognize it as a long.

    long i = 12345678910L;
    
  2. Yes.

See Primitive Data Types which says "An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int."

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

Swift 2.0

Pass info using userInfo which is a optional Dictionary of type [NSObject : AnyObject]?

  let imageDataDict:[String: UIImage] = ["image": image]

  // Post a notification
  NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

 // Register to receive notification in your class
 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

 // handle notification
 func showSpinningWheel(notification: NSNotification) { 

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
 }

Swift 3.0 version and above

The userInfo now takes [AnyHashable:Any]? as an argument, which we provide as a dictionary literal in Swift

  let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 // For swift 4.0 and above put @objc attribute in front of function Definition  
 func showSpinningWheel(_ notification: NSNotification) {

  if let image = notification.userInfo?["image"] as? UIImage {
  // do something with your image   
  }
 }

NOTE: Notification “names” are no longer strings, but are of type Notification.Name, hence why we are using NSNotification.Name(rawValue:"notificationName") and we can extend Notification.Name with our own custom notifications.

extension Notification.Name {
static let myNotification = Notification.Name("myNotification")
}

// and post notification like this
NotificationCenter.default.post(name: .myNotification, object: nil)

How to change DatePicker dialog color for Android 5.0

I had the problem that time picker buttons have not been seen in the screen for API 24 in android. (API 21+) it is solved by

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
            <item name="android:colorAccent">@color/colorPrimary2</item></style>

<style name="Theme" parent="BBaseTheme">
         <item name="android:datePickerDialogTheme">@style/MyDatePickerDialogTheme</item>
</style>

How to put a link on a button with bootstrap?

Combining the above answers i find a simply solution that probably will help you too:

<button type="submit" onclick="location.href = 'your_link';">Login</button>

by just adding inline JS code you can transform a button in a link and keeping his design.

Is it possible to run selenium (Firefox) web driver without a GUI?

An optional is to use pyvirtualdisplay like this:

from pyvirtualdisplay import Display

display = Display(visible=0, size=[800, 600])
display.start()

#do selenium job here

display.close()

A shorter version is:

with Display() as display:
    # selenium job here

This is generally a python encapsulate of xvfb, and more convinient somehow.

By the way, although PhantomJS is a headless browser and no window will be open if you use it, it seems that PhantomJS still needs a gui environment to work.

I got Error Code -6 when I use PhantomJS() instead of Firefox() in headless mode (putty-connected console). However everything is ok in desktop environment.

How do I refresh the page in ASP.NET? (Let it reload itself by code)

Try this:

Response.Redirect(Request.Url.AbsoluteUri);

Swift - encode URL

What helped me was that I created a separate NSCharacterSet and used it on an UTF-8 encoded string i.e. textToEncode to generate the required result:

var queryCharSet = NSCharacterSet.urlQueryAllowed
queryCharSet.remove(charactersIn: "+&?,:;@+=$*()")
    
let utfedCharacterSet = String(utf8String: textToEncode.cString(using: .utf8)!)!
let encodedStr = utfedCharacterSet.addingPercentEncoding(withAllowedCharacters: queryCharSet)!
    
let paramUrl = "https://api.abc.eu/api/search?device=true&query=\(escapedStr)"

How to use OUTPUT parameter in Stored Procedure

You need to close the connection before you can use the output parameters. Something like this

con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());

Set inputType for an EditText Programmatically?

For setting the input type for an EditText programmatically, you have to specify that input class type is text.

editPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

Greater than and less than in one statement

Nowadays you can use lodash:

var x = 1;
var y = 5;
var z = 3;
_.inRange(z,x,y);
//results true

How to implement the Java comparable interface?

This thing can easily be done by implementing a public class that implements Comparable. This will allow you to use compareTo method which can be used with any other object to which you wish to compare.

for example you can implement it in this way:

public String compareTo(Animal oth) 
{
    return String.compare(this.population, oth.population);
}

I think this might solve your purpose.

Regular expression to match numbers with or without commas and decimals in text

EDIT: Since this has gotten a lot of views, let me start by giving everybody what they Googled for:

#ALL THESE REQUIRE THE WHOLE STRING TO BE A NUMBER
#For numbers embedded in sentences, see discussion below

#### NUMBERS AND DECIMALS ONLY ####
#No commas allowed
#Pass: (1000.0), (001), (.001)
#Fail: (1,000.0)
^\d*\.?\d+$

#No commas allowed
#Can't start with "."
#Pass: (0.01)
#Fail: (.01)
^(\d+\.)?\d+$

#### CURRENCY ####
#No commas allowed
#"$" optional
#Can't start with "."
#Either 0 or 2 decimal digits
#Pass: ($1000), (1.00), ($0.11)
#Fail: ($1.0), (1.), ($1.000), ($.11)
^\$?\d+(\.\d{2})?$

#### COMMA-GROUPED ####
#Commas required between powers of 1,000
#Can't start with "."
#Pass: (1,000,000), (0.001)
#Fail: (1000000), (1,00,00,00), (.001)
^\d{1,3}(,\d{3})*(\.\d+)?$

#Commas required
#Cannot be empty
#Pass: (1,000.100), (.001)
#Fail: (1000), ()
^(?=.)(\d{1,3}(,\d{3})*)?(\.\d+)?$

#Commas optional as long as they're consistent
#Can't start with "."
#Pass: (1,000,000), (1000000)
#Fail: (10000,000), (1,00,00)
^(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$

#### LEADING AND TRAILING ZEROES ####
#No commas allowed
#Can't start with "."
#No leading zeroes in integer part
#Pass: (1.00), (0.00)
#Fail: (001)
^([1-9]\d*|0)(\.\d+)?$

#No commas allowed
#Can't start with "."
#No trailing zeroes in decimal part
#Pass: (1), (0.1)
#Fail: (1.00), (0.1000)
^\d+(\.\d*[1-9])?$

Now that that's out of the way, most of the following is meant as commentary on how complex regex can get if you try to be clever with it, and why you should seek alternatives. Read at your own risk.


This is a very common task, but all the answers I see here so far will accept inputs that don't match your number format, such as ,111, 9,9,9, or even .,,.. That's simple enough to fix, even if the numbers are embedded in other text. IMHO anything that fails to pull 1,234.56 and 1234—and only those numbers—out of abc22 1,234.56 9.9.9.9 def 1234 is a wrong answer.

First of all, if you don't need to do this all in one regex, don't. A single regex for two different number formats is hard to maintain even when they aren't embedded in other text. What you should really do is split the whole thing on whitespace, then run two or three smaller regexes on the results. If that's not an option for you, keep reading.

Basic pattern

Considering the examples you've given, here's a simple regex that allows pretty much any integer or decimal in 0000 format and blocks everything else:

^\d*\.?\d+$

Here's one that requires 0,000 format:

^\d{1,3}(,\d{3})*(\.\d+)?$

Put them together, and commas become optional as long as they're consistent:

^(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)$

Embedded numbers

The patterns above require the entire input to be a number. You're looking for numbers embedded in text, so you have to loosen that part. On the other hand, you don't want it to see catch22 and think it's found the number 22. If you're using something with lookbehind support (like .NET), this is pretty easy: replace ^ with (?<!\S) and $ with (?!\S) and you're good to go:

(?<!\S)(\d*\.?\d+|\d{1,3}(,\d{3})*(\.\d+)?)(?!\S)

If you're working with JavaScript or Ruby or something, things start looking more complex:

(?:^|\s)(\d*\.?\d+|\d{1,3}(?:,\d{3})*(?:\.\d+)?)(?!\S)

You'll have to use capture groups; I can't think of an alternative without lookbehind support. The numbers you want will be in Group 1 (assuming the whole match is Group 0).

Validation and more complex rules

I think that covers your question, so if that's all you need, stop reading now. If you want to get fancier, things turn very complex very quickly. Depending on your situation, you may want to block any or all of the following:

  • Empty input
  • Leading zeroes (e.g. 000123)
  • Trailing zeroes (e.g. 1.2340000)
  • Decimals starting with the decimal point (e.g. .001 as opposed to 0.001)

Just for the hell of it, let's assume you want to block the first 3, but allow the last one. What should you do? I'll tell you what you should do, you should use a different regex for each rule and progressively narrow down your matches. But for the sake of the challenge, here's how you do it all in one giant pattern:

(?<!\S)(?=.)(0|([1-9](\d*|\d{0,2}(,\d{3})*)))?(\.\d*[1-9])?(?!\S)

And here's what it means:

(?<!\S) to (?!\S) #The whole match must be surrounded by either whitespace or line boundaries. So if you see something bogus like :;:9.:, ignore the 9.
(?=.)             #The whole thing can't be blank.

(                    #Rules for the integer part:
  0                  #1. The integer part could just be 0...
  |                  #
  [1-9]              #   ...otherwise, it can't have leading zeroes.
  (                  #
    \d*              #2. It could use no commas at all...
    |                #
    \d{0,2}(,\d{3})* #   ...or it could be comma-separated groups of 3 digits each.
  )                  # 
)?                   #3. Or there could be no integer part at all.

(       #Rules for the decimal part:
  \.    #1. It must start with a decimal point...
  \d*   #2. ...followed by a string of numeric digits only.
  [1-9] #3. It can't be just the decimal point, and it can't end in 0.
)?      #4. The whole decimal part is also optional. Remember, we checked at the beginning to make sure the whole thing wasn't blank.

Tested here: http://rextester.com/YPG96786

This will allow things like:

100,000
999.999
90.0009
1,000,023.999
0.111
.111
0

It will block things like:

1,1,1.111
000,001.111
999.
0.
111.110000
1.1.1.111
9.909,888

There are several ways to make this regex simpler and shorter, but understand that changing the pattern will loosen what it considers a number.

Since many regex engines (e.g. JavaScript and Ruby) don't support the negative lookbehind, the only way to do this correctly is with capture groups:

(:?^|\s)(?=.)((?:0|(?:[1-9](?:\d*|\d{0,2}(?:,\d{3})*)))?(?:\.\d*[1-9])?)(?!\S)

The numbers you're looking for will be in capture group 1.

Tested here: http://rubular.com/r/3HCSkndzhT

One final note

Obviously, this is a massive, complicated, nigh-unreadable regex. I enjoyed the challenge, but you should consider whether you really want to use this in a production environment. Instead of trying to do everything in one step, you could do it in two: a regex to catch anything that might be a number, then another one to weed out whatever isn't a number. Or you could do some basic processing, then use your language's built-in number parsing functions. Your choice.

Convert DOS line endings to Linux line endings in Vim

:%s/\r\+//g

In Vim, that strips all carriage returns, and leaves only newlines.

Mysql - delete from multiple tables with one query

Apparently, it is possible. From the manual:

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE. The table_references clause lists the tables involved in the join. Its syntax is described in Section 12.2.8.1, “JOIN Syntax”.

The example in the manual is:

DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;

should be applicable 1:1.

How to do a PUT request with curl?

An example PUT following Martin C. Martin's comment:

curl -T filename.txt http://www.example.com/dir/

With -T (same as --upload-file) curl will use PUT for HTTP.

ASP.NET page life cycle explanation

Partial Class _Default
    Inherits System.Web.UI.Page
    Dim str As String

    Protected Sub Page_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed

        str += "PAGE DISPOSED" & "<br />"
    End Sub

    Protected Sub Page_Error(sender As Object, e As System.EventArgs) Handles Me.Error
        str += "PAGE ERROR " & "<br />"
    End Sub

    Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
        str += "PAGE INIT " & "<br />"
    End Sub

    Protected Sub Page_InitComplete(sender As Object, e As System.EventArgs) Handles Me.InitComplete
        str += "INIT Complte " & "<br />"
    End Sub

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        str += "PAGE LOAD " & "<br />"

    End Sub

    Protected Sub Page_LoadComplete(sender As Object, e As System.EventArgs) Handles Me.LoadComplete
        str += "PAGE LOAD Complete " & "<br />"
    End Sub

    Protected Sub Page_PreInit(sender As Object, e As System.EventArgs) Handles Me.PreInit
        str = ""
        str += "PAGE PRE INIT" & "<br />"
    End Sub

    Protected Sub Page_PreLoad(sender As Object, e As System.EventArgs) Handles Me.PreLoad
        str += "PAGE PRE LOAD " & "<br />"
    End Sub

    Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
        str += "PAGE PRE RENDER " & "<br />"
    End Sub

    Protected Sub Page_PreRenderComplete(sender As Object, e As System.EventArgs) Handles Me.PreRenderComplete
        str += "PAGE PRE RENDER COMPLETE " & "<br />"
    End Sub

    Protected Sub Page_SaveStateComplete(sender As Object, e As System.EventArgs) Handles Me.SaveStateComplete
        str += "PAGE SAVE STATE COMPLTE  " & "<br />"
        lbl.Text = str
    End Sub

    Protected Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
        'Response.Write("PAGE UN LOAD\n")
    End Sub
End Class

Use Device Login on Smart TV / Console

Implement Login for Devices

Facebook Login for Devices is for devices that directly make HTTP calls over the internet. The following are the API calls and responses your device can make.

1. Enable Login for Devices

Change Settings > Advanced > OAuth Settings > Login from Devices to 'Yes'.

2. Generate a Code which is required for facebook device identification

When the person clicks Log in with Facebook, you device should make an HTTP POST to:

POST https://graph.facebook.com/oauth/device?
       type=device_code
       &amp;client_id=<YOUR_APP_ID>
       &amp;scope=<COMMA_SEPARATED_PERMISSION_NAMES> // e.g.public_profile,user_likes

The response comes in this form:

{
  "code": "92a2b2e351f2b0b3503b2de251132f47",
  "user_code": "A1NWZ9",
  "verification_uri": "https://www.facebook.com/device",
  "expires_in": 420,
  "interval": 5
}

This response means:

  • Display the string “A1NWZ9” on your device
  • Tell the person to go to “facebook.com/device” and enter this code
  • The code expires in 420 seconds. You should cancel the login flow after that time if you do not receive an access token
  • Your device should poll the Device Login API every 5 seconds to see if the authorization has been successful

3. Display the Code

Your device should display the user_code and tell people to visit the verification_uri such as facebook.com/device on their PC or smartphone. See the Design Guidelines.

4. Poll for Authorization

Your device should poll the Device Login API to see if the person successfully authorized your application. You should do this at the interval in the response to your call in Step 1, which is every 5 seconds. Your device should poll to:

POST https://graph.facebook.com/oauth/device?
       type=device_token
       &amp;client_id=<YOUR_APP_ID> 
       &amp;code=<LONG_CODE_FROM_STEP_1> //e.g."92a2b2e351f2b0b3503b2de251132f47"

You will get 200 HTTP code i.e User has successfully authorized the device. The device can now use the access_token value to make authenticated API calls.

5. Confirm Successful Login

Your device should display their name and if available, a profile picture until they click Continue. To get the person's name and profile picture, your device should make a standard Graph API call:

GET https://graph.facebook.com/v2.3/me?
      fields=name,picture&amp;
      access_token=<USER_ACCESS_TOKEN>

Response:

{
  "name": "John Doe", 
  "picture": {
    "data": {
      "is_silhouette": false, 
      "url": "https://fbcdn.akamaihd.net/hmac...ile.jpg"
    }
  }, 
  "id": "2023462875238472"
}

6. Store Access Tokens

Your device should persist the access token to make other requests to the Graph API.

Device Login access tokens may be valid for up to 60 days but may be invalided in a number of scenarios. For example when a person changes their Facebook password their access token is invalidated.

If the token is invalid, your device should delete the token from its memory. The person using your device needs to perform the Device Login flow again from Step 1 to retrieve a new, valid token.

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:

enter image description here

form-data

Header

content-type: multipart/form-data; boundary=--------------------------590299136414163472038474

Body

key1=value1key2=value2

x-www-form-urlencoded

Header

Content-Type: application/x-www-form-urlencoded

Body

key1=value1&key2=value2

Raw text/plain

Header

Content-Type: text/plain

Body

This is some text.

Raw json

Header

Content-Type: application/json

Body

{"key1":"value1","key2":"value2"}

PostgreSQL Crosstab Query

Solution with JSON aggregation:

CREATE TEMP TABLE t (
  section   text
, status    text
, ct        integer  -- don't use "count" as column name.
);

INSERT INTO t VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                   , ('C', 'Inactive', 7); 


SELECT section,
       (obj ->> 'Active')::int AS active,
       (obj ->> 'Inactive')::int AS inactive
FROM (SELECT section, json_object_agg(status,ct) AS obj
      FROM t
      GROUP BY section
     )X

RESTful URL design for search

For the searching, use querystrings. This is perfectly RESTful:

/cars?color=blue&type=sedan&doors=4

An advantage to regular querystrings is that they are standard and widely understood and that they can be generated from form-get.

Is Secure.ANDROID_ID unique for each device?

//Fields
String myID;
int myversion = 0;


myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
        TelephonyManager mngr = (TelephonyManager) 
getSystemService(Context.TELEPHONY_SERVICE);
        myID= mngr.getDeviceId();
    }
    else
    {
        myID = 
Settings.Secure.getString(getApplicationContext().getContentResolver(), 
Settings.Secure.ANDROID_ID);
    }

Yes, Secure.ANDROID_ID is unique for each device.

Bootstrap 3 unable to display glyphicon properly

For me placing my fonts folder as per location specified in bootstrap.css solved the problem

Mostly its fonts folder should be in parent directory of bootstrap.css file .

I faced this problem , and researching many answers , if anyone still in 2015 faces this problem then its either a CSS problem , or location mismatch for files .

The bug has already been solved by bootstrap

Using gradle to find dependency tree

You can render the dependency tree with the command gradle dependencies. For more information check the section 11.6.4 Listing project dependencies in the online user guide.

Rounding a variable to two decimal places C#

Console.WriteLine(decimal.Round(pay,2));

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

Run the following command :

sudo rm /var/lib/mongodb/mongod.lock
sudo service mongod restart

Connection refused to MongoDB errno 111

MacOS:

rm /usr/local/var/mongodb/mongod.lock  
sudo service mongod restart

Why does this "Slow network detected..." log appear in Chrome?

EDIT: This is not working with latest version of 63.0+

I was able to disable it using help from one of above comments, go to

chrome://flags/#enable-webfonts-intervention-v2

The trick is to also disable the "Trigger User Agent Intervention for WebFonts loading always" option just below that as well.

enter image description here

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

The answer I have finally found is that the SMTP service on the server is not using the same certificate as https.

The diagnostic steps I had read here make the assumption they use the same certificate and every time I've tried this in the past they have done and the diagnostic steps are exactly what I've done to solve the problem several times.

In this case those steps didn't work because the certificates in use were different, and the possibility of this is something I had never come across.

The solution is either to export the actual certificate from the server and then install it as a trusted certificate on my machine, or to get a different valid/trusted certificate for the SMTP service on the server. That is currently with our IT department who administer the servers to decide which they want to do.

Hash function for a string

First, it usually does not matter that much in practice. Most hash functions are "good enough".

But if you really care, you should know that it is a research subject by itself. There are thousand of papers about that. You can still get a PhD today by studying & designing hashing algorithms.

Your second hash function might be slightly better, because it probably should separate the string "ab" from the string "ba". On the other hand, it is probably less quick than the first hash function. It may, or may not, be relevant for your application.

I'll guess that hash functions used for genome strings are quite different than those used to hash family names in telephone databases. Perhaps even some string hash functions are better suited for German, than for English or French words.

Many software libraries give you good enough hash functions, e.g. Qt has qhash, and C++11 has std::hash in <functional>, Glib has several hash functions in C, and POCO has some hash function.

I quite often have hashing functions involving primes (see Bézout's identity) and xor, like e.g.

#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
unsigned hash_str(const char* s)
{
   unsigned h = FIRSTH;
   while (*s) {
     h = (h * A) ^ (s[0] * B);
     s++;
   }
   return h; // or return h % C;
}

But I don't claim to be an hash expert. Of course, the values of A, B, C, FIRSTH should preferably be primes, but you could have chosen other prime numbers.

Look at some MD5 implementation to get a feeling of what hash functions can be.

Most good books on algorithmics have at least a whole chapter dedicated to hashing. Start with wikipages on hash function & hash table.

How to copy data from another workbook (excel)?

Would you be happy to make "my file.xls" active if it didn't affect the screen? Turning off screen updating is the way to achieve this, it also has performance improvements (significant if you are doing looping while switching around worksheets / workbooks).

The command to do this is:

    Application.ScreenUpdating = False

Don't forget to turn it back to True when your macros is finished.

Difference between "as $key => $value" and "as $value" in PHP foreach

The difference is that on the

foreach($featured as $key => $value){
 echo $value['name'];
}

you are able to manipulate the value of each iteration's $key from their key-value pair. Like @djiango answered, if you are not manipulating each value's $key, the result of the loop will be exactly the same as

foreach($featured as $value) {
  echo $value['name']
}

Source: You can read it from the PHP Documentation:

The first form loops over the array given by array_expression. On each iteration, the value >of the current element is assigned to $value and the internal array pointer is advanced by >one (so on the next iteration, you'll be looking at the next element).*

The second form will additionally assign the current element's key to the $key variable on >each iteration.


If the data you are manipulating is, say, arrays with custom keys, you could print them to screen like so:

$array = ("name" => "Paul", "age" => 23);

foreach($featured as $key => $value){
 echo $key . "->" . $value;
}

Should print:

name->Paul

age->23

And you wouldn't be able to do that with a foreach($featured as $value) with the same ease. So consider the format above a convenient way to manipulate keys when needed.

Cheers

angular2 submit form by pressing enter without submit button

This way is much simple...

<form [formGroup]="form" (keyup.enter)="yourMethod(form.value)">

</form>

Check if passed argument is file or directory in Bash

Using the "file" command may be useful for this:

#!/bin/bash
check_file(){

if [ -z "${1}" ] ;then
 echo "Please input something"
 return;
fi

f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
        echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
        echo "DIRECTORY FOUND ($result) ";
else
        echo "FILE FOUND ($result) ";
fi

}

check_file "${1}"

Output examples :

$ ./f.bash login
DIRECTORY FOUND (login: directory) 
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or  directory)) 
$ ./f.bash evil.php 
FILE FOUND (evil.php: PHP script, ASCII text) 

FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:

#!/bin/bash

check_file(){
    local file="${1}"
    [[ -s "${file}" ]] || { echo "is not valid"; return; } 
    [[ -d "${file}" ]] && { echo "is a directory"; return; }
    [[ -f "${file}" ]] && { echo "is a file"; return; }
}

check_file ${1}

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

You can replace nan with None in your numpy array:

>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>

How to check if directory exist using C++ and winAPI

Here is a simple function which does exactly this :

#include <windows.h>
#include <string>

bool dirExists(const std::string& dirName_in)
{
  DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
  if (ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  //something is wrong with your path!

  if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // this is a directory!

  return false;    // this is not a directory!
}

find the array index of an object with a specific key value in underscore

Array.prototype.getIndex = function (obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][Id] == obj.Id) {
            return i;
        }
    }
    return -1;
}

List.getIndex(obj);

How to compare times in Python?

You can use the time() method of datetime objects to get the time of day, which you can use for comparison without taking the date into account:

>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True

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

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

UTF-8 encoding problem in Spring MVC

I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.

Adding a header to the HttpServletResponse works.

@RequestMapping(value="/test", method=RequestMethod.POST)
public void test(HttpServletResponse resp) {
    try {
        resp.addHeader("content-type", "application/json; charset=utf-8");
        PrintWriter w = resp.getWriter();
        w.write("{\"name\" : \"µr µicron\"}");
        w.flush();
        w.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Visual Studio Code: format is not using indent settings

If you're using a plugin (in my case Vetur, for vue.js), these may set their own tab formatting settings.

Open your settings, search for "format" and look through relevant plugin settings that may be overwriting the global tab format. This worked for me; once I updated Vetur tab settings to match my preference (4-size tabs in my case), formatting .vue documents started to work properly:

enter image description here

How to restore PostgreSQL dump file into Postgres databases?

Combining the advice from MartinP and user664833, I was also able to get it to work. Caveat is that entering psql from the pgAdmin GUI tool via choosing Plugins...PSQL Console sets the credentials and permission level for the psql session, so you must have Admin or CRUD permissions on the table and maybe also Admin on the DB (do not know for sure on that). The command then in the psql console would take this form:

postgres=# \i driveletter:/folder_path/backupfilename.backup

where postgres=# is the psql prompt, not part of the command.

The .backup file will include the commands used to create the table, so you may also get things like "ALTER TABLE ..." commands in the file that get executed but reported as errors. I suppose you can always delete these commands before running the restore but you're probably better safe than sorry to keep them in there, as these will not likely cause the restore of data to fail. But always check to be sure the data you wanted to resore actually got there. (Sorry if this seems like patronizing advice to anyone, but it's an oversight that can happen to anyone no matter how long they have been at this stuff -- a moment's distraction from a colleague, a phone call, etc., and it's easy to forget this step. I have done it myself using other databases earlier in my career and wondered "Gee, why am I not seeing any data back from this query?" Answer was the data never actually got restored, and I just wasted 2 hours trying to hunt down suspected possible bugs that didn't exist.)

Why are you not able to declare a class as static in Java?

if the benefit of using a static-class was not to instantiate an object and using a method then just declare the class as public and this method as static.

C# go to next item in list based on if statement in foreach

Try this:

foreach (Item item in myItemsList)
{
  if (SkipCondition) continue;
  // More stuff here
}

Should I make HTML Anchors with 'name' or 'id'?

You shouldn’t use <h1><a name="foo"/>Foo Title</h1> in any flavor of HTML served as text/html, because the XML empty element syntax isn’t supported in text/html. However, <h1><a name="foo">Foo Title</a></h1> is OK in HTML4. It is not valid in HTML5 as currently drafted.

<h1 id="foo">Foo Title</h1> is OK in both HTML4 and HTML5. This won’t work in Netscape 4, but you’ll probably use a dozen other features that don’t work in Netscape 4.

jQuery scroll to ID from different page

function scroll_down(){
    $.noConflict();
    jQuery(document).ready(function($) {
        $('html, body').animate({
            scrollTop : $("#bottom").offset().top
        }, 1);
    });
    return false;
}

here "bottom" is the div tag id where you want to scroll to. For changing the animation effects, you can change the time from '1' to a different value

Format Float to n decimal places

Of note, use of DecimalFormat constructor is discouraged. The javadoc for this class states:

In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.

https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

So what you need to do is (for instance):

NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP); 
Float formatedFloat = new Float(formatter.format(floatValue));

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

This was good enough for me

sudo /etc/init.d/mysql restart

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Add this attribute to you activity in manifest file. android:noHistory="true"

How do I disable a Button in Flutter?

For disabling any Button in flutter such as FlatButton, RaisedButton, MaterialButton, IconButton etc all you need to do is to set the onPressed and onLongPress properties to null. Below is some simple examples for some of the buttons:

FlatButton (Enabled)

FlatButton(
  onPressed: (){}, 
  onLongPress: null, // Set one as NOT null is enough to enable the button
  textColor: Colors.black,
  disabledColor: Colors.orange,
  disabledTextColor: Colors.white,
  child: Text('Flat Button'),
),

enter image description here enter image description here

FlatButton (Disabled)

FlatButton(
  onPressed: null,
  onLongPress: null,
  textColor: Colors.black,
  disabledColor: Colors.orange,
  disabledTextColor: Colors.white,
  child: Text('Flat Button'),
),

enter image description here

RaisedButton (Enabled)

RaisedButton(
  onPressed: (){},
  onLongPress: null, // Set one as NOT null is enough to enable the button
  // For when the button is enabled
  color: Colors.lightBlueAccent,
  textColor: Colors.black,
  splashColor: Colors.blue,
  elevation: 8.0,

  // For when the button is disabled
  disabledTextColor: Colors.white,
  disabledColor: Colors.orange,
  disabledElevation: 0.0,

  child: Text('Raised Button'),
),

enter image description here

RaisedButton (Disabled)

RaisedButton(
  onPressed: null,
  onLongPress: null,
  // For when the button is enabled
  color: Colors.lightBlueAccent,
  textColor: Colors.black,
  splashColor: Colors.blue,
  elevation: 8.0,

  // For when the button is disabled
  disabledTextColor: Colors.white,
  disabledColor: Colors.orange,
  disabledElevation: 0.0,

  child: Text('Raised Button'),
),

enter image description here

IconButton (Enabled)

IconButton(
  onPressed: () {},
  icon: Icon(Icons.card_giftcard_rounded),
  color: Colors.lightBlueAccent,
            
  disabledColor: Colors.orange,
),

enter image description here enter image description here

IconButton (Disabled)

IconButton(
  onPressed: null,
  icon: Icon(Icons.card_giftcard_rounded),
  color: Colors.lightBlueAccent,
            
  disabledColor: Colors.orange,
),

enter image description here

Note: Some of buttons such as IconButton have only the onPressed property.

Specified argument was out of the range of valid values. Parameter name: site

I had the same issue i resolved it by repairing the iis server in programs and features.

GO TO

Controll panel > uninstall a program and then right click the installed iis express server (installed with Visual Studio) and then click repair.

this is how i solved this issue

PHP form send email to multiple recipients

Make sure you concatenate the multiple emails with ',' instead of ';'

Why can't I inherit static classes?

Citation from here:

This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.

There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.

(Mads Torgersen, C# Language PM)

Other opinions from channel9

Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...

Static methods are only held once in memory. There is no virtual table etc. that is created for them.

If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?

(littleguru)

And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.

How to Make A Chevron Arrow Using CSS?

You can use the before or after pseudo-element and apply some CSS to it. There are various ways. You can add both before and after, and rotate and position each of them to form one of the bars. An easier solution is adding two borders to just the before element and rotate it using transform: rotate.

Scroll down for a different solution that uses an actual element instead of the pseuso elements

In this case, I've added the arrows as bullets in a list and used em sizes to make them size properly with the font of the list.

_x000D_
_x000D_
ul {_x000D_
    list-style: none;_x000D_
}_x000D_
_x000D_
ul.big {_x000D_
    list-style: none;_x000D_
    font-size: 300%_x000D_
}_x000D_
_x000D_
li::before {_x000D_
    position: relative;_x000D_
    /* top: 3pt; Uncomment this to lower the icons as requested in comments*/_x000D_
    content: "";_x000D_
    display: inline-block;_x000D_
    /* By using an em scale, the arrows will size with the font */_x000D_
    width: 0.4em;_x000D_
    height: 0.4em;_x000D_
    border-right: 0.2em solid black;_x000D_
    border-top: 0.2em solid black;_x000D_
    transform: rotate(45deg);_x000D_
    margin-right: 0.5em;_x000D_
}_x000D_
_x000D_
/* Change color */_x000D_
li:hover {_x000D_
  color: red; /* For the text */_x000D_
}_x000D_
li:hover::before {_x000D_
  border-color: red; /* For the arrow (which is a border) */_x000D_
}
_x000D_
<ul>_x000D_
    <li>Item1</li>_x000D_
    <li>Item2</li>_x000D_
    <li>Item3</li>_x000D_
    <li>Item4</li>_x000D_
</ul>_x000D_
_x000D_
<ul class="big">_x000D_
    <li>Item1</li>_x000D_
    <li>Item2</li>_x000D_
    <li>Item3</li>_x000D_
    <li>Item4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Of course you don't need to use before or after, you can apply the same trick to a normal element as well. For the list above it is convenient, because you don't need additional markup. But sometimes you may want (or need) the markup anyway. You can use a div or span for that, and I've even seen people even recycle the i element for 'icons'. So that markup could look like below. Whether using <i> for this is right is debatable, but you can use span for this as well to be on the safe side.

_x000D_
_x000D_
/* Default icon formatting */_x000D_
i {_x000D_
  display: inline-block;_x000D_
  font-style: normal;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
/* Additional formatting for arrow icon */_x000D_
i.arrow {_x000D_
    /* top: 2pt; Uncomment this to lower the icons as requested in comments*/_x000D_
    width: 0.4em;_x000D_
    height: 0.4em;_x000D_
    border-right: 0.2em solid black;_x000D_
    border-top: 0.2em solid black;_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
And so you can have an <i class="arrow" title="arrow icon"></i> in your text._x000D_
This arrow is <i class="arrow" title="arrow icon"></i> used to be deliberately lowered slightly on request._x000D_
I removed that for the general public <i class="arrow" title="arrow icon"></i> but you can uncomment the line with 'top' <i class="arrow" title="arrow icon"></i> to restore that effect.
_x000D_
_x000D_
_x000D_

If you seek more inspiration, make sure to check out this awesome library of pure CSS icons by Nicolas Gallagher. :)

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I got the same error but I have fixed it by changing the file reading path from "ConfigFile.xml" to AppDomain.CurrentDomain.BaseDirectory.ToString() + "ConfigFile.xml"

In my case, this error due to file path error because task manager starts program from "System32" as initial path but the folder we thought.

Compare two MySQL databases

If you only need to compare schemas (not data), and have access to Perl, mysqldiff might work. I've used it because it lets you compare local databases to remote databases (via SSH), so you don't need to bother dumping any data.

http://adamspiers.org/computing/mysqldiff/

It will attempt to generate SQL queries to synchronize two databases, but I don't trust it (or any tool, actually). As far as I know, there's no 100% reliable way to reverse-engineer the changes needed to convert one database schema to another, especially when multiple changes have been made.

For example, if you change only a column's type, an automated tool can easily guess how to recreate that. But if you also move the column, rename it, and add or remove other columns, the best any software package can do is guess at what probably happened. And you may end up losing data.

I'd suggest keeping track of any schema changes you make to the development server, then running those statements by hand on the live server (or rolling them into an upgrade script or migration). It's more tedious, but it'll keep your data safe. And by the time you start allowing end users access to your site, are you really going to be making constant heavy database changes?

Kill all processes for a given user

The following kills all the processes created by this user:

kill  -9  -1

Storing a Key Value Array into a compact JSON string

So why don't you simply use a key-value literal?

var params = {
    'slide0001.html': 'Looking Ahead',
    'slide0002.html': 'Forecase',
    ...
};

return params['slide0001.html']; // returns: Looking Ahead

Populating a ComboBox using C#

Create a class Language

public class Language
{
     public string Name{get;set;}
     public string Value{get;set;}
     public override string ToString() { return this.Name;}
}

Then, add as many language to the combobox that you want:

yourCombobox.Items.Add(new Language{Name="English",Value="En"});

How do I use a Boolean in Python?

True ... and False obviously.

Otherwise, None evaluates to False, as does the integer 0 and also the float 0.0 (although I wouldn't use floats like that). Also, empty lists [], empty tuplets (), and empty strings '' or "" evaluate to False.

Try it yourself with the function bool():

bool([])
bool(['a value'])
bool('')
bool('A string')
bool(True)  # ;-)
bool(False)
bool(0)
bool(None)
bool(0.0)
bool(1)

etc..

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

Display Parameter(Multi-value) in Report

=Join(Parameters!Product.Label, vbcrfl) for new line

Set background image in CSS using jquery

try this

 $(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");

PHP - check if variable is undefined

JavaScript's 'strict not equal' operator (!==) on comparison with undefined does not result in false on null values.

var createTouch = null;
isTouch = createTouch !== undefined  // true

To achieve an equivalent behaviour in PHP, you can check whether the variable name exists in the keys of the result of get_defined_vars().

// just to simplify output format
const BR = '<br>' . PHP_EOL;

// set a global variable to test independence in local scope
$test = 1;

// test in local scope (what is working in global scope as well)
function test()
{
  // is global variable found?
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test does not exist.

  // is local variable found?
  $test = null;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // try same non-null variable value as globally defined as well
  $test = 1;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // repeat test after variable is unset
  unset($test);
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.') . BR;
  // $test does not exist.
}

test();

In most cases, isset($variable) is appropriate. That is aquivalent to array_key_exists('variable', get_defined_vars()) && null !== $variable. If you just use null !== $variable without prechecking for existence, you will mess up your logs with warnings because that is an attempt to read the value of an undefined variable.

However, you can apply an undefined variable to a reference without any warning:

// write our own isset() function
function my_isset(&$var)
{
  // here $var is defined
  // and initialized to null if the given argument was not defined
  return null === $var;
}

// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable);   // $is_set is false

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

jQuery: how to find first visible input/select/textarea excluding buttons?

You may try below code...

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('form').find('input[type=text],textarea,select').filter(':visible:first').focus();_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>_x000D_
<form>_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
<input type="text" />_x000D_
    _x000D_
<input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes, the order of elements in a python list is persistent.

How to check the version of GitLab?

The easiest way is to paste the following command:

cat /opt/gitlab/version-manifest.txt | head -n 1

and there you get the version installed. :)

Access restriction on class due to restriction on required library rt.jar?

Just change the order of build path libraries of your project. Right click on project>Build Path> Configure Build Path>Select Order and Export(Tab)>Change the order of the entries. I hope moving the "JRE System library" to the bottom will work. It worked so for me. Easy and simple....!!!

how to remove empty strings from list, then remove duplicate values from a list

Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.

var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
    if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

How to cherry-pick multiple commits

Git 1.7.2 introduced the ability to cherry pick a range of commits. From the release notes:

git cherry-pick learned to pick a range of commits (e.g. cherry-pick A..B and cherry-pick --stdin), so did git revert; these do not support the nicer sequencing control rebase [-i] has, though.

To cherry-pick all the commits from commit A to commit B (where A is older than B), run:

git cherry-pick A^..B

If you want to ignore A itself, run:

git cherry-pick A..B

(Credit goes to damian, J. B. Rainsberger and sschaef in the comments)

finding the type of an element using jQuery

You can use .prop() with tagName as the name of the property that you want to get:

$("#elementId").prop('tagName'); 

ERROR 2003 (HY000): Can't connect to MySQL server (111)

I have got a same question like you, I use wireshark to capture my sent TCP packets, I found when I use mysql bin to connect the remote host, it connects remote's 3307 port, that's my falut in /etc/mysql/my.cnf, 3307 is another project mysql port, but I change that config in my.cnf [client] part, when I use -P option to specify 3306 port, it's OK.

Free Barcode API for .NET

I do recommend BarcodeLibrary

Here is a small piece of code of how to use it.

        BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
        {
            IncludeLabel = true,
            Alignment = AlignmentPositions.CENTER,
            Width = 300,
            Height = 100,
            RotateFlipType = RotateFlipType.RotateNoneFlipNone,
            BackColor = Color.White,
            ForeColor = Color.Black,
        };

        Image img = barcode.Encode(TYPE.CODE128B, "123456789");

Javascript string/integer comparisons

You can use Number() function also since it converts the object argument to a number that represents the object's value.

Eg: javascript:alert( Number("2") > Number("10"))

Radio button checked event handling

$("#expires1").click(function(){
     if (this.checked)
        alert("testing....");
});

MySQL JOIN with LIMIT 1 on joined table

What about this?

SELECT c.id, c.title, (SELECT id from products AS p 
                            WHERE c.id = p.category_id 
                            ORDER BY ... 
                            LIMIT 1)
   FROM categories AS c;

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

Does Spring @Transactional attribute work on a private method?

The answer is no. Please see Spring Reference: Using @Transactional :

The @Transactional annotation may be placed before an interface definition, a method on an interface, a class definition, or a public method on a class

Python: Fetch first 10 results from a list

list[:10]

will give you the first 10 elements of this list using slicing.

However, note, it's best not to use list as a variable identifier as it's already used by Python: list()

To find out more about these type of operations you might find this tutorial on lists helpful and the link @DarenThomas provided Explain Python's slice notation - thanks Daren)

MySQLi count(*) always returns 1

$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.

How to programmatically tell if a Bluetooth device is connected?

Add bluetooth permission to your AndroidManifest,

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

Then use intent filters to listen to the ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, and ACTION_ACL_DISCONNECTED broadcasts:

public void onCreate() {
    ...
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter);
}

//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           ... //Device found
        }
        else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
           ... //Device is now connected
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
           ... //Done searching
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
           ... //Device is about to disconnect
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
           ... //Device has disconnected
        }           
    }
};

A few notes:

  • There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to QUERY, instead it allows you to listen to CHANGES.
  • A hoaky work around to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected).
  • Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

How to calculate the sum of the datatable column in asp.net?

I think this solves

using System.Linq;


(datagridview1.DataSource as DataTable).AsEnumerable().Sum(c => c.Field<double>("valor"))

Find and replace string values in list

In case you're wondering about the performance of the different approaches, here are some timings:

In [1]: words = [str(i) for i in range(10000)]

In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop

In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop

In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop

In [5]: import re

In [6]: r = re.compile('1')

In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop

as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:

In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop

In [9]: r = re.compile('(1|324|567)')

In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop

This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.

Delete multiple rows by selecting checkboxes using PHP

You should treat it as an array like this,

<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">

Then only, you can take its count and loop it for deletion.

You also need to pass the database connection to the query.

$result = mysqli_query($dbc, $sql);

Yours did not include it:

$result = mysqli_query($sql);

CSS opacity only to background color, not the text on it?

A great way to do this would be to use CSS 3 indeed.

Create a div width a class - e.g. supersizer on top of your page:

Then set following CSS properties:

_x000D_
_x000D_
  .supersizer {_x000D_
    background: url("http://fc06.deviantart.net/fs70/f/2012/099/d/f/stackoverflow_16x16_icon_by_muntoo_stock-d4vl2v4.png") no-repeat center center fixed;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    position: fixed;_x000D_
    z-index: -1;_x000D_
    opacity: 0.5;_x000D_
    -webkit-background-size: cover;_x000D_
    -moz-background-size: cover;_x000D_
    -o-background-size: cover;_x000D_
    background-size: cover;_x000D_
    top: 0;_x000D_
  }
_x000D_
<div class="supersizer"></div>
_x000D_
_x000D_
_x000D_

Javascript: best Singleton pattern

function SingletonClass() 
{
    // demo variable
    var names = [];

    // instance of the singleton
    this.singletonInstance = null;

    // Get the instance of the SingletonClass
    // If there is no instance in this.singletonInstance, instanciate one
    var getInstance = function() {
        if (!this.singletonInstance) {
            // create a instance
            this.singletonInstance = createInstance();
        }

        // return the instance of the singletonClass
        return this.singletonInstance;
    }

    // function for the creation of the SingletonClass class
    var createInstance = function() {

        // public methodes
        return {
            add : function(name) {
                names.push(name);
            },
            names : function() {
                return names;
            }
        }
    }

    // wen constructed the getInstance is automaticly called and return the SingletonClass instance 
    return getInstance();
}

var obj1 = new SingletonClass();
obj1.add("Jim");
console.log(obj1.names());
// prints: ["Jim"]

var obj2 = new SingletonClass();
obj2.add("Ralph");
console.log(obj1.names());
// Ralph is added to the singleton instance and there for also acceseble by obj1
// prints: ["Jim", "Ralph"]
console.log(obj2.names());
// prints: ["Jim", "Ralph"]

obj1.add("Bart");
console.log(obj2.names());
// prints: ["Jim", "Ralph", "Bart"]

Django template how to look up a dictionary value with a variable

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

I faced the same issue in my scenario as follow:

I created textbook table first with

create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );

Then chapter table:

create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40), constraint pk_chapter primary key(txtbk_isbn,chapter_title), constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));

Then topic table:

create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));

Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:

create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20), primary key (txtbk_isbn, chapter_title, topic_id), foreign key (txtbk_isbn) references textbook(txtbk_isbn), foreign key (chapter_title) references chapter(chapter_title), foreign key (topic_id) references topic (topic_id));

The solution was to refer to composite foreign key as below:

create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20), primary key (txtbk_isbn, chapter_title, topic_id), foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title), foreign key (topic_id) references topic (topic_id));

Thanks to APC post in which he mentioned in his post a statement that:

Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED

How do I best silence a warning about unused variables?

C++17 Update

In C++17 we gain the attribute [[maybe_unused]] which is covered in [dcl.attr.unused]

The attribute-token maybe_unused indicates that a name or entity is possibly intentionally unused. It shall appear at most once in each attribute-list and no attribute-argument-clause shall be present. ...

Example:

 [[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2) {
  [[maybe_unused]] bool b = thing1 && thing2;
    assert(b);
 }

Implementations should not warn that b is unused, whether or not NDEBUG is defined. —end example ]

For the following example:

int foo ( int bar) {
    bool unused_bool ;
    return 0;
}

Both clang and gcc generate a diagnostic using -Wall -Wextra for both bar and unused_bool (See it live).

While adding [[maybe_unused]] silences the diagnostics:

int foo ([[maybe_unused]] int bar) {
    [[maybe_unused]] bool unused_bool ;
    return 0;
}

see it live.

Before C++17

In C++11 an alternative form of the UNUSED macro could be formed using a lambda expression(via Ben Deane) with an capture of the unused variable:

#define UNUSED(x) [&x]{}()

The immediate invocation of the lambda expression should be optimized away, given the following example:

int foo (int bar) {
    UNUSED(bar) ;
    return 0;
}

we can see in godbolt that the call is optimized away:

foo(int):
xorl    %eax, %eax
ret

How to compare two double values in Java?

You can use Double.compare; It compares the two specified double values.

Fastest way to count number of occurrences in a Python list

Combination of lambda and map function can also do the job:

list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2

How to display loading message when an iFrame is loading?

I think that this code is going to help:

JS:

$('#foo').ready(function () {
    $('#loadingMessage').css('display', 'none');
});
$('#foo').load(function () {
    $('#loadingMessage').css('display', 'none');
});

HTML:

<iframe src="http://google.com/" id="foo"></iframe>
<div id="loadingMessage">Loading...</div>

CSS:

#loadingMessage {
    width: 100%;
    height: 100%;
    z-index: 1000;
    background: #ccc;
    top: 0px;
    left: 0px;
    position: absolute;
}

Error - is not marked as serializable

You need to add a Serializable attribute to the class which you want to serialize.

[Serializable]
public class OrgPermission

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

instanceof cannot be used with primitive types or generic types either. As in the following code:

//Define Class< T > type ... 

Object e = new Object();

if(e instanceof T) {
  // Do something.
}

The error is: Cannot perform instanceof check against type parameter T. Use it's erasure Object instead since further generic type information will be erased at runtime.

Does not compile due to type erasure removing the runtime reference. However, the code below will compile:

if( type.isAssignableFrom(e.getClass())){
  // Do something.
}

Get most recent row for given ID

SELECT * FROM (SELECT * FROM tb1 ORDER BY signin DESC) GROUP BY id;

Closing Excel Application using VBA

I think your problem is that it's closing the document that calls the macro before sending the command to quit the application.

Your solution in that case is to not send a command to close the workbook. Instead, you could set the "Saved" state of the workbook to true, which would circumvent any messages about closing an unsaved book. Note: this does not save the workbook; it just makes it look like it's saved.

ThisWorkbook.Saved = True

and then, right after

Application.Quit

How to correctly represent a whitespace character

Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " ".

Paging with LINQ for objects

var pages = items.Select((item, index) => new { item, Page = index / batchSize }).GroupBy(g => g.Page);

Batchsize will obviously be an integer. This takes advantage of the fact that integers simply drop decimal places.

I'm half joking with this response, but it will do what you want it to, and because it's deferred, you won't incur a large performance penalty if you do

pages.First(p => p.Key == thePage)

This solution is not for LinqToEntities, I don't even know if it could turn this into a good query.

Split string into array of characters?

According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))

Generating sql insert into for Oracle

You can do that in PL/SQL Developer v10.
1. Click on Table that you want to generate script for.
2. Click Export data.
3. Check if table is selected that you want to export data for.
4. Click on SQL inserts tab.
5. Add where clause if you don't need the whole table.
6. Select file where you will find your SQL script.
7. Click export.
enter image description here

Update Row if it Exists Else Insert Logic with Entity Framework

Corrected

public static void InsertOrUpdateRange<T, T2>(this T entity, List<T2> updateEntity) 
        where T : class
        where T2 : class
        {
            foreach(var e in updateEntity)
            {
                context.Set<T2>().InsertOrUpdate(e);
            }
        }


        public static void InsertOrUpdate<T, T2>(this T entity, T2 updateEntity) 
        where T : class
        where T2 : class
        {
            if (context.Entry(updateEntity).State == EntityState.Detached)
            {
                if (context.Set<T2>().Any(t => t == updateEntity))
                {
                   context.Set<T2>().Update(updateEntity); 
                }
                else
                {
                    context.Set<T2>().Add(updateEntity);
                }

            }
            context.SaveChanges();
        }

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

How to convert password into md5 in jquery?

jQuery doesnt have a method to provide the md5 of a string. So you need to use some external script. There is a plugin called jQuery MD5. and it gives you number of methods to achieve md5. Few of those are

Create (hex-encoded) MD5 hash of a given string value:

var md5 = $.md5('value');

Create (hex-encoded) HMAC-MD5 hash of a given string value and key:

var md5 = $.md5('value', 'key');

Create raw MD5 hash of a given string value:

var md5 = $.md5('value', null, true);

Create raw HMAC-MD5 hash of a given string value and key:

var md5 = $.md5('value', 'key', true);

This might do what you want... Check the snippet here. jQuery MD5

Build error: You must add a reference to System.Runtime

For me helped only this code line:

Assembly.Load("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");

python: get directory two levels up

You can use this as a generic solution:

import os

def getParentDir(path, level=1):
  return os.path.normpath( os.path.join(path, *([".."] * level)) )

passing several arguments to FUN of lapply (and others *apply)

myfun <- function(x, arg1) {
 # doing something here with x and arg1
}

x is a vector or a list and myfun in lapply(x, myfun) is called for each element of x separately.

Option 1

If you'd like to use whole arg1 in each myfun call (myfun(x[1], arg1), myfun(x[2], arg1) etc.), use lapply(x, myfun, arg1) (as stated above).

Option 2

If you'd however like to call myfun to each element of arg1 separately alongside elements of x (myfun(x[1], arg1[1]), myfun(x[2], arg1[2]) etc.), it's not possible to use lapply. Instead, use mapply(myfun, x, arg1) (as stated above) or apply:

 apply(cbind(x,arg1), 1, myfun)

or

 apply(rbind(x,arg1), 2, myfun).

How to remove unwanted space between rows and columns in table?

This worked for me:

#table {
  border-collapse: collapse;
  border-spacing: 0;
}

How do I convert a Swift Array to a String?

if you have string array list , then convert to Int

let arrayList = list.map { Int($0)!} 
     arrayList.description

it will give you string value

Why do I get a "permission denied" error while installing a gem?

I think the problem happened when you use rbenv. Try the below commands to fix it.

rbenv shell {rb_version}
rbenv global {rb_version}
or 
rbenv local {rb_version}

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

For .NET CORE 3.1

I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them

What i mean is:

change this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseHttpsRedirection();  

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

      ...

     }

to this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

      ...
        
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseHttpsRedirection(); 

      ...

     }

By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.

extract month from date in python

>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Hide element by class in pure Javascript

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/

Bootstrap 3.0 Popovers and tooltips

If you're using Rails and ActiveAdmin, this is going to be your problem: https://github.com/seyhunak/twitter-bootstrap-rails/issues/450 Basically, a conflict with active_admin.js

This is the solution: https://stackoverflow.com/a/11745446/264084 (Karen's answer) tldr: Move active_admin assets into the "vendor" directory.

Swift: Display HTML data in a label or textView

Here is a Swift 3 version:

private func getHtmlLabel(text: String) -> UILabel {
    let label = UILabel()
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.attributedString = stringFromHtml(string: text)
    return label
}

private func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                             documentAttributes: nil)
            return str
        }
    } catch {
    }
    return nil
}

I found issues with some of the other answers here and it took me a bit to get this right. I set the line break mode and number of lines so that the label sized appropriately when the HTML spanned multiple lines.

Error handling in getJSON calls

In some cases, you may run into a problem of synchronization with this method. I wrote the callback call inside a setTimeout function, and it worked synchronously just fine =)

E.G:

function obterJson(callback) {


    jqxhr = $.getJSON(window.location.href + "js/data.json", function(data) {

    setTimeout(function(){
        callback(data);
    },0);
}

How can I call a method in Objective-C?

use this,
[self score]; 
instead of @selector(score).

Simple conversion between java.util.Date and XMLGregorianCalendar

You can use the this customization to change the default mapping to java.util.Date

<xsd:annotation>
<xsd:appinfo>
    <jaxb:globalBindings>
        <jaxb:javaType name="java.util.Date" xmlType="xsd:dateTime"
                 parseMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.parseDateTime"
                 printMethod="org.apache.cxf.xjc.runtime.DataTypeAdapter.printDateTime"/>
    </jaxb:globalBindings>
</xsd:appinfo>

Why do I get a C malloc assertion failure?

My alternative solution to using Valgrind:

I'm very happy because I just helped my friend debug a program. His program had this exact problem (malloc() causing abort), with the same error message from GDB.

I compiled his program using Address Sanitizer with

gcc -Wall -g3 -fsanitize=address -o new new.c
              ^^^^^^^^^^^^^^^^^^

And then ran gdb new. When the program gets terminated by SIGABRT caused in a subsequent malloc(), a whole lot of useful information is printed:

=================================================================
==407==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6060000000b4 at pc 0x7ffffe49ed1a bp 0x7ffffffedc20 sp 0x7ffffffed3c8
WRITE of size 104 at 0x6060000000b4 thread T0
    #0 0x7ffffe49ed19  (/usr/lib/x86_64-linux-gnu/libasan.so.4+0x5ed19)
    #1 0x8001dab in CreatHT2 /home/wsl/Desktop/hash/new.c:59
    #2 0x80031cf in main /home/wsl/Desktop/hash/new.c:209
    #3 0x7ffffe061b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
    #4 0x8001679 in _start (/mnt/d/Desktop/hash/new+0x1679)

0x6060000000b4 is located 0 bytes to the right of 52-byte region [0x606000000080,0x6060000000b4)
allocated by thread T0 here:
    #0 0x7ffffe51eb50 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb50)
    #1 0x8001d56 in CreatHT2 /home/wsl/Desktop/hash/new.c:55
    #2 0x80031cf in main /home/wsl/Desktop/hash/new.c:209
    #3 0x7ffffe061b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)

Let's take a look at the output, especially the stack trace:

The first part says there's a invalid write operation at new.c:59. That line reads

memset(len,0,sizeof(int*)*p);
             ^^^^^^^^^^^^

The second part says the memory that the bad write happened on is created at new.c:55. That line reads

if(!(len=(int*)malloc(sizeof(int)*p))){
                      ^^^^^^^^^^^

That's it. It only took me less than half a minute to locate the bug that confused my friend for a few hours. He managed to locate the failure, but it's a subsequent malloc() call that failed, without being able to spot this error in previous code.

Sum up: Try the -fsanitize=address of GCC or Clang. It can be very helpful when debugging memory issues.

How to find the sum of an array of numbers

This is much easier

function sumArray(arr) {
    var total = 0;
    arr.forEach(function(element){
        total += element;
    })
    return total;
}

var sum = sumArray([1,2,3,4])

console.log(sum)

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Step by step self explaining commands for update of feature branch with the latest code from origin "develop" branch:

git checkout develop
git pull -p
git checkout feature_branch
git merge develop
git push origin feature_branch

How do I create a comma delimited string from an ArrayList?

Something like:

String.Join(",", myArrayList.toArray(string.GetType()) );

Which basically loops ya know...

EDIT

how about:

string.Join(",", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString));

Found conflicts between different versions of the same dependent assembly that could not be resolved

I had this warning after migrating to Package Reference. In diagnostic output there was information that library was referenced by the same library itself. It might be a bug of new Package Reference. The solution was to enable AutoGenerateBindingRedirects and delete custom binding redirect.

Multiple conditions in ngClass - Angular 4

you need object notation

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

ref: NgClass

Wait 5 seconds before executing next line

Try this:

//the code will execute in 1 3 5 7 9 seconds later
function exec() {
    for(var i=0;i<5;i++) {
        setTimeout(function() {
            console.log(new Date());   //It's you code
        },(i+i+1)*1000);
    }
}

alert() not working in Chrome

put this line at the end of the body. May be the DOM is not ready yet at the moment this line is read by compiler.

<script type="text/javascript" src="script.js"></script>"

Docker - Container is not running

Here is what worked for me.

Get the container ID and restart.

docker ps -a --no-trunc 

ace7ca65e6e3fdb678d9cdfb33a7a165c510e65c3bc28fecb960ac993c37ef33


docker restart ace7ca65e6e3fdb678d9cdfb33a7a165c510e65c3bc28fecb960ac993c37ef33

Determining the size of an Android view at runtime

There are actually multiple solutions, depending on the scenario:

  1. The safe method, will work just before drawing the view, after the layout phase has finished:
public static void runJustBeforeBeingDrawn(final View view, final Runnable runnable) {
    final OnPreDrawListener preDrawListener = new OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            runnable.run();
            return true;
        }
    };
    view.getViewTreeObserver().addOnPreDrawListener(preDrawListener); 
}

Sample usage:

    ViewUtil.runJustBeforeBeingDrawn(yourView, new Runnable() {
        @Override
        public void run() {
            //Here you can safely get the view size (use "getWidth" and "getHeight"), and do whatever you wish with it
        }
    });
  1. On some cases, it's enough to measure the size of the view manually:
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int width=view.getMeasuredWidth(); 
int height=view.getMeasuredHeight();

If you know the size of the container:

    val widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxWidth, View.MeasureSpec.AT_MOST)
    val heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(maxHeight, View.MeasureSpec.AT_MOST)
    view.measure(widthMeasureSpec, heightMeasureSpec)
    val width=view.measuredWidth
    val height=view.measuredHeight
  1. if you have a custom view that you've extended, you can get its size on the "onMeasure" method, but I think it works well only on some cases :
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
    final int newHeight= MeasureSpec.getSize(heightMeasureSpec);
    final int newWidth= MeasureSpec.getSize(widthMeasureSpec);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
  1. If you write in Kotlin, you can use the next function, which behind the scenes works exactly like runJustBeforeBeingDrawn that I've written:

     view.doOnPreDraw { actionToBeTriggered() }
    

Note that you need to add this to gradle (found via here) :

android {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

implementation 'androidx.core:core-ktx:#.#'

How can I find out if an .EXE has Command-Line Options?

This is what I get from console on Windows 10:

C:\>find /?
Searches for a text string in a file or files.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]

  /V         Displays all lines NOT containing the specified string.
  /C         Displays only the count of lines containing the string.
  /N         Displays line numbers with the displayed lines.
  /I         Ignores the case of characters when searching for the string.
  /OFF[LINE] Do not skip files with offline attribute set.
  "string"   Specifies the text string to find.
  [drive:][path]filename
             Specifies a file or files to search.

If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.

What's causing my java.net.SocketException: Connection reset?

FWIW, I was getting this error when I was accidentally making a GET request to an endpoint that was expecting a POST request. Presumably that was just that particular servers way of handling the problem.

Extract file name from path, no matter what the os/path format

import os
file_location = '/srv/volume1/data/eds/eds_report.csv'
file_name = os.path.basename(file_location )  #eds_report.csv
location = os.path.dirname(file_location )    #/srv/volume1/data/eds

How to return dictionary keys as a list in Python?

A bit off on the "duck typing" definition -- dict.keys() returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)

In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list().

Very similarly for zip() -- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?

This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.

dict.keys() should work with comprehensions, though -- check carefully for typos or something... it works fine for me:

>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]

How to read pickle file?

The following is an example of how you might write and read a pickle file. Note that if you keep appending pickle data to the file, you will need to continue reading from the file until you find what you want or an exception is generated by reaching the end of the file. That is what the last function does.

import os
import pickle


PICKLE_FILE = 'pickle.dat'


def main():
    # append data to the pickle file
    add_to_pickle(PICKLE_FILE, 123)
    add_to_pickle(PICKLE_FILE, 'Hello')
    add_to_pickle(PICKLE_FILE, None)
    add_to_pickle(PICKLE_FILE, b'World')
    add_to_pickle(PICKLE_FILE, 456.789)
    # load & show all stored objects
    for item in read_from_pickle(PICKLE_FILE):
        print(repr(item))
    os.remove(PICKLE_FILE)


def add_to_pickle(path, item):
    with open(path, 'ab') as file:
        pickle.dump(item, file, pickle.HIGHEST_PROTOCOL)


def read_from_pickle(path):
    with open(path, 'rb') as file:
        try:
            while True:
                yield pickle.load(file)
        except EOFError:
            pass


if __name__ == '__main__':
    main()

How to pass parameters in $ajax POST?

function funcion(y) {
$.ajax({
   type: 'POST',
   url: '/ruta',
   data: {"x": y},
   contentType: "application/x-www-form-urlencoded;charset=utf8",
});
}

Change placeholder text

Using jquery you can do this by following code:

<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>

$('#tbxEmail').attr('placeholder','Some New Text');

Why am I getting this redefinition of class error?

You're defining the class in the header file, include the header file into a *.cpp file and define the class a second time because the first definition is dragged into the translation unit by the header file. But only one gameObject class definition is allowed per translation unit.

You actually don't need to define the class a second time just to implement the functions. Implement the functions like this:

#include "gameObject.h"

gameObject::gameObject(int inx, int iny)
{
    x = inx;
    y = iny;
}

int gameObject::add()
{
    return x+y;
}

etc

How can I convert ticks to a date format?

Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.

public class Time
{
    public static void Timestamps()
    {
        OutputTimestamp();
        Thread.Sleep(1000);
        OutputTimestamp();
    }

    private static void OutputTimestamp()
    {
        var timestamp = DateTime.UtcNow.Ticks;
        var localTicks = DateTime.Now.Ticks;
        var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
        Console.Out.WriteLine("Timestamp = {0}.  Local ticks = {1}.  Local time = {2}.", timestamp, localTicks, localTime);
    }
}

Output:

Timestamp = 636988286338754530.  Local ticks = 636988034338754530.  Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736.  Local ticks = 636988034348878736.  Local time = 2019-07-15 4:03:54 PM.

Getting RAW Soap Data from a Web Reference Client running in ASP.net

It looks like Tim Carter's solution doesn't work if the call to the web reference throws an exception. I've been trying to get at the raw web resonse so I can examine it (in code) in the error handler once the exception is thrown. However, I'm finding that the response log written by Tim's method is blank when the call throws an exception. I don't completely understand the code, but it appears that Tim's method cuts into the process after the point where .Net has already invalidated and discarded the web response.

I'm working with a client that's developing a web service manually with low level coding. At this point, they are adding their own internal process error messages as HTML formatted messages into the response BEFORE the SOAP formatted response. Of course, the automagic .Net web reference blows up on this. If I could get at the raw HTTP response after an exception is thrown, I could look for and parse any SOAP response within the mixed returning HTTP response and know that they received my data OK or not.

Later ...

Here's a solution that does work, even after an execption (note that I'm only after the response - could get the request too):

namespace ChuckBevitt
{
    class GetRawResponseSoapExtension : SoapExtension
    {
        //must override these three methods
        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        {
            return null;
        }
        public override object GetInitializer(Type serviceType)
        {
            return null;
        }
        public override void Initialize(object initializer)
        {
        }

        private bool IsResponse = false;

        public override void ProcessMessage(SoapMessage message)
        {
            //Note that ProcessMessage gets called AFTER ChainStream.
            //That's why I'm looking for AfterSerialize, rather than BeforeDeserialize
            if (message.Stage == SoapMessageStage.AfterSerialize)
                IsResponse = true;
            else
                IsResponse = false;
        }

        public override Stream ChainStream(Stream stream)
        {
            if (IsResponse)
            {
                StreamReader sr = new StreamReader(stream);
                string response = sr.ReadToEnd();
                sr.Close();
                sr.Dispose();

                File.WriteAllText(@"C:\test.txt", response);

                byte[] ResponseBytes = Encoding.ASCII.GetBytes(response);
                MemoryStream ms = new MemoryStream(ResponseBytes);
                return ms;

            }
            else
                return stream;
        }
    }
}

Here's how you configure it in the config file:

<configuration>
     ...
  <system.web>
    <webServices>
      <soapExtensionTypes>
        <add type="ChuckBevitt.GetRawResponseSoapExtension, TestCallWebService"
           priority="1" group="0" />
      </soapExtensionTypes>
    </webServices>
  </system.web>
</configuration>

"TestCallWebService" shoud be replaced with the name of the library (that happened to be the name of the test console app I was working in).

You really shouldn't have to go to ChainStream; you should be able to do it more simply from ProcessMessage as:

public override void ProcessMessage(SoapMessage message)
{
    if (message.Stage == SoapMessageStage.BeforeDeserialize)
    {
        StreamReader sr = new StreamReader(message.Stream);
        File.WriteAllText(@"C:\test.txt", sr.ReadToEnd());
        message.Stream.Position = 0; //Will blow up 'cause type of stream ("ConnectStream") doesn't alow seek so can't reset position
    }
}

If you look up SoapMessage.Stream, it's supposed to be a read-only stream that you can use to inspect the data at this point. This is a screw-up 'cause if you do read the stream, subsequent processing bombs with no data found errors (stream was at end) and you can't reset the position to the beginning.

Interestingly, if you do both methods, the ChainStream and the ProcessMessage ways, the ProcessMessage method will work because you changed the stream type from ConnectStream to MemoryStream in ChainStream, and MemoryStream does allow seek operations. (I tried casting the ConnectStream to MemoryStream - wasn't allow.)

So ..... Microsoft should either allow seek operations on the ChainStream type or make the SoapMessage.Stream truly a read-only copy as it's supposed to be. (Write your congressman, etc...)

One further point. After creating a way to retreive the raw HTTP response after an exception, I still didn't get the full response (as determined by a HTTP sniffer). This was because when the development web service added the HTML error messages to the beginning of the response, it didn't adjust the Content-Length header, so the Content-Length value was less than the size of the actual response body. All I got was the Content-Length value number of characters - the rest were missing. Obviously, when .Net reads the response stream, it just reads the Content-Length number of characters and doesn't allow for the Content-Length value possibily being wrong. This is as it should be; but if the Content-Length header value is wrong, the only way you'll ever get the entire response body is with a HTTP sniffer (I user HTTP Analyzer from http://www.ieinspector.com).

Align labels in form next to input

Here is generic labels width for all form labels. Nothing fix width.

call setLabelWidth calculator with all the labels. This function will load all labels on UI and find out maximum label width. Apply return value of below function to all the labels.

     this.setLabelWidth = function (labels) {
            var d = labels.join('<br>'),
                dummyelm = jQuery("#lblWidthCalcHolder"),
                width;
            dummyelm.empty().html(d);
            width = Math.ceil(dummyelm[0].getBoundingClientRect().width);
            width = width > 0 ? width + 5: width;
            //this.resetLabels(); //to reset labels.
            var element = angular.element("#lblWidthCalcHolder")[0];
            element.style.visibility = "hidden";
            //Removing all the lables from the element as width is calculated and the element is hidden
            element.innerHTML = "";
            return {
                width: width,
                validWidth: width !== 0
            };

        };

Rails update_attributes without save?

For mass assignment of values to an ActiveRecord model without saving, use either the assign_attributes or attributes= methods. These methods are available in Rails 3 and newer. However, there are minor differences and version-related gotchas to be aware of.

Both methods follow this usage:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }

@user.attributes = { model: "Sierra", year: "2012", looks: "Sexy" }

Note that neither method will perform validations or execute callbacks; callbacks and validation will happen when save is called.

Rails 3

attributes= differs slightly from assign_attributes in Rails 3. attributes= will check that the argument passed to it is a Hash, and returns immediately if it is not; assign_attributes has no such Hash check. See the ActiveRecord Attribute Assignment API documentation for attributes=.

The following invalid code will silently fail by simply returning without setting the attributes:

@user.attributes = [ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ]

attributes= will silently behave as though the assignments were made successfully, when really, they were not.

This invalid code will raise an exception when assign_attributes tries to stringify the hash keys of the enclosing array:

@user.assign_attributes([ { model: "Sierra" }, { year: "2012" }, { looks: "Sexy" } ])

assign_attributes will raise a NoMethodError exception for stringify_keys, indicating that the first argument is not a Hash. The exception itself is not very informative about the actual cause, but the fact that an exception does occur is very important.

The only difference between these cases is the method used for mass assignment: attributes= silently succeeds, and assign_attributes raises an exception to inform that an error has occurred.

These examples may seem contrived, and they are to a degree, but this type of error can easily occur when converting data from an API, or even just using a series of data transformation and forgetting to Hash[] the results of the final .map. Maintain some code 50 lines above and 3 functions removed from your attribute assignment, and you've got a recipe for failure.

The lesson with Rails 3 is this: always use assign_attributes instead of attributes=.

Rails 4

In Rails 4, attributes= is simply an alias to assign_attributes. See the ActiveRecord Attribute Assignment API documentation for attributes=.

With Rails 4, either method may be used interchangeably. Failure to pass a Hash as the first argument will result in a very helpful exception: ArgumentError: When assigning attributes, you must pass a hash as an argument.

Validations

If you're pre-flighting assignments in preparation to a save, you might be interested in validating before save, as well. You can use the valid? and invalid? methods for this. Both return boolean values. valid? returns true if the unsaved model passes all validations or false if it does not. invalid? is simply the inverse of valid?

valid? can be used like this:

@user.assign_attributes{ model: "Sierra", year: "2012", looks: "Sexy" }.valid?

This will give you the ability to handle any validations issues in advance of calling save.

PHP check whether property exists in object or class

Solution

echo $person->middleName ?? 'Person does not have a middle name';

To show how this would look in an if statement for more clarity on how this is working.

if($person->middleName ?? false) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

Explanation

The traditional PHP way to check for something's existence is to do:

if(isset($person->middleName)) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

OR for a more class specific way:

if(property_exists($person, 'middleName')) {
    echo $person->middleName;
} else {
    echo 'Person does not have a middle name';
}

These are both fine in long form statements but in ternary statements they become unnecessarily cumbersome like so:

isset($person->middleName) ? echo $person->middleName : echo 'Person does not have a middle name';

You can also achieve this with just the ternary operator like so:

echo $person->middleName ?: 'Person does not have a middle name';

But... if the value does not exist (is not set) it will raise an E_NOTICE and is not best practise. If the value is null it will not raise the exception.

Therefore ternary operator to the rescue making this a neat little answer:

echo $person->middleName ?? 'Person does not have a middle name';

Display help message with python argparse when script is called without any arguments

If your command is something where a user needs to choose some action, then use a mutually exclusive group with required=True.

This is kind of an extension to the answer given by pd321.

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--batch", action='store', type=int,  metavar='pay_id')
group.add_argument("--list", action='store_true')
group.add_argument("--all", action='store_true', help='check all payments')

args=parser.parse_args()

if args.batch:
    print('batch {}'.format(args.batch))

if args.list:
    print('list')

if args.all:
    print('all')

Output:

$ python3 a_test.py
usage: a_test.py [-h] (--batch pay_id | --list | --all)
a_test.py: error: one of the arguments --batch --list --all is required

This only give the basic help. And some of the other answers will give you the full help. But at least your users know they can do -h

How to create number input field in Flutter?

You can use Form Builder Package to display any type of form field. For number input field,

FormBuilderTextField(
     keyboardType: TextInputType.number,
     validators: [
          FormBuilderValidators.numeric(),
     ],
),

Git diff between current branch and master but not including unmerged master commits

Here's what worked for me:

git diff origin/master...

This shows only the changes between my currently selected local branch and the remote master branch, and ignores all changes in my local branch that came from merge commits.

IO Error: The Network Adapter could not establish the connection

In my case, I needed to specify a viahost and viauser. Worth trying if you're in a complex system. :)

Add onclick event to newly added element in JavaScript

You can also set attribute:

elem.setAttribute("onclick","alert('blah');");

How do I deal with corrupted Git object files?

For anyone stumbling across the same issue:

I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.

Java String new line

If you simply want to print a newline in the console you can use ´\n´ for newlines.

If you want to break text in swing components you can use html:

String s = "<html>first line<br />second line</html>";

Is it possible to capture the stdout from the sh DSL command in the pipeline

Now, the sh step supports returning stdout by supplying the parameter returnStdout.

// These should all be performed at the point where you've
// checked out your sources on the slave. A 'git' executable
// must be available.
// Most typical, if you're not cloning into a sub directory
gitCommit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
// short SHA, possibly better for chat notifications, etc.
shortCommit = gitCommit.take(6)

See this example.

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Which characters are valid in CSS class names/selectors?

Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)

edit: relevant paragraph follows:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:

In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:

'-' + vendor identifier + '-' + meaningful name 
'_' + vendor identifier + '-' + meaningful name

Example(s):

For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.

Other known examples:

 -moz-box-sizing
 -moz-border-radius
 -wap-accesskey

An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.

Authors should avoid vendor-specific extensions

How to make a simple collection view with Swift

This project has been tested with Xcode 10 and Swift 4.2.

Create a new project

It can be just a Single View App.

Add the code

Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in the storyboard.

import UIKit
class MyCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet weak var myLabel: UILabel!
}

We will connect this outlet later.

Open ViewController.swift and make sure you have the following content:

import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]
    
    
    // MARK: - UICollectionViewDataSource protocol
    
    // tell the collection view how many cells to make
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }
    
    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
        
        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project
        
        return cell
    }
    
    // MARK: - UICollectionViewDelegate protocol
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }
}

Notes

  • UICollectionViewDataSource and UICollectionViewDelegate are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout protocol to change the size of the views programmatically, but it isn't necessary.
  • We are just putting simple strings in our grid, but you could certainly do images later.

Set up the storyboard

Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.

enter image description here

Make sure that your defaults in the Attribute Inspector are also

  • Items: 1
  • Layout: Flow

The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.

enter image description here

Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell" in ViewController.swift.

enter image description here

And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell, our custom class that we made.

enter image description here

Hook up the outlets

  • Hook the Label in the collection cell to myLabel in the MyCollectionViewCell class. (You can Control-drag.)
  • Hook the Collection View delegate and dataSource to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)

enter image description here

Finished

Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.

enter image description here

Making Improvements

The example above works but it is rather ugly. Here are a few things you can play with:

Background color

In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.

Cell spacing

Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.

Cell shape

If you want rounded corners, a border, and the like, you can play around with the cell layer. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan in code above.

cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8

See this answer for other things you can do with the layer (shadow, for example).

Changing the color when tapped

It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController class:

// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.red
}

// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.cyan
}

Here is the updated look:

enter image description here

Further study

UITableView version of this Q&A

TextView bold via xml file?

Just you need to use 

//for bold
android:textStyle="bold"

//for italic
android:textStyle="italic"

//for normal
android:textStyle="normal"

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:text="@string/userName"
    android:layout_gravity="left"
    android:textSize="16sp"
/>

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

replace

implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

with

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Since the version with jre is absolute , just replace and sync the project

Official Documentation here Thanks for the link @ ROMANARMY

Happy Coding :)

How can I determine whether a specific file is open in Windows?

The equivalent of lsof -p pid is the combined output from sysinternals handle and listdlls, ie

handle -p pid
listdlls -p pid

you can find out pid with sysinternals pslist.

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

This is the error that is returned when the Windows Firewall blocks the port (out-going). We have a strict web server so the outgoing ports are blocked by default. All I had to do was to create a rule to allow the TCP port number in wf.msc.

Check if DataRow exists by column name in c#?

You can use

try {
   user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
   // do something if you want 
}

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

The inline-block display style seems to do what you want. Note that the <nobr> tag is deprecated, and should not be used. Non-breaking white space is doable in CSS. Here's how I would alter your example style rules:

div { display: inline-block; white-space: nowrap; }
.success { background-color: #ccffcc; }

Alter your stylesheet, remove the <nobr> tags from your source, and give it a try. Note that display: inline-block does not work in every browser, though it tends to only be problematic in older browsers (newer versions should support it to some degree). My personal opinion is to ignore coding for broken browsers. If your code is standards compliant, it should work in all of the major, modern browsers. Anyone still using IE6 (or earlier) deserves the pain. :-)

How to make div fixed after you scroll to that div?

Adding on to @Alexandre Aimbiré's answer - sometimes you may need to specify z-index:1 to have the element always on top while scrolling. Like this:

position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;

Force IE10 to run in IE10 Compatibility View?

You can try :

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >

Just like you tried before, but caution:

It seems like the X-UA-Compatible tag has to be the first tag in the < head > section

If this conclusion is correct, then I believe it is undocumented in Microsoft’s blogs/msdn (and if it is documented, then it isn’t sticking out well enough from the docs). Ensuring that this was the first meta tag in the forced IE9 to switch to IE8 mode successfully

Difference between variable declaration syntaxes in Javascript (including global variables)?

Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window)

This is an example of his idea:

Html

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="init.js"></script>
    <script type="text/javascript">
      MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
    </script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello !</h1>
  </body>    
</html>

init.js (Based on this answer)

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function(i) {
            return _args[i];
        }
    };
}());

script.js

// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

Here's the plnkr. Hope it help !

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

You should execute the next query:

GRANT ALL ON TABLE mytable TO myuser;

Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:

GRANT ALL ON TABLE tbm_grupo TO myuser;

How to Call a Function inside a Render in React/Jsx

_x000D_
_x000D_
class App extends React.Component {_x000D_
  _x000D_
  buttonClick(){_x000D_
    console.log("came here")_x000D_
    _x000D_
  }_x000D_
  _x000D_
  subComponent() {_x000D_
    return (<div>Hello World</div>);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    return ( _x000D_
      <div className="patient-container">_x000D_
          <button onClick={this.buttonClick.bind(this)}>Click me</button>_x000D_
          {this.subComponent()}_x000D_
       </div>_x000D_
     )_x000D_
  }_x000D_
  _x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)

UPDATE

This is how you call a method outside the render.

buttonClick(){
    console.log("came here")
}

render() {
   return (
       <div className="patient-container">
          <button onClick={this.buttonClick.bind(this)}>Click me</button>
       </div>
   );
}

The recommended way is to write a separate component and import it.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Unable to find velocity template resources

Great question - I solved my issue today as follows using Ecilpse:

  1. Put your template in the same folder hierarchy as your source code (not in a separate folder hierarchy even if you include it in the build path) as below: Where to put your template file

  2. In your code simply use the following lines of code (assuming you just want the date to be passed as data):

    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    VelocityContext context = new VelocityContext();
    context.put("date", getMyTimestampFunction());
    Template t = ve.getTemplate( "templates/email_html_new.vm" );
    StringWriter writer = new StringWriter();
    t.merge( context, writer );
    

See how first we tell VelocityEngine to look in the classpath. Without this it wouldn't know where to look.

How to compare DateTime without time via LINQ?

It happens that LINQ doesn't like properties such as DateTime.Date. It just can't convert to SQL queries. So I figured out a way of comparing dates using Jon's answer, but without that naughty DateTime.Date. Something like this:

var q = db.Games.Where(t => t.StartDate.CompareTo(DateTime.Today) >= 0).OrderBy(d => d.StartDate);

This way, we're comparing a full database DateTime, with all that date and time stuff, like 2015-03-04 11:49:45.000 or something like this, with a DateTime that represents the actual first millisecond of that day, like 2015-03-04 00:00:00.0000.

Any DateTime we compare to that DateTime.Today will return us safely if that date is later or the same. Unless you want to compare literally the same day, in which case I think you should go for Caesar's answer.

The method DateTime.CompareTo() is just fancy Object-Oriented stuff. It returns -1 if the parameter is earlier than the DateTime you referenced, 0 if it is LITERALLY EQUAL (with all that timey stuff) and 1 if it is later.

Get parent of current directory from Python script

Using os.path

To get the parent directory of the directory containing the script (regardless of the current working directory), you'll need to use __file__.

Inside the script use os.path.abspath(__file__) to obtain the absolute path of the script, and call os.path.dirname twice:

from os.path import dirname, abspath
d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory

Basically, you can walk up the directory tree by calling os.path.dirname as many times as needed. Example:

In [4]: from os.path import dirname

In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')
Out[5]: '/home/kristina/desire-directory/scripts'

In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))
Out[6]: '/home/kristina/desire-directory'

If you want to get the parent directory of the current working directory, use os.getcwd:

import os
d = os.path.dirname(os.getcwd())

Using pathlib

You could also use the pathlib module (available in Python 3.4 or newer).

Each pathlib.Path instance have the parent attribute referring to the parent directory, as well as the parents attribute, which is a list of ancestors of the path. Path.resolve may be used to obtain the absolute path. It also resolves all symlinks, but you may use Path.absolute instead if that isn't a desired behaviour.

Path(__file__) and Path() represent the script path and the current working directory respectively, therefore in order to get the parent directory of the script directory (regardless of the current working directory) you would use

from pathlib import Path
# `path.parents[1]` is the same as `path.parent.parent`
d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')

and to get the parent directory of the current working directory

from pathlib import Path
d = Path().resolve().parent

Note that d is a Path instance, which isn't always handy. You can convert it to str easily when you need it:

In [15]: str(d)
Out[15]: '/home/kristina/desire-directory'

How can I create a simple index.html file which lists all files/directories?

For me PHP is the easiest way to do it:

<?php
echo "Here are our files";
$path = ".";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != ".." && $file != "index.php" && $file != ".htaccess" && $file != "error_log" && $file != "cgi-bin") {
        echo "<a href='$path/$file'>$file</a><br /><br />";
        $i++;
    }
}
closedir($dh);
?> 

Place this in your directory and set where you want it to search on the $path. The first if statement will hide your php file and .htaccess and the error log. It will then display the output with a link. This is very simple code and easy to edit.

Declare a dictionary inside a static class

Make the Dictionary a static, and never add to it outside of your static object's ctor. That seems to be a simpler solution than fiddling with the static/const rules in C#.

How to create a sticky left sidebar menu using bootstrap 3?

Bootstrap 3

Here is a working left sidebar example:

http://bootply.com/90936 (similar to the Bootstrap docs)

The trick is using the affix component along with some CSS to position it:

  #sidebar.affix-top {
    position: static;
    margin-top:30px;
    width:228px;
  }

  #sidebar.affix {
    position: fixed;
    top:70px;
    width:228px;
  }

EDIT- Another example with footer and affix-bottom


Bootstrap 4

The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top class is explained in this answer.

Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?

Select datatype of the field in postgres

run psql -E and then \d student_details

Verilog generate/genvar in an always block

If you do not mind having to compile/generate the file then you could use a pre processing technique. This gives you the power of the generate but results in a clean Verilog file which is often easier to debug and leads to less simulator issues.

I use RubyIt to generate verilog files from templates using ERB (Embedded Ruby).

parameter ROWBITS = <%= ROWBITS %> ;
always @(posedge sysclk) begin
  <% (0...ROWBITS).each do |addr| -%>
    temp[<%= addr %>] <= 1'b0;
  <% end -%>
end

Generating the module_name.v file with :

$ ruby_it --parameter ROWBITS=4 --outpath ./ --file ./module_name.rv

The generated module_name.v

parameter ROWBITS = 4 ;
always @(posedge sysclk) begin
  temp[0] <= 1'b0;
  temp[1] <= 1'b0;
  temp[2] <= 1'b0;
  temp[3] <= 1'b0;
end

How to use .htaccess in WAMP Server?

Open the httpd.conf file and search for

"rewrite"

, then remove

"#"

at the starting of the line,so the line looks like.

LoadModule rewrite_module modules/mod_rewrite.so

then restart the wamp.

Check if a file exists with wildcard in shell script

Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):

# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}

# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
   echo "No files not found"
elif [ $array_length -eq 1 ] ; then
   echo "File was found"
else
   echo "Files were found"
fi

for myfile in ${myarray[@]}
do
  echo "$myfile"
done

Yes, this does smell like Perl. Glad I didn't step in it ;)

Angular - POST uploaded file

In my project , I use the XMLHttpRequest to send multipart/form-data. I think it will fit you to.

and the uploader code

let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://www.example.com/rest/api', true);
xhr.withCredentials = true;
xhr.send(formData);

Here is example : https://github.com/wangzilong/angular2-multipartForm