Programs & Examples On #Extra

Terminal emulation for mainframes. IBM System z (Mainframe), IBM System i (AS/400), UNIX/Linux/OpenVMS (VT), and HP NonStop/Tandem systems.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

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.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

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

Fixed it by opting out of Ivy as per documentation.

https://angular.io/guide/ivy

Change tsconfig.app.json to opt out of Ivy.

"enableIvy": false

How to Install pip for python 3.7 on Ubuntu 18?

Install python pre-requisites

sudo apt update
sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget

Install python 3.7 (from ppa repository)

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt update
sudo apt install python3.7

Install pip3.7

sudo apt install python3-pip
python3.7 -m pip install pip

Create python and pip alternatives

sudo update-alternatives --install /usr/local/bin/python python /usr/bin/python3.7 10
sudo update-alternatives --install /usr/local/bin/pip pip /home/your_username/.local/bin/pip3.7 10

Make changes

source ~/.bashrc
python --version
pip --version

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

The easiest way I've found is delete Android Studio from the applications folder, then download & install it again.

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

Add this to your .prettierrc file and open the VSCODE

"endOfLine": "auto"

Can not find module “@angular-devkit/build-angular”

If you are using angular version 8 please run the below command to fix this issue.

ng update @angular/cli @angular/core

Could not find module "@angular-devkit/build-angular"

I resolved this by installing Angular on a 64 bit operating system. I was getting the error because I was initially running it on a 32 bit OS

Extract Google Drive zip from Google colab notebook

in my idea, you must go to a certain path for example:

from google.colab import drive drive.mount('/content/drive/') cd drive/MyDrive/f/

then :

!apt install unzip !unzip zip_folder.zip -d unzip_folder enter image description here

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

I have added in Application Class

@Bean
@ConfigurationProperties("app.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

application.properties I have added

app.datasource.url=jdbc:mysql://localhost/test
app.datasource.username=dbuser
app.datasource.password=dbpass
app.datasource.pool-size=30

More details Configure a Custom DataSource

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

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

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

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

import json

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

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

dict_list = json.loads(string)

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

This happened to me after I ran a script with cProfile a la python3 -m cProfile script.py even though xlrd was already installed and had never thrown this error before. it persisted even under python3 script.py. (Granted, I agree this wasn't what happened to OP, given the obvious import error)

However, for cases like mine, the following fixed the issue, despite being told "requirement already met" in every case.

pip install --upgrade pandas
pip install --upgrade xlrd

Pretty confounding stuff; not sure if cProfile was the cause or just a coincidence

The following should work, assuming your pip install operated on python2.

python3 -m pip install xlrd

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

Pandas: ValueError: cannot convert float NaN to integer

For identifying NaN values use boolean indexing:

print(df[df['x'].isnull()])

Then for removing all non-numeric values use to_numeric with parameter errors='coerce' - to replace non-numeric values to NaNs:

df['x'] = pd.to_numeric(df['x'], errors='coerce')

And for remove all rows with NaNs in column x use dropna:

df = df.dropna(subset=['x'])

Last convert values to ints:

df['x'] = df['x'].astype(int)

No provider for HttpClient

You are getting error for HttpClient so, you are missing HttpClientModule for that.

You should import it in app.module.ts file like this -

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

and mention it in the NgModule Decorator like this -

@NgModule({
...
imports:[ HttpClientModule ]
...
})

If this even doesn't work try clearing cookies of the browser and try restarting your server. Hopefully it may work, I was getting the same error.

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

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

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

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

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

package.json counts with a optionalDependencies key. NPM on Optional Dependencies.

You can add fsevents to this object and if you find yourself installing packages in a different platform than MacOS, fsevents will be skipped by either yarn or npm.

"optionalDependencies": {
  "fsevents": "2.1.2"
},

You will find a message like the following in the installation log:

info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.

Hope it helps!

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

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

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

In my case, it's happening in my shared module and I had to add the following into @NgModule:

...
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    IonicModule
  ],
...

Extract a page from a pdf as a jpeg

The pdf2image library can be used.

You can install it simply using,

pip install pdf2image

Once installed you can use following code to get images.

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

Saving pages in jpeg format

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

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

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

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

conda install -c conda-forge poppler

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

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

npm install -g npm-install-peers

it will add all the missing peers and remove all the error

How can I read pdf in python?

You can use textract module in python

Textract

for install

pip install textract

for read pdf

import textract
text = textract.process('path/to/pdf/file', method='pdfminer')

For detail Textract

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

RestClientException: Could not extract response. no suitable HttpMessageConverter found

I was trying to use Feign, while I encounter same issue, As I understood HTTP message converter will help but wanted to understand how to achieve this.

@FeignClient(name = "mobilesearch", url = "${mobile.search.uri}" ,
        fallbackFactory = MobileSearchFallbackFactory.class,
        configuration = MobileSearchFeignConfig.class)
public interface MobileSearchClient {

    @RequestMapping(method = RequestMethod.GET)
    List<MobileSearchResponse> getPhones();
}

You have to use Customer Configuration for the decoder, MobileSearchFeignConfig,

public class MobileSearchFeignConfig {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    @Bean
    public Decoder feignDecoder() {
        return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
    }

    public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
        return new ObjectFactory<HttpMessageConverters>() {
            @Override
            public HttpMessageConverters getObject() throws BeansException {
                return httpMessageConverters;
            }
        };
    }

    public class MappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
        MappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
            setSupportedMediaTypes(mediaTypes);
        }
    }

}

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

Remember to pipe Observables to async, like *ngFor item of items$ | async, where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair>, and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T.

Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty

Remove Unnamed columns in pandas dataframe

The approved solution doesn't work in my case, so my solution is the following one:

    ''' The column name in the example case is "Unnamed: 7"
 but it works with any other name ("Unnamed: 0" for example). '''

        df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)

        # Then, drop the column as usual.

        df.drop(["a"], axis=1, inplace=True)

Hope it helps others.

How to extract svg as file from web page

For me its very easy just install following tool in chrome server :

svg-grabber

Once you're on a web page, click the extension's icon next to the URL bar and a new tab will open showing you all the SVG files it found on the page. You can copy an SVG file to your clipboard, download only the few you need, or click the 'Download all SVGs' button to add them all to a zipped file and download them.

For detail check here

Hope it will helpful.

Jenkins pipeline if else not working

        if ( params.build_deploy == '1' ) {
            println "build_deploy ? ${params.build_deploy}"
              jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                         string(name:'environment', value: "${params.environment}"),
                         string(name:'branch_name', value: "${params.branch_name}"),
                         string(name:'service_name', value: "${params.service_name}"),                      
                     ]
            println jobB.getResult()
        }

Visual Studio Code pylint: Unable to import 'protorpc'

Changing the library path worked for me. Hitting Ctrl + Shift + P and typing python interpreter and choosing one of the available shown. One was familiar (as pointed to a virtualenv that was working fine earlier) and it worked. Take note of the version of python you are working with, either 2.7 or 3.x and choose accordingly

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>

How to re-render flatlist?

after lots of searching and looking for real answer finally i got the answer which i think it is the best :

       <FlatList
      data={this.state.data}
      renderItem={this.renderItem}
      ListHeaderComponent={this.renderHeader}
      ListFooterComponent={this.renderFooter}
      ItemSeparatorComponent={this.renderSeparator}
      refreshing={this.state.refreshing}
      onRefresh={this.handleRefresh}
      onEndReached={this.handleLoadMore}
      onEndReachedThreshold={1}
      extraData={this.state.data}
      removeClippedSubviews={true}
      **keyExtractor={ (item, index) => index }**
              />
    .....

my main problem was (KeyExtractor) i was not using it like this . not working : keyExtractor={ (item) => item.ID} after i changed to this it worked like charm i hope this helps someone.

cordova Android requirements failed: "Could not find an installed version of Gradle"

I tried many but it didnt work finally ,

  1. I installed gradle using macos port
  2. I set GRADLE_HOME path as it told after installing gradle
  3. I executed ::

sudo chmod -R a+rwx /Library/Java/JavaVirtualMachines *

sudo chmod -R a+rwx *

sudo chmod 777 {your-gradle-path}

It immediately started working

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

None of the above helped for me.

I am using Kubernetes on Google Cloud with tesla k-80 gpu.

Follow along this guide to ensure you installed everything correctly: https://cloud.google.com/kubernetes-engine/docs/how-to/gpus

I was missing few important things:

  1. Installing NVIDIA GPU device drivers On your NODES. To do this use:

For COS node:

kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/nvidia-driver-installer/cos/daemonset-preloaded.yaml

For UBUNTU node:

kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/nvidia-driver-installer/ubuntu/daemonset-preloaded.yaml

Make sure an update was rolled to your nodes. Restart them if upgrades are off.

  1. I use this image nvidia/cuda:10.1-base-ubuntu16.04 in my docker

  2. You have to set gpu limit! This is the only way the node driver can communicate with the pod. In your yaml configuration add this under your container:

    resources:
      limits:
        nvidia.com/gpu: 1
    

How to download Visual Studio 2017 Community Edition for offline installation?

I have used the exact steps from here and it worked flawlessly : https://docs.microsoft.com/en-us/visualstudio/install/install-vs-inconsistent-quality-network

In 3 simple steps:

Step 1 : Download the respective Visual Studio 2017 version from the download page (https://www.visualstudio.com/downloads/)

Step 2: Open your command prompt as Administarator, point to where your Visual studio download exe is and execute the following command (this command is specifically for Web & Desktop development) :

vs_community.exe --layout c:\vs2017layout --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional --lang en-US

Step 3 : Traverse to the path c:\vs2017layout in your command prompt and then run the following command (this command is specifically for Web & Desktop development)

vs_community.exe --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional

FileProvider - IllegalArgumentException: Failed to find configured root

None of this worked for me. The only approach that works is not to declare an explicit path in xml. So do this and be happy:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="." />
</paths>

Here too has a excelent tutorial about this question: https://www.youtube.com/watch?v=9ZxRTKvtfnY&t=613s

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

How I add Headers to http.get or http.post in Typescript and angular 2?

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
   var myFormData = { email: '[email protected]', password: '123' };
   const headers = new HttpHeaders();
   headers.append('Content-Type', 'application/json');
   //HTTP POST REQUEST
   this.httpClient
  .post(this.REST_API_SERVER, myFormData, {
    headers: headers,
   })
  .subscribe((data) => {
    console.log("i'm from service............", data, myFormData, headers);
    return data;
  });
}

How to mount a single file in a volume

For anyone using Windows container like me, know that you CANNOT bind or mount single files using windows container.

The following examples will fail when using Windows-based containers, as the destination of a volume or bind mount inside the container must be one of: a non-existing or empty directory; or a drive other than C:. Further, the source of a bind mount must be a local directory, not a file.

net use z: \\remotemachine\share

docker run -v z:\foo:c:\dest ...

docker run -v \\uncpath\to\directory:c:\dest ...

docker run -v c:\foo\somefile.txt:c:\dest ...

docker run -v c:\foo:c: ...

docker run -v c:\foo:c:\existing-directory-with-contents ...

It's hard to spot but it's there

Link to the Github issue regarding mapping files into Windows container

How to implement debounce in Vue2?

Assigning debounce in methods can be trouble. So instead of this:

// Bad
methods: {
  foo: _.debounce(function(){}, 1000)
}

You may try:

// Good
created () {
  this.foo = _.debounce(function(){}, 1000);
}

It becomes an issue if you have multiple instances of a component - similar to the way data should be a function that returns an object. Each instance needs its own debounce function if they are supposed to act independently.

Here's an example of the problem:

_x000D_
_x000D_
Vue.component('counter', {_x000D_
  template: '<div>{{ i }}</div>',_x000D_
  data: function(){_x000D_
    return { i: 0 };_x000D_
  },_x000D_
  methods: {_x000D_
    // DON'T DO THIS_x000D_
    increment: _.debounce(function(){_x000D_
      this.i += 1;_x000D_
    }, 1000)_x000D_
  }_x000D_
});_x000D_
_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  mounted () {_x000D_
    this.$refs.counter1.increment();_x000D_
    this.$refs.counter2.increment();_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <div>Both should change from 0 to 1:</div>_x000D_
  <counter ref="counter1"></counter>_x000D_
  <counter ref="counter2"></counter>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I eventually figured out an easy way to do it:

  1. On your Twitter feed, click the date/time of the tweet containing the video. That will open the single tweet view
  2. Look for the down-pointing arrow at the top-right corner of the tweet, click it to open drop-down menue
  3. Select the "Embed Video" option and copy the HTML embed code and Paste it to Notepad
  4. Find the last "t.co" shortened URL inside the HTML code (should be something like this: https://``t.co/tQM43ftXyM). Copy this URL and paste it in a new browser tab.
  5. The browser will expand the shortened URL to something which looks like this: https://twitter.com/UserName/status/828267001496784896/video/1

This is the link to the Twitter Card containing the native video. Pasting this link in a new tweet or DM will include the native video in it!

`col-xs-*` not working in Bootstrap 4

col-xs-* have been dropped in Bootstrap 4 in favor of col-*.

Replace col-xs-12 with col-12 and it will work as expected.

Also note col-xs-offset-{n} were replaced by offset-{n} in v4.

Which ChromeDriver version is compatible with which Chrome Browser version?

The Chrome Browser versión should matches with the chromeDriver versión. Go to : chrome://settings/help

How do I confirm I'm using the right chromedriver?

  • Go to the folder where you have chromeDriver
  • Open command prompt pointing the folder
  • run: chromeDriver -v

Laravel Carbon subtract days from current date

You can always use strtotime to minus the number of days from the current date:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();

how to display a javascript var in html body

Index.html:

<html>
<body>
    Javascript Version: <b id="version"></b>
    <script src="app.js"></script>
</body>
</html>

app.js:

var ver="1.1";
document.getElementById("version").innerHTML = ver;

How to request Location Permission at runtime

check this code from MainActivity

 // Check location permission is granted - if it is, start
// the service, otherwise request the permission
fun checkOrAskLocationPermission(callback: () -> Unit) {
    // Check GPS is enabled
    val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
    if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "Please enable location services", Toast.LENGTH_SHORT).show()
        buildAlertMessageNoGps(this)
        return
    }

    // Check location permission is granted - if it is, start
    // the service, otherwise request the permission
    val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
    if (permission == PackageManager.PERMISSION_GRANTED) {
        callback.invoke()
    } else {
        // callback will be inside the activity's onRequestPermissionsResult(
        ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
            PERMISSIONS_REQUEST
        )
    }
}

plus

   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    if (requestCode == PERMISSIONS_REQUEST) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
              // Permission ok. Do work.
         }
    }
}

plus

 fun buildAlertMessageNoGps(context: Context) {
    val builder = AlertDialog.Builder(context);
    builder.setMessage("Your GPS is disabled. Do you want to enable it?")
        .setCancelable(false)
        .setPositiveButton("Yes") { _, _ -> context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }
        .setNegativeButton("No") { dialog, _ -> dialog.cancel(); }
    val alert = builder.create();
    alert.show();
}

usage

checkOrAskLocationPermission() {
            // Permission ok. Do work.
        }

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

I faced the same issue. I was using Java 9 and the following dependency in pom file:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

The issue was resolved after adding the dependency below in pom:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

How to discard local changes and pull latest from GitHub repository

Run the below commands

git log

From this you will get your last push commit hash key

git reset --hard <your commit hash key>

React eslint error missing in props validation

I ran into this issue over the past couple days. Like Omri Aharon said in their answer above, it is important to add definitions for your prop types similar to:

SomeClass.propTypes = {
    someProp: PropTypes.number,
    onTap: PropTypes.func,
};

Don't forget to add the prop definitions outside of your class. I would place it right below/above my class. If you are not sure what your variable type or suffix is for your PropType (ex: PropTypes.number), refer to this npm reference. To Use PropTypes, you must import the package:

import PropTypes from 'prop-types';

If you get the linting error:someProp is not required, but has no corresponding defaultProps declaration all you have to do is either add .isRequired to the end of your prop definition like so:

SomeClass.propTypes = {
    someProp: PropTypes.number.isRequired,
    onTap: PropTypes.func.isRequired,
};

OR add default prop values like so:

SomeClass.defaultProps = {
    someProp: 1
};

If you are anything like me, unexperienced or unfamiliar with reactjs, you may also get this error: Must use destructuring props assignment. To fix this error, define your props before they are used. For example:

const { someProp } = this.props;

ImportError: No module named google.protobuf

if protobuf is installed then import it like this

pip install protobuf

import google.protobuf

return string with first match Regex

You shouldn't be using .findall() at all - .search() is what you want. It finds the leftmost match, which is what you want (or returns None if no match exists).

m = re.search(pattern, text)
result = m.group(0) if m else ""

Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search() on its own finds a match (it returns None if it didn't, or an SRE_Match object if it did).

SyntaxError: Unexpected token o in JSON at position 1

Don't ever use JSON.parse without wrapping it in try-catch block:

// payload 
let userData = null;

try {
    // Parse a JSON
    userData = JSON.parse(payload); 
} catch (e) {
    // You can read e for more info
    // Let's assume the error is that we already have parsed the payload
    // So just return that
    userData = payload;
}

// Now userData is the parsed result

How to convert an object to JSON correctly in Angular 2 with TypeScript

You'll have to parse again if you want it in actual JSON:

JSON.parse(JSON.stringify(object))

How to return value from function which has Observable subscription inside?

function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())

In above case console.log runs before the promise is resolved so no value is displayed, change it to following

function getValueFromObservable() {
    return this.store
}

getValueFromObservable()
 .subscribe((data: any) => {
    // do something here with data
    console.log(data);
});

other solution is when you need data inside getValueFromObservable to return the observable using of operator and subscribe to the function.

 function getValueFromObservable() {
        return this.store.subscribe((data: any) => {
            // do something with data here
            console.log(data);
            //return again observable.
            return of(data);
       })
    }

    getValueFromObservable()
     .subscribe((data: any) => {
        // do something here with data
        console.log(data);
    });

Automatically accept all SDK licences

I have faced two errors while Build my project on Android Studio:

  1. License for package Android SDK Platform 28 not accepted. (while Build my project in Android Studio 4.1)

  2. exception in thread main java.lang.noclassdeffounderror javax/xml/bind/annotation/xmlschema (while running SDK manager to accept license)

For me, it was a java version problem. I have installed JDK instead of java. TO SOLVE THE ISSUE, I did the following steps.

For Windows:

Step1: Download and install the latest JAVA version from https://www.java.com/en/download/

Step2: Search for "View advanced system settings" in the start menu button (windows icon)

Step3: Click on "Environment Variables"

Step4: under "System variables" click on "New", now set "Variable name: JAVA_HOME" and "Variable value: C:\Program Files\Java\jre1.8.0_271" (add latest installed java path here). Then "OK", "OK", and "OK".

Step5: open cmd as an administrator and type the following commands:

  1. cd C:\Users\kevin\AppData\Local\Android\Sdk\tools\bin (*change username here)

  2. sdkmanager --licenses

Press "y" for all questions.

Step6: Restart your Android Studio again.

DONE.

Let me know if anyone having a problem while following the above steps.

'import' and 'export' may only appear at the top level

Maybe you're missing some plugins, try:

npm i --save-dev babel-plugin-transform-vue-jsx

npm i --save-dev babel-plugin-transform-runtime

npm i --save-dev babel-plugin-syntax-dynamic-import
  • If using "Webpack.config.js":

Missing Plugins

  • If using ".babelrc", see answer in this link.

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

I found it useful (where I wanted to ignore line feeds and not change any files) to ignore them in the .eslintrc using linebreak-style as per this answer: https://stackoverflow.com/a/43008668/1129108

module.exports = {
  extends: 'google',
  quotes: [2, 'single'],
  globals: {
    SwaggerEditor: false
  },
  env: {
    browser: true
  },
  rules:{
    "linebreak-style": 0
  }
};

Extract Month and Year From Date in R

The zoo package has the function of as.yearmon can help to convert.

require(zoo)

df$ym<-as.yearmon(df$date, "%Y %m")

Use virtualenv with Python with Visual Studio Code in Ubuntu

With the latest update to the extension all you need to do is just specify the "python.pythonPath" as follows.

The values for "python.autoComplete.extraPaths" will be determined during runtime, but you are still free to specify custom paths in there.

Please, remember to restart Visual Studio Code once the necessary changes have been made.

{
    "editor.rulers": [80,100],
    "python.pythonPath":"~/dev/venvs/proj/bin/python"
}

Adb install failure: INSTALL_CANCELED_BY_USER

1 Settings

2 Additional Settings

3 Developer Options

4 Developer options: Check the Install via USB option.

enter image description here

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

first you remove this thing in your project .. its is in build.gradle(module:app) then build your app now you project show the actual error and you find what is your actual problem is .. and after you find actual problem again paste it where its is belong to

allprojects { gradle.projectsEvaluated {

    tasks.withType(JavaCompile)

{ options.encoding = 'UTF-8'

        options.compilerArgs

<< "-Xlint:unchecked" << "-Xlint:deprecation"}]}}

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

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

Add Favicon with React and Webpack

Replace the favicon.ico in your public folder with yours, that should get you going.

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

Property 'catch' does not exist on type 'Observable<any>'

Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below

=====================

Yes, you need to import the operator:

import 'rxjs/add/operator/catch';

Or import Observable this way:

import {Observable} from 'rxjs/Rx';

But in this case, you import all operators.

See this question for more details:

How to add Certificate Authority file in CentOS 7

QUICK HELP 1: To add a certificate in the simple PEM or DER file formats to the list of CAs trusted on the system:

  • add it as a new file to directory /etc/pki/ca-trust/source/anchors/

  • run update-ca-trust extract

QUICK HELP 2: If your certificate is in the extended BEGIN TRUSTED file format (which may contain distrust/blacklist trust flags, or trust flags for usages other than TLS) then:

  • add it as a new file to directory /etc/pki/ca-trust/source/
  • run update-ca-trust extract

More detail infomation see man update-ca-trust

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I'll try to give the benchmark of the three most common way (also mentioned above):

from timeit import repeat

setup = """
import numpy as np;
import random;
x = np.linspace(0,100);
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) * (x <= ub)]', 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'

for _ in range(3):
    for stmt in stmts:
        t = min(repeat(stmt, setup, number=100_000))
        print('%.4f' % t, stmt)
    print()

result:

0.4808 x[(x > lb) * (x <= ub)]
0.4726 x[(x > lb) & (x <= ub)]
0.4904 x[np.logical_and(x > lb, x <= ub)]

0.4725 x[(x > lb) * (x <= ub)]
0.4806 x[(x > lb) & (x <= ub)]
0.5002 x[np.logical_and(x > lb, x <= ub)]

0.4781 x[(x > lb) * (x <= ub)]
0.4336 x[(x > lb) & (x <= ub)]
0.4974 x[np.logical_and(x > lb, x <= ub)]

But, * is not supported in Panda Series, and NumPy Array is faster than pandas data frame (arround 1000 times slower, see number):

from timeit import repeat

setup = """
import numpy as np;
import random;
import pandas as pd;
x = pd.DataFrame(np.linspace(0,100));
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'

for _ in range(3):
    for stmt in stmts:
        t = min(repeat(stmt, setup, number=100))
        print('%.4f' % t, stmt)
    print()

result:

0.1964 x[(x > lb) & (x <= ub)]
0.1992 x[np.logical_and(x > lb, x <= ub)]

0.2018 x[(x > lb) & (x <= ub)]
0.1838 x[np.logical_and(x > lb, x <= ub)]

0.1871 x[(x > lb) & (x <= ub)]
0.1883 x[np.logical_and(x > lb, x <= ub)]

Note: adding one line of code x = x.to_numpy() will need about 20 µs.

For those who prefer %timeit:

import numpy as np
import random
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
lb, ub
x = pd.DataFrame(np.linspace(0,100))

def asterik(x):
    x = x.to_numpy()
    return x[(x > lb) * (x <= ub)]

def and_symbol(x):
    x = x.to_numpy()
    return x[(x > lb) & (x <= ub)]

def numpy_logical(x):
    x = x.to_numpy()
    return x[np.logical_and(x > lb, x <= ub)]

for i in range(3):
    %timeit asterik(x)
    %timeit and_symbol(x)
    %timeit numpy_logical(x)
    print('\n')

result:

23 µs ± 3.62 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
35.6 µs ± 9.53 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
31.3 µs ± 8.9 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)


21.4 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
21.9 µs ± 1.02 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
21.7 µs ± 500 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


25.1 µs ± 3.71 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
36.8 µs ± 18.3 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
28.2 µs ± 5.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

extract column value based on another column pandas dataframe

Use df[df['B']==3]['A'].values if you just want item itself without the brackets

Install pip in docker

Try this:

  1. Uncomment the following line in /etc/default/docker DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4"
  2. Restart the Docker service sudo service docker restart
  3. Delete any images which have cached the invalid DNS settings.
  4. Build again and the problem should be solved.

From this question.

Extract year from date

As discussed in the comments, this can be achieved by converting the entry into Date format and extracting the year, for instance like this:

format(as.Date(df1$Date, format="%d/%m/%Y"),"%Y")

Extract first and last row of a dataframe in pandas

Here is the same style as in large datasets:

x = df[:5]
y = pd.DataFrame([['...']*df.shape[1]], columns=df.columns, index=['...'])
z = df[-5:]
frame = [x, y, z]
result = pd.concat(frame)

print(result)

Output:

                     date  temp
0     1981-01-01 00:00:00  20.7
1     1981-01-02 00:00:00  17.9
2     1981-01-03 00:00:00  18.8
3     1981-01-04 00:00:00  14.6
4     1981-01-05 00:00:00  15.8
...                   ...   ...
3645  1990-12-27 00:00:00    14
3646  1990-12-28 00:00:00  13.6
3647  1990-12-29 00:00:00  13.5
3648  1990-12-30 00:00:00  15.7
3649  1990-12-31 00:00:00    13

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

Anyone facing this while using cmake build, the solution is to make sure you have included the four supported platforms in your app module's android{} block:

 externalNativeBuild {
            cmake {
                cppFlags "-std=c++14"
                abiFilters "arm64-v8a", "x86", "armeabi-v7a", "x86_64"
            }
        }

Extract Data from PDF and Add to Worksheet

To improve the solution of Slinky Sloth I had to add this beforere get from clipboard :

Set objPDF = New MSForms.DataObject

Sadly it didn't worked for a pdf of 10 pages.

Serialize and Deserialize Json and Json Array in Unity

Unity added JsonUtility to their API after 5.3.3 Update. Forget about all the 3rd party libraries unless you are doing something more complicated. JsonUtility is faster than other Json libraries. Update to Unity 5.3.3 version or above then try the solution below.

JsonUtility is a lightweight API. Only simple types are supported. It does not support collections such as Dictionary. One exception is List. It supports List and List array!

If you need to serialize a Dictionary or do something other than simply serializing and deserializing simple datatypes, use a third-party API. Otherwise, continue reading.

Example class to serialize:

[Serializable]
public class Player
{
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

1. ONE DATA OBJECT (NON-ARRAY JSON)

Serializing Part A:

Serialize to Json with the public static string ToJson(object obj); method.

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance);
Debug.Log(playerToJson);

Output:

{"playerId":"8484239823","playerLoc":"Powai","playerNick":"Random Nick"}

Serializing Part B:

Serialize to Json with the public static string ToJson(object obj, bool prettyPrint); method overload. Simply passing true to the JsonUtility.ToJson function will format the data. Compare the output below to the output above.

Player playerInstance = new Player();
playerInstance.playerId = "8484239823";
playerInstance.playerLoc = "Powai";
playerInstance.playerNick = "Random Nick";

//Convert to JSON
string playerToJson = JsonUtility.ToJson(playerInstance, true);
Debug.Log(playerToJson);

Output:

{
    "playerId": "8484239823",
    "playerLoc": "Powai",
    "playerNick": "Random Nick"
}

Deserializing Part A:

Deserialize json with the public static T FromJson(string json); method overload.

string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = JsonUtility.FromJson<Player>(jsonString);
Debug.Log(player.playerLoc);

Deserializing Part B:

Deserialize json with the public static object FromJson(string json, Type type); method overload.

string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";
Player player = (Player)JsonUtility.FromJson(jsonString, typeof(Player));
Debug.Log(player.playerLoc);

Deserializing Part C:

Deserialize json with the public static void FromJsonOverwrite(string json, object objectToOverwrite); method. When JsonUtility.FromJsonOverwrite is used, no new instance of that Object you are deserializing to will be created. It will simply re-use the instance you pass in and overwrite its values.

This is efficient and should be used if possible.

Player playerInstance;
void Start()
{
    //Must create instance once
    playerInstance = new Player();
    deserialize();
}

void deserialize()
{
    string jsonString = "{\"playerId\":\"8484239823\",\"playerLoc\":\"Powai\",\"playerNick\":\"Random Nick\"}";

    //Overwrite the values in the existing class instance "playerInstance". Less memory Allocation
    JsonUtility.FromJsonOverwrite(jsonString, playerInstance);
    Debug.Log(playerInstance.playerLoc);
}

2. MULTIPLE DATA(ARRAY JSON)

Your Json contains multiple data objects. For example playerId appeared more than once. Unity's JsonUtility does not support array as it is still new but you can use a helper class from this person to get array working with JsonUtility.

Create a class called JsonHelper. Copy the JsonHelper directly from below.

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

Serializing Json Array:

Player[] playerInstance = new Player[2];

playerInstance[0] = new Player();
playerInstance[0].playerId = "8484239823";
playerInstance[0].playerLoc = "Powai";
playerInstance[0].playerNick = "Random Nick";

playerInstance[1] = new Player();
playerInstance[1].playerId = "512343283";
playerInstance[1].playerLoc = "User2";
playerInstance[1].playerNick = "Rand Nick 2";

//Convert to JSON
string playerToJson = JsonHelper.ToJson(playerInstance, true);
Debug.Log(playerToJson);

Output:

{
    "Items": [
        {
            "playerId": "8484239823",
            "playerLoc": "Powai",
            "playerNick": "Random Nick"
        },
        {
            "playerId": "512343283",
            "playerLoc": "User2",
            "playerNick": "Rand Nick 2"
        }
    ]
}

Deserializing Json Array:

string jsonString = "{\r\n    \"Items\": [\r\n        {\r\n            \"playerId\": \"8484239823\",\r\n            \"playerLoc\": \"Powai\",\r\n            \"playerNick\": \"Random Nick\"\r\n        },\r\n        {\r\n            \"playerId\": \"512343283\",\r\n            \"playerLoc\": \"User2\",\r\n            \"playerNick\": \"Rand Nick 2\"\r\n        }\r\n    ]\r\n}";

Player[] player = JsonHelper.FromJson<Player>(jsonString);
Debug.Log(player[0].playerLoc);
Debug.Log(player[1].playerLoc);

Output:

Powai

User2


If this is a Json array from the server and you did not create it by hand:

You may have to Add {"Items": in front of the received string then add } at the end of it.

I made a simple function for this:

string fixJson(string value)
{
    value = "{\"Items\":" + value + "}";
    return value;
}

then you can use it:

string jsonString = fixJson(yourJsonFromServer);
Player[] player = JsonHelper.FromJson<Player>(jsonString);

3.Deserialize json string without class && De-serializing Json with numeric properties

This is a Json that starts with a number or numeric properties.

For example:

{ 
"USD" : {"15m" : 1740.01, "last" : 1740.01, "buy" : 1740.01, "sell" : 1744.74, "symbol" : "$"}, 

"ISK" : {"15m" : 179479.11, "last" : 179479.11, "buy" : 179479.11, "sell" : 179967, "symbol" : "kr"},

"NZD" : {"15m" : 2522.84, "last" : 2522.84, "buy" : 2522.84, "sell" : 2529.69, "symbol" : "$"}
}

Unity's JsonUtility does not support this because the "15m" property starts with a number. A class variable cannot start with an integer.

Download SimpleJSON.cs from Unity's wiki.

To get the "15m" property of USD:

var N = JSON.Parse(yourJsonString);
string price = N["USD"]["15m"].Value;
Debug.Log(price);

To get the "15m" property of ISK:

var N = JSON.Parse(yourJsonString);
string price = N["ISK"]["15m"].Value;
Debug.Log(price);

To get the "15m" property of NZD:

var N = JSON.Parse(yourJsonString);
string price = N["NZD"]["15m"].Value;
Debug.Log(price);

The rest of the Json properties that doesn't start with a numeric digit can be handled by Unity's JsonUtility.


4.TROUBLESHOOTING JsonUtility:

Problems when serializing with JsonUtility.ToJson?

Getting empty string or "{}" with JsonUtility.ToJson?

A. Make sure that the class is not an array. If it is, use the helper class above with JsonHelper.ToJson instead of JsonUtility.ToJson.

B. Add [Serializable] to the top of the class you are serializing.

C. Remove property from the class. For example, in the variable, public string playerId { get; set; } remove { get; set; }. Unity cannot serialize this.

Problems when deserializing with JsonUtility.FromJson?

A. If you get Null, make sure that the Json is not a Json array. If it is, use the helper class above with JsonHelper.FromJson instead of JsonUtility.FromJson.

B. If you get NullReferenceException while deserializing, add [Serializable] to the top of the class.

C.Any other problems, verify that your json is valid. Go to this site here and paste the json. It should show you if the json is valid. It should also generate the proper class with the Json. Just make sure to remove remove { get; set; } from each variable and also add [Serializable] to the top of each class generated.


Newtonsoft.Json:

If for some reason Newtonsoft.Json must be used then check out the forked version for Unity here. Note that you may experience crash if certain feature is used. Be careful.


To answer your question:

Your original data is

 [{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]

Add {"Items": in front of it then add } at the end of it.

Code to do this:

serviceData = "{\"Items\":" + serviceData + "}";

Now you have:

 {"Items":[{"playerId":"1","playerLoc":"Powai"},{"playerId":"2","playerLoc":"Andheri"},{"playerId":"3","playerLoc":"Churchgate"}]}

To serialize the multiple data from php as arrays, you can now do

public player[] playerInstance;
playerInstance = JsonHelper.FromJson<player>(serviceData);

playerInstance[0] is your first data

playerInstance[1] is your second data

playerInstance[2] is your third data

or data inside the class with playerInstance[0].playerLoc, playerInstance[1].playerLoc, playerInstance[2].playerLoc ......

You can use playerInstance.Length to check the length before accessing it.

NOTE: Remove { get; set; } from the player class. If you have { get; set; }, it won't work. Unity's JsonUtility does NOT work with class members that are defined as properties.

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

The error is because you are including the script links at two places which will do the override and re-initialization of date-picker

_x000D_
_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />_x000D_
_x000D_
_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
    $('.dateinput').datepicker({ format: "yyyy/mm/dd" });_x000D_
}); _x000D_
</script>_x000D_
_x000D_
      <!-- Bootstrap core JavaScript_x000D_
================================================== -->_x000D_
<!-- Placed at the end of the document so the pages load faster -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

So exclude either src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"

or src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"

It will work..

How to Extract Year from DATE in POSTGRESQL

Try

select date_part('year', your_column) from your_table;

or

select extract(year from your_column) from your_table;

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

It's a terrible practice to give away access to the entire s3 (all actions, all buckets), just to unblock yourself.

The 403 error above is usually due to the lack of "Read" permission of files. The Read action for reading a file in S3 is s3:GetObject.

        {
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::mybucketname/path/*",
                "arn:aws:s3:::mybucketname"
            ]
        }

Solution 1: A new Policy in IAM (Tell Role/User to know S3)

You can create a Policy (e.g. MY_S3_READER) with the following, and attach it to the user or role that's doing the job. (e.g. EC2 Instance's IAM role)

Here is the exact JSON for your Policy: (just replace mybucketname and path)

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::mybucketname/path/*",
                "arn:aws:s3:::mybucketname"
            ]
        }
    ]
}

Create this Policy. Then, go to IAM > Roles > Attach Policy and attach it.

Solution 2: Edit Buckey Policy in S3 (Tell S3 to know User/Role)

Go to your bucket in S3, then add the following example: (replace mybucketname and myip)

{
    "Version": "2012-10-17",
    "Id": "SourceIP",
    "Statement": [
        {
            "Sid": "ValidIpAllowRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::mybucketname",
                "arn:aws:s3:::mybucketname/*"
            ],
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "myip/32"
                }
            }
        }
    ]
}

If you want to change this read permission to by User or Role (instead of IP Address), remove the Condition part, and change "Principal" to "Principal": { "AWS": "<IAM User/Role's ARN>" },".

Additional Notes

  1. Check the permissions via aws s3 cp or aws s3 ls manually for faster debugging.

  2. It sometimes takes up to 30 seconds for the permission change to be effective. Be patient.

  3. Note that for doing "ls" (e.g. aws s3 ls s3://mybucket/mypath) you need s3:ListBucket access.

  4. IMPORTANT Accessing files by their HTTP(S) URL via cURL or similar tools (e.g. axios on AJAX calls) requires you to grant either IP access, or supply proper headers, manually, or get a signedUrl from the SDK first.

How to install Python packages from the tar.gz file without using pip install

Thanks to the answers below combined I've got it working.

  • First needed to unpack the tar.gz file into a folder.
  • Then before running python setup.py install had to point cmd towards the correct folder. I did this by pushd C:\Users\absolutefilepathtotarunpackedfolder
  • Then run python setup.py install

Thanks Tales Padua & Hugo Honorem

How to convert Base64 String to javascript file object like as from file input form?

Heads up,

JAVASCRIPT

<script>
   function readMtlAtClient(){

       mtlFileContent = '';

       var mtlFile = document.getElementById('mtlFileInput').files[0];
       var readerMTL = new FileReader();

       // Closure to capture the file information.
       readerMTL.onload = (function(reader) {
           return function() {
               mtlFileContent = reader.result;
               mtlFileContent = mtlFileContent.replace('data:;base64,', '');
               mtlFileContent = window.atob(mtlFileContent);

           };
       })(readerMTL);

       readerMTL.readAsDataURL(mtlFile);
   }
</script>

HTML

    <input class="FullWidth" type="file" name="mtlFileInput" value="" id="mtlFileInput" 
onchange="readMtlAtClient()" accept=".mtl"/>

Then mtlFileContent has your text as a decoded string !

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

This happened to me even on debug builds and just cleared all the module level and project level build folders and it worked, yeah just like that.

Having services in React application

Service is not limited to Angular, even in Angular2+,

Service is just collection of helper functions...

And there are many ways to create them and reuse them across the application...

1) They can be all separated function which are exported from a js file, similar as below:

export const firstFunction = () => {
   return "firstFunction";
}

export const secondFunction = () => {
   return "secondFunction";
}
//etc

2) We can also use factory method like, with collection of functions... with ES6 it can be a class rather than a function constructor:

class myService {

  constructor() {
    this._data = null;
  }

  setMyService(data) {
    this._data = data;
  }

  getMyService() {
    return this._data;
  }

}

In this case you need make an instance with new key...

const myServiceInstance = new myService();

Also in this case, each instance has it's own life, so be careful if you want to share it across, in that case you should export only the instance you want...

3) If your function and utils not gonna be shared, you can even put them in React component, in this case, just as function in your react component...

class Greeting extends React.Component {
  getName() {
    return "Alireza Dezfoolian";
  }

  render() {
    return <h1>Hello, {this.getName()}</h1>;
  }
}

4) Another way you may handle things, could be using Redux, it's a temporary store for you, so if you have it in your React application, it can help you with many getter setter functions you use... It's like a big store that keep tracks of your states and can share it across your components, so can get rid of many pain for getter setter stuffs we use in the services...

It's always good to do a DRY code and not repeating what needs to be used to make the code reusable and readable, but don't try to follow Angular ways in React app, as mentioned in item 4, using Redux can reduces your need of services and you limit using them for some reuseable helper functions like item 1...

Extract the filename from a path

If you are ok with including the extension this should do what you want.

$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf

React Router with optional path parameter

For any React Router v4 users arriving here following a search, optional parameters in a <Route> are denoted with a ? suffix.

Here's the relevant documentation:

https://reacttraining.com/react-router/web/api/Route/path-string

path: string

Any valid URL path that path-to-regexp understands.

    <Route path="/users/:id" component={User}/>

https://www.npmjs.com/package/path-to-regexp#optional

Optional

Parameters can be suffixed with a question mark (?) to make the parameter optional. This will also make the prefix optional.

Simple example of a paginated section of a site that can be accessed with or without a page number.

    <Route path="/section/:page?" component={Section} />

Get first letter of a string from column

.str.get

This is the simplest to specify string methods

# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df

        A    B
0     xyz  123
1     abc  456
2  foobar  789

df.dtypes

A    object
B     int64
dtype: object

For string (read:object) type columns, use

df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)

.str handles NaNs by returning NaN as the output.

For non-numeric columns, an .astype conversion is required beforehand, as shown in @Ed Chum's answer.

# Note that this won't work well if the data has NaNs. 
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

List Comprehension and Indexing

There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.

# For string columns
df['C'] = [x[0] for x in df['A']]

# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]

df
        A    B  C  D
0     xyz  123  x  1
1     abc  456  a  4
2  foobar  789  f  7

If your data has NaNs, then you will need to handle this appropriately with an if/else in the list comprehension,

df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2

        A      B
0     xyz  123.0
1     NaN  456.0
2  foobar    NaN

# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]

# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]

        A      B    C    D
0     xyz  123.0    x    1
1     NaN  456.0  NaN    4
2  foobar    NaN    f  NaN

Let's do some timeit tests on some larger data.

df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True) 

%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])

%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])

12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehensions are 4x faster.

Extract values in Pandas value_counts()

Try this:

dataframe[column].value_counts().index.tolist()
['apple', 'sausage', 'banana', 'cheese']

Plotting lines connecting points

I think you're going to need separate lines for each segment:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()

(The numpy import is just to set up some random 2x10 sample data)

enter image description here

Variable used in lambda expression should be final or effectively final

From a lambda, you can't get a reference to anything that isn't final. You need to declare a final wrapper from outside the lamda to hold your variable.

I've added the final 'reference' object as this wrapper.

private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) {
    final AtomicReference<TimeZone> reference = new AtomicReference<>();

    try {
       cal.getComponents().getComponents("VTIMEZONE").forEach(component->{
        VTimeZone v = (VTimeZone) component;
           v.getTimeZoneId();
           if(reference.get()==null) {
               reference.set(TimeZone.getTimeZone(v.getTimeZoneId().getValue()));
           }
           });
    } catch (Exception e) {
        //log.warn("Unable to determine ical timezone", e);
    }
    return reference.get();
}   

How to extract text from a PDF file?

You can use PDFtoText https://github.com/jalan/pdftotext

PDF to text keeps text format indentation, doesn't matter if you have tables.

Extracting specific selected columns to new DataFrame as a copy

There is a way of doing this and it actually looks similar to R

new = old[['A', 'C', 'D']].copy()

Here you are just selecting the columns you want from the original data frame and creating a variable for those. If you want to modify the new dataframe at all you'll probably want to use .copy() to avoid a SettingWithCopyWarning.

An alternative method is to use filter which will create a copy by default:

new = old.filter(['A','B','D'], axis=1)

Finally, depending on the number of columns in your original dataframe, it might be more succinct to express this using a drop (this will also create a copy by default):

new = old.drop('B', axis=1)

How can I show current location on a Google Map on Android Marshmallow?

For using FusedLocationProviderClient with Google Play Services 11 and higher:

see here: How to get current Location in GoogleMap using FusedLocationProviderClient

For using (now deprecated) FusedLocationProviderApi:

If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.

The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.

Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.

It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo). In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true) and also before requesting location updates.

public class MapLocationActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;

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

        getSupportActionBar().setTitle("Map Location Activity");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapLocationActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

activity_main.xml:

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

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapLocationActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result:

Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):

enter image description here

Prompt the user for Location permission by calling ActivityCompat.requestPermissions():

enter image description here

Move camera to current location and place Marker when the Location permission is granted:

enter image description here

How to install Android SDK on Ubuntu?

To install it on a Debian based system simply do

# Install latest JDK
sudo apt install default-jdk

# install unzip if not installed yet
sudo apt install unzip

# get latest sdk tools - link will change. go to https://developer.android.com/studio/#downloads to get the latest one
cd ~
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip

# unpack archive
unzip sdk-tools-linux-4333796.zip

rm sdk-tools-linux-4333796.zip

mkdir android-sdk
mv tools android-sdk/tools

Then add the Android SDK to your PATH, open ~/.bashrc in editor and add the following lines into the file

# Export the Android SDK path 
export ANDROID_HOME=$HOME/android-sdk
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

# Fixes sdkmanager error with java versions higher than java 8
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'

Run

source ~/.bashrc

Show all available sdk packages

sdkmanager --list

Identify latest android platform (here it's 28) and run

sdkmanager "platform-tools" "platforms;android-28"

Now you have adb, fastboot and the latest sdk tools installed

Changing fonts in ggplot2

Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

mysqld --initialize to initialize the data directory then mysqld &

If you had already launched mysqld& without mysqld --initialize you might have to delete all files in your data directory

You can also modify /etc/my.cnf to add a custom path to your data directory like this :

[mysqld]
...  
datadir=/path/to/directory

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

android : Error converting byte to dex

In my case, this was due to my library not being configured as 'android'. E.g. apply plugin:'java' instead of apply plugin:'com.android.library'

React passing parameter via onclick event using ES6 syntax

Something nobody has mentioned so far is to make handleRemove return a function.

You can do something like:

handleRemove = id => event => {
  // Do stuff with id and event
}

// render...
  return <button onClick={this.handleRemove(id)} />

However all of these solutions have the downside of creating a new function on each render. Better to create a new component for Button which gets passed the id and the handleRemove separately.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

Possibly something has changed in recent TensorFlow builds, because for me, running

sess = tf.Session()
sess.run(tf.local_variables_initializer())

before fitting any models seems to do the trick. Most older examples and comments seem to suggest tf.global_variables_initializer().

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

Why I get 'list' object has no attribute 'items'?

You have a dictionary within a list. You must first extract the dictionary from the list and then process the items in the dictionary.

If your list contained multiple dictionaries and you wanted the value from each dictionary stored in a list as you have shown do this:

result_list = [[int(v) for k,v in d.items()] for d in qs]

Which is the same as:

result_list = []
for d in qs:
    result_list.append([int(v) for k,v in d.items()])

The above will keep the values from each dictionary in their own separate list. If you just want all the values in one big list you can do this:

result_list = [int(v) for d in qs for k,v in d.items()]

RecyclerView - Get view at particular position

If you want the View, make sure to access the itemView property of the ViewHolder like so: myRecyclerView.findViewHolderForAdapterPosition(pos).itemView;

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

The problem might originate from a macro instruction in SDL_main.h

In that macro your main(){} is renamed to SDL_main(){} because SDL needs its own main(){} on some of the many platforms they support, so they change yours. Mostly it achieves their goal, but on my platform it created problems, rather than solved them. I added a 2nd line in SDL_main.h, and for me all problems were gone.

#define main SDL_main    //Original line. Renames main(){} to SDL_main(){}. 

#define main main        //Added line. Undo the renaming.

If you don't like the compiler warning caused by this pair of lines, comment both lines out.

If your code is in WinApp(){} you don't have this problem at all. This answer only might help if your main code is in main(){} and your platform is similar to mine.

I have: Visual Studio 2019, Windows 10, x64, writing a 32 bit console app that opens windows using SDL2.0 as part of a tutorial.

Python - Extracting and Saving Video Frames

After a lot of research on how to convert frames to video I have created this function hope this helps. We require opencv for this:

import cv2
import numpy as np
import os

def frames_to_video(inputpath,outputpath,fps):
   image_array = []
   files = [f for f in os.listdir(inputpath) if isfile(join(inputpath, f))]
   files.sort(key = lambda x: int(x[5:-4]))
   for i in range(len(files)):
       img = cv2.imread(inputpath + files[i])
       size =  (img.shape[1],img.shape[0])
       img = cv2.resize(img,size)
       image_array.append(img)
   fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
   out = cv2.VideoWriter(outputpath,fourcc, fps, size)
   for i in range(len(image_array)):
       out.write(image_array[i])
   out.release()


inputpath = 'folder path'
outpath =  'video file path/video.mp4'
fps = 29
frames_to_video(inputpath,outpath,fps)

change the value of fps(frames per second),input folder path and output folder path according to your own local locations

Extract number from string with Oracle function

You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

Copy all values in a column to a new column in a pandas dataframe

Following up on these solutions, here is some helpful code illustrating :

#
# Copying columns in pandas without slice warning
#
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC'))

#
# copies column B into new column D
df.loc[:,'D'] = df['B']
print df

#
# creates new column 'E' with values -99
# 
# But copy command replaces those where 'B'>0 while others become NaN (not copied)
df['E'] = -99
print df
df['E'] = df[df['B']>0]['B'].copy()
print df

#
# creates new column 'F' with values -99
# 
# Copy command only overwrites values which meet criteria 'B'>0
df['F']=-99
df.loc[df['B']>0,'F'] = df[df['B']>0]['B'].copy()
print df

How to Get JSON Array Within JSON Object?

I guess this will help you.

JSONObject jsonObj = new JSONObject(jsonStr);

JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj.length();
for(int i=0; i<length; i++) {
  JSONObject jsonObj = ja_data.getJSONObject(i);
  Toast.makeText(this, jsonObj.getString("Name"), Toast.LENGTH_LONG).show();

  // getting inner array Ingredients
  JSONArray ja = jsonObj.getJSONArray("Ingredients");
  int len = ja.length();

  ArrayList<String> Ingredients_names = new ArrayList<>();
  for(int j=0; j<len; j++) {
    JSONObject json = ja.getJSONObject(j);
    Ingredients_names.add(json.getString("name"));
  }
}

FFMPEG mp4 from http live streaming m3u8 file?

Your command is completely incorrect. The output format is not rawvideo and you don't need the bitstream filter h264_mp4toannexb which is used when you want to convert the h264 contained in an mp4 to the Annex B format used by MPEG-TS for example. What you want to use instead is the aac_adtstoasc for the AAC streams.

ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, and WRITE_EXTERNAL_STORAGE are all part of the Android 6.0 runtime permission system. In addition to having them in the manifest as you do, you also have to request them from the user at runtime (using requestPermissions()) and see if you have them (using checkSelfPermission()).

One workaround in the short term is to drop your targetSdkVersion below 23.

But, eventually, you will want to update your app to use the runtime permission system.

For example, this activity works with five permissions. Four are runtime permissions, though it is presently only handling three (I wrote it before WRITE_EXTERNAL_STORAGE was added to the runtime permission roster).

/***
 Copyright (c) 2015 CommonsWare, LLC
 Licensed under the Apache License, Version 2.0 (the "License"); you may not
 use this file except in compliance with the License. You may obtain a copy
 of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
 by applicable law or agreed to in writing, software distributed under the
 License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 OF ANY KIND, either express or implied. See the License for the specific
 language governing permissions and limitations under the License.

 From _The Busy Coder's Guide to Android Development_
 https://commonsware.com/Android
 */

package com.commonsware.android.permmonger;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
  private static final String[] INITIAL_PERMS={
    Manifest.permission.ACCESS_FINE_LOCATION,
    Manifest.permission.READ_CONTACTS
  };
  private static final String[] CAMERA_PERMS={
    Manifest.permission.CAMERA
  };
  private static final String[] CONTACTS_PERMS={
      Manifest.permission.READ_CONTACTS
  };
  private static final String[] LOCATION_PERMS={
      Manifest.permission.ACCESS_FINE_LOCATION
  };
  private static final int INITIAL_REQUEST=1337;
  private static final int CAMERA_REQUEST=INITIAL_REQUEST+1;
  private static final int CONTACTS_REQUEST=INITIAL_REQUEST+2;
  private static final int LOCATION_REQUEST=INITIAL_REQUEST+3;
  private TextView location;
  private TextView camera;
  private TextView internet;
  private TextView contacts;
  private TextView storage;

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

    location=(TextView)findViewById(R.id.location_value);
    camera=(TextView)findViewById(R.id.camera_value);
    internet=(TextView)findViewById(R.id.internet_value);
    contacts=(TextView)findViewById(R.id.contacts_value);
    storage=(TextView)findViewById(R.id.storage_value);

    if (!canAccessLocation() || !canAccessContacts()) {
      requestPermissions(INITIAL_PERMS, INITIAL_REQUEST);
    }
  }

  @Override
  protected void onResume() {
    super.onResume();

    updateTable();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actions, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
      case R.id.camera:
        if (canAccessCamera()) {
          doCameraThing();
        }
        else {
          requestPermissions(CAMERA_PERMS, CAMERA_REQUEST);
        }
        return(true);

      case R.id.contacts:
        if (canAccessContacts()) {
          doContactsThing();
        }
        else {
          requestPermissions(CONTACTS_PERMS, CONTACTS_REQUEST);
        }
        return(true);

      case R.id.location:
        if (canAccessLocation()) {
          doLocationThing();
        }
        else {
          requestPermissions(LOCATION_PERMS, LOCATION_REQUEST);
        }
        return(true);
    }

    return(super.onOptionsItemSelected(item));
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    updateTable();

    switch(requestCode) {
      case CAMERA_REQUEST:
        if (canAccessCamera()) {
          doCameraThing();
        }
        else {
          bzzzt();
        }
        break;

      case CONTACTS_REQUEST:
        if (canAccessContacts()) {
          doContactsThing();
        }
        else {
          bzzzt();
        }
        break;

      case LOCATION_REQUEST:
        if (canAccessLocation()) {
          doLocationThing();
        }
        else {
          bzzzt();
        }
        break;
    }
  }

  private void updateTable() {
    location.setText(String.valueOf(canAccessLocation()));
    camera.setText(String.valueOf(canAccessCamera()));
    internet.setText(String.valueOf(hasPermission(Manifest.permission.INTERNET)));
    contacts.setText(String.valueOf(canAccessContacts()));
    storage.setText(String.valueOf(hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)));
  }

  private boolean canAccessLocation() {
    return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
  }

  private boolean canAccessCamera() {
    return(hasPermission(Manifest.permission.CAMERA));
  }

  private boolean canAccessContacts() {
    return(hasPermission(Manifest.permission.READ_CONTACTS));
  }

  private boolean hasPermission(String perm) {
    return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
  }

  private void bzzzt() {
    Toast.makeText(this, R.string.toast_bzzzt, Toast.LENGTH_LONG).show();
  }

  private void doCameraThing() {
    Toast.makeText(this, R.string.toast_camera, Toast.LENGTH_SHORT).show();
  }

  private void doContactsThing() {
    Toast.makeText(this, R.string.toast_contacts, Toast.LENGTH_SHORT).show();
  }

  private void doLocationThing() {
    Toast.makeText(this, R.string.toast_location, Toast.LENGTH_SHORT).show();
  }
}

(from this sample project)

For the requestPermissions() function, should the parameters just be "ACCESS_COARSE_LOCATION"? Or should I include the full name "android.permission.ACCESS_COARSE_LOCATION"?

I would use the constants defined on Manifest.permission, as shown above.

Also, what is the request code?

That will be passed back to you as the first parameter to onRequestPermissionsResult(), so you can tell one requestPermissions() call from another.

Extract column values of Dataframe as List in Apache Spark

With Spark 2.x and Scala 2.11

I'd think of 3 possible ways to convert values of a specific column to List.

Common code snippets for all the approaches

import org.apache.spark.sql.SparkSession

val spark = SparkSession.builder.getOrCreate    
import spark.implicits._ // for .toDF() method

val df = Seq(
    ("first", 2.0),
    ("test", 1.5), 
    ("choose", 8.0)
  ).toDF("id", "val")

Approach 1

df.select("id").collect().map(_(0)).toList
// res9: List[Any] = List(one, two, three)

What happens now? We are collecting data to Driver with collect() and picking element zero from each record.

This could not be an excellent way of doing it, Let's improve it with next approach.


Approach 2

df.select("id").rdd.map(r => r(0)).collect.toList 
//res10: List[Any] = List(one, two, three)

How is it better? We have distributed map transformation load among the workers rather than single Driver.

I know rdd.map(r => r(0)) does not seems elegant you. So, let's address it in next approach.


Approach 3

df.select("id").map(r => r.getString(0)).collect.toList 
//res11: List[String] = List(one, two, three)

Here we are not converting DataFrame to RDD. Look at map it won't accept r => r(0)(or _(0)) as the previous approach due to encoder issues in DataFrame. So end up using r => r.getString(0) and it would be addressed in the next versions of Spark.

Conclusion

All the options give the same output but 2 and 3 are effective, finally 3rd one is effective and elegant(I'd think).

Databricks notebook

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

func funcationname()
{

    var parameters = [String:String]()
    let apiToken = "Bearer \(UserDefaults.standard.string(forKey: "vAuthToken")!)"
    let headers = ["Vauthtoken":apiToken]
    let mobile = "\(ApiUtillity.sharedInstance.getUserData(key: "mobile"))"
    parameters = ["first_name":First_name,"last_name":last_name,"email":Email,"mobile_no":mobile]

    print(parameters)
    ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loading...")
    let URL1 = ApiUtillity.sharedInstance.API(Join: "user/update_profile")
    let url = URL(string: URL1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    var urlRequest = URLRequest(url: url!)
    urlRequest.httpMethod = "POST"
    urlRequest.allHTTPHeaderFields = headers
    Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append(self.imageData_pf_pic, withName: "profile_image", fileName: "image.jpg", mimeType: "image/jpg")


        for (key, value) in parameters {

            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

    }, with: urlRequest) { (encodingResult) in

        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                    let status = (JSON as AnyObject).value(forKey: "status") as! Int
                    let sts = Int(status)
                    if sts == 200
                    {
                        ApiUtillity.sharedInstance.dismissSVProgressHUD()
                        let UserData = ((JSON as AnyObject).value(forKey: "data") as! NSDictionary)
                        ApiUtillity.sharedInstance.setUserData(data: UserData)


                    }
                    else
                    {
                        ApiUtillity.sharedInstance.dismissSVProgressHUD()

                        let ErrorDic:NSDictionary = (JSON as AnyObject).value(forKey: "message") as! NSDictionary

                        let Errormobile_no = ErrorDic.value(forKey: "mobile_no") as? String
                        let Erroremail = ErrorDic.value(forKey: "email") as? String

                        if Errormobile_no?.count == nil
                        {}
                        else
                        {
                            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: Errormobile_no!)
                        }
                        if Erroremail?.count == nil
                        {}
                        else
                        {
                            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: Erroremail!)
                        }
                    }

                }

            }

        case .failure(let encodingError):
            ApiUtillity.sharedInstance.dismissSVProgressHUD()
            print(encodingError)
        }

    }
}

Boto3 to download all files from a S3 Bucket

Reposting @glefait 's answer with an if condition at the end to avoid os error 20. The first key it gets is the folder name itself which cannot be written in the destination path.

def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
    paginator = client.get_paginator('list_objects')
    for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
        if result.get('CommonPrefixes') is not None:
            for subdir in result.get('CommonPrefixes'):
                download_dir(client, resource, subdir.get('Prefix'), local, bucket)
        for file in result.get('Contents', []):
            print("Content: ",result)
            dest_pathname = os.path.join(local, file.get('Key'))
            print("Dest path: ",dest_pathname)
            if not os.path.exists(os.path.dirname(dest_pathname)):
                print("here last if")
                os.makedirs(os.path.dirname(dest_pathname))
            print("else file key: ", file.get('Key'))
            if not file.get('Key') == dist:
                print("Key not equal? ",file.get('Key'))
                resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)enter code here

"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)

The high voted answers didn't work for me, it seems to work for El Capitan users. But for MacOS Sierra users try the following steps

  1. brew install python
  2. sudo pip install --user <package name>

Using a Glyphicon as an LI bullet point (Bootstrap 3)

This isn't too difficult with a little CSS, and is much better than using an image for the bullet since you can scale it and colour it and it will keep sharp at all resolutions.

  1. Find the character code of the glyphicon by opening the Bootstrap docs and inspecting the character you want to use.

    Inspecting a glyphicon

  2. Use that character code in the following CSS

    li {
        display: block;
    }
    
    li:before {
        /*Using a Bootstrap glyphicon as the bullet point*/
        content: "\e080";
        font-family: 'Glyphicons Halflings';
        font-size: 9px;
        float: left;
        margin-top: 4px;
        margin-left: -17px;
        color: #CCCCCC;
    }
    

    You may like to tweak the colour and margins to suit your font size and taste.

View Demo & Code

ionic build Android | error: No installed build tools found. Please install the Android build tools

Go to D:Android sdk\Android SDK and click on SDK Manager and check whether Build Tools are installed or not if they are not installed then install those tools

.map() a Javascript ES6 Map?

You can map() arrays, but there is no such operation for Maps. The solution from Dr. Axel Rauschmayer:

  • Convert the map into an array of [key,value] pairs.
  • Map or filter the array.
  • Convert the result back to a map.

Example:

let map0 = new Map([
  [1, "a"],
  [2, "b"],
  [3, "c"]
]);

const map1 = new Map(
  [...map0]
  .map(([k, v]) => [k * 2, '_' + v])
);

resulted in

{2 => '_a', 4 => '_b', 6 => '_c'}

How to unzip gz file using Python

Maybe you want pass it to pandas also.

with gzip.open('features_train.csv.gz') as f:

    features_train = pd.read_csv(f)

features_train.head()

Android Push Notifications: Icon not displaying in notification, white square shown instead

I have resolved the problem by adding below code to manifest,

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/ic_stat_name" />

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/black" />

where ic_stat_name created on Android Studio Right Click on res >> New >>Image Assets >> IconType(Notification)

And one more step I have to do on server php side with notification payload

$message = [
    "message" => [
        "notification" => [
            "body"  => $title , 
            "title" => $message
        ],

        "token" => $token,

    "android" => [
           "notification" => [
            "sound"  => "default",
            "icon"  => "ic_stat_name"
            ]
        ],

       "data" => [
            "title" => $title,
            "message" => $message
         ]


    ]
];

Note the section

    "android" => [
           "notification" => [
            "sound"  => "default",
            "icon"  => "ic_stat_name"
            ]
        ]

where icon name is "icon" => "ic_stat_name" should be the same set on manifest.

ffprobe or avprobe not found. Please install one

There is some confusion when using pip install in Windows. The instructions talk about a specific folder which has youtube-dl.exe. There is no such folder if you use pip install.

The solution is to:

  • Download one of the builds from https://ffmpeg.zeranoe.com/
  • Extract the zip contents
  • Place the contents of the bin folder (there are three exe files) in any folder which is a path in Windows. I personally use Ananconda, so I placed them in /Anaconda/Scripts, but you could place it in any folder and add that folder to the path.

Oracle SQL - DATE greater than statement

As your query string is a literal, and assuming your dates are properly stored as DATE you should use date literals:

SELECT * FROM OrderArchive
WHERE OrderDate <= DATE '2015-12-31'

If you want to use TO_DATE (because, for example, your query value is not a literal), I suggest you to explicitly set the NLS_DATE_LANGUAGE parameter as you are using US abbreviated month names. That way, it won't break on some localized Oracle Installation:

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014', 'DD MON YYYY',
                           'NLS_DATE_LANGUAGE = American');

python pandas extract year from datetime: df['year'] = df['date'].year is not working

When to use dt accessor

A common source of confusion revolves around when to use .year and when to use .dt.year.

The former is an attribute for pd.DatetimeIndex objects; the latter for pd.Series objects. Consider this dataframe:

df = pd.DataFrame({'Dates': pd.to_datetime(['2018-01-01', '2018-10-20', '2018-12-25'])},
                  index=pd.to_datetime(['2000-01-01', '2000-01-02', '2000-01-03']))

The definition of the series and index look similar, but the pd.DataFrame constructor converts them to different types:

type(df.index)     # pandas.tseries.index.DatetimeIndex
type(df['Dates'])  # pandas.core.series.Series

The DatetimeIndex object has a direct year attribute, while the Series object must use the dt accessor. Similarly for month:

df.index.month               # array([1, 1, 1])
df['Dates'].dt.month.values  # array([ 1, 10, 12], dtype=int64)

A subtle but important difference worth noting is that df.index.month gives a NumPy array, while df['Dates'].dt.month gives a Pandas series. Above, we use pd.Series.values to extract the NumPy array representation.

How to open local files in Swagger-UI

In a local directory that contains the file ./docs/specs/openapi.yml that you want to view, you can run the following to start a container and access the spec at http://127.0.0.1:8246.

docker run -t -i -p 8246:8080 -e SWAGGER_JSON=/var/specs/openapi.yml -v $PWD/docs/specs:/var/specs swaggerapi/swagger-ui

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

It's interesting things with IDE (IntelliJ in this case):

  • if you leave default, i.e. don't declare spring-boot-starter-tomcat as provided, a spring-boot-maven-plugin (SBMP) put tomcat's jars to your war -> and you'll probably get errors deploying this war to container (there could be a versions conflict)

  • else you'll get classpath with no compile dependency on tomcat-embed (SBMP will build executable war/jar with provided deps included anyway)

    • intelliJ honestly doesn't see provided deps at runtime (they are not in classpath) when you run its Spring Boot run configuration.
    • and with no tomcat-embed you can't run Spring-Boot with embedded servlet container.

There is some tricky workaround: put Tomcat's jars to classpath of your idea-module via UI: File->Project Structure->(Libraries or Modules/Dependencies tab) .

  • tomcat-embed-core
  • tomcat-embed-el
  • tomcat-embed-websocket
  • tomcat-embed-logging-juli

Better solution for maven case

Instead of adding module dependencies in Idea, it is better to declare maven profile with compile scope of spring-boot-starter-tomcat library.

<profiles>
    <profile>
        <id>embed-tomcat</id>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <scope>compile</scope>
            </dependency>
        </dependencies>
    </profile>
</profiles>

while spring-boot-starter-tomcat was declared provided in <dependencies/>, making this profile active in IDE or CLI (mvn -Pembed-tomcat ...) allow you to launch build with embedded tomcat.

Ubuntu apt-get unable to fetch packages

Just for the sake of any Googlers, if you're getting this error while building a Docker image, preface the failing RUN command with

apt-get update &&

This happens when Docker uses a cached image. Why the cached image wouldn't have the latest repo information the second time around is totally beyond me, but prefacing every single apt-get with an update does solve the problem.

Combine several images horizontally with Python

Based on DTing's answer I created a function that is easier to use:

from PIL import Image


def append_images(images, direction='horizontal',
                  bg_color=(255,255,255), aligment='center'):
    """
    Appends images in horizontal/vertical direction.

    Args:
        images: List of PIL images
        direction: direction of concatenation, 'horizontal' or 'vertical'
        bg_color: Background color (default: white)
        aligment: alignment mode if images need padding;
           'left', 'right', 'top', 'bottom', or 'center'

    Returns:
        Concatenated image as a new PIL image object.
    """
    widths, heights = zip(*(i.size for i in images))

    if direction=='horizontal':
        new_width = sum(widths)
        new_height = max(heights)
    else:
        new_width = max(widths)
        new_height = sum(heights)

    new_im = Image.new('RGB', (new_width, new_height), color=bg_color)


    offset = 0
    for im in images:
        if direction=='horizontal':
            y = 0
            if aligment == 'center':
                y = int((new_height - im.size[1])/2)
            elif aligment == 'bottom':
                y = new_height - im.size[1]
            new_im.paste(im, (offset, y))
            offset += im.size[0]
        else:
            x = 0
            if aligment == 'center':
                x = int((new_width - im.size[0])/2)
            elif aligment == 'right':
                x = new_width - im.size[0]
            new_im.paste(im, (x, offset))
            offset += im.size[1]

    return new_im

It allows choosing a background color and image alignment. It's also easy to do recursion:

images = map(Image.open, ['hummingbird.jpg', 'tiger.jpg', 'monarch.png'])

combo_1 = append_images(images, direction='horizontal')
combo_2 = append_images(images, direction='horizontal', aligment='top',
                        bg_color=(220, 140, 60))
combo_3 = append_images([combo_1, combo_2], direction='vertical')
combo_3.save('combo_3.png')

Example concatenated image

Reading specific columns from a text file in python

I know this is an old question, but nobody mentioned that when your data looks like an array, numpy's loadtxt comes in handy:

>>> import numpy as np
>>> np.loadtxt("myfile.txt")[:, 1]
array([10., 20., 30., 40., 23., 13.])

How to install Intellij IDEA on Ubuntu?

Since Ubuntu 16.04 includes snapd by default.
So, the easiest way to install the stable version is

  • IntelliJ IDEA Community:
    $ sudo snap install intellij-idea-community --classic
  • IntelliJ IDEA Ultimate:
    $ sudo snap install intellij-idea-ultimate --classic

For the latest version use channel --edge
$ sudo snap install intellij-idea-community --classic --edge

Here is the list of all channels https://snapcraft.io/intellij-idea-ultimate (drop down 'All versions').

options

--classic

The --classic option is required because the IntelliJ IDEA snap requires full access to the system, like a traditionally packaged application.
[https://www.jetbrains.com/help/idea/install-and-set-up-product.html#install-on-linux-with-snaps]

--edge

--edge Install from the edge channel [http://manpages.ubuntu.com/manpages/bionic/man1/snap.1.html]

Note: Snap, also work a few major distributions: Arch, Debian, Fedora, openSUSE, Linux Mint,...

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

The logic is simple. setOnClickListener belongs to step 2.

  1. You create the button
  2. You create an instance of OnClickListener* like it's done in that example and override the onClick-method.
  3. You assign that OnClickListener to that button using btn.setOnClickListener(myOnClickListener); in your fragments/activities onCreate-method.
  4. When the user clicks the button, the onClick function of the assigned OnClickListener is called.

*If you import android.view.View; you use View.OnClickListener. If you import android.view.View.*; or import android.view.View.OnClickListener; you use OnClickListener as far as I get it.

Another way is to let you activity/fragment inherit from OnClickListener. This way you assign your fragment/activity as the listener for your button and implement onClick as a member-function.

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

How do I extract data from JSON with PHP?

// Using json as php array 

$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';

//or use from file
//$json = file_get_contents('results.json');

$someArray = json_decode($json, true);

foreach ($someArray as $key => $value) {
    echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}

How to break out of the IF statement

You can use a goto to drop past some code. In the example, if thing1 is true then the check for things2 is bypassed.

if (something) {
    do_stuff();
    if (thing1) { 
        do_thing1();
        goto SkipToEnd;
    }
    if (thing2) {
        do_thing2();
    }
SkipToEnd:
    do_thing3();
}

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

These are the correct version that you can add in your build.gradle according to the API needs.

API 24:

implementation 'com.android.support:appcompat-v7:24.2.1'
implementation 'com.android.support:recyclerview-v7:24.2.1'

API 25:

implementation 'com.android.support:appcompat-v7:25.4.0'
implementation 'com.android.support:recyclerview-v7:25.4.0'

API 26:

implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:recyclerview-v7:26.1.0'

API 27:

implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'

Replace all occurrences of a string in a data frame

I had the problem, I had to replace "Not Available" with NA and my solution goes like this

data <- sapply(data,function(x) {x <- gsub("Not Available",NA,x)})

Using --add-host or extra_hosts with docker-compose

Basic docker-compose.yml with extra hosts:

version: '3'
services:
api:
    build: .
    ports:
        - "5003:5003"
    extra_hosts:
        - "your-host.name.com:162.242.195.82" #host and ip
        - "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
        

The content in the /etc/hosts file in the created container:

162.242.195.82  your-host.name.com
50.31.209.229   your-host--1.name.com your-host--2.name.com

You can check the /etc/hosts file with the following commands:

$ docker-compose -f path/to/file/docker-compose.yml run api bash  # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts

How to convert a pymongo.cursor.Cursor into a dict?

The find method returns a Cursor instance, which allows you to iterate over all matching documents.

To get the first document that matches the given criteria you need to use find_one. The result of find_one is a dictionary.

You can always use the list constructor to return a list of all the documents in the collection but bear in mind that this will load all the data in memory and may not be what you want.

You should do that if you need to reuse the cursor and have a good reason not to use rewind()


Demo using find:

>>> import pymongo
>>> conn = pymongo.MongoClient()
>>> db = conn.test #test is my database
>>> col = db.spam #Here spam is my collection
>>> cur = col.find()  
>>> cur
<pymongo.cursor.Cursor object at 0xb6d447ec>
>>> for doc in cur:
...     print(doc)  # or do something with the document
... 
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}
{'a': 1, 'c': 3, '_id': ObjectId('54ff32a2add8f30feb902690'), 'b': 2}

Demo using find_one:

>>> col.find_one()
{'a': 1, '_id': ObjectId('54ff30faadd8f30feb90268f'), 'b': 2}

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

PHP - SSL certificate error: unable to get local issuer certificate

elaborating on the above answers for server deployment.

$hostname = gethostname();
if($hostname=="mydevpc")
{
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}

should do the trick for development environment without compromising the server when deployed.

ECMAScript 6 arrow function that returns an object

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

Hadoop cluster setup - java.net.ConnectException: Connection refused

I was getting the same issue and found that OpenSSH service was not running and it was causing the issue. After starting the SSH service it worked.

To check if SSH service is running or not:

ssh localhost

To start the service, if OpenSSH is already installed:

sudo /etc/init.d/ssh start

Extract / Identify Tables from PDF python

I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py

This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.

android.content.Context.getPackageName()' on a null object reference

Put fragment name before the activity

Intent mIntent = new Intent(SigninFragment.this.getActivity(),MusicHome.class);

EXEC sp_executesql with multiple parameters

If one need to use the sp_executesql with OUTPUT variables:

EXEC sp_executesql @sql
                  ,N'@p0 INT'
                  ,N'@p1 INT OUTPUT'
                  ,N'@p2 VARCHAR(12) OUTPUT' 
                  ,@p0
                  ,@p1 OUTPUT
                  ,@p2 OUTPUT;

How to change default Anaconda python environment

The correct answer (as of Dec 2018) is... you can't. Upgrading conda install python=3.6 may work, but it might not if you have packages that are necessary, but cannot be uninstalled.

Anaconda uses a default environment named base and you cannot create a new (e.g. python 3.6) environment with the same name. This is intentional. If you want your base Anaconda to be python 3.6, the right way to do this is to install Anaconda for python 3.6. As a package manager, the goal of Anaconda is to make different environments encapsulated, hence why you must source activate into them and why you can't just quietly switch the base package at will as this could lead to many issues on production systems.

Open web in new tab Selenium + Python

browser.execute_script('''window.open("http://bings.com","_blank");''')

Where browser is the webDriver

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

How to decompile to java files intellij idea

Some time ago I used JAD (JAva Decompiler) to achieve this - I do not think IntelliJ's decompiler was incorporated with exporting in mind. It is more of a tool to help look through classes where sources are not available.

JAD is still available for download, but I do not think anyone maintains it anymore: http://varaneckas.com/jad/

There were numerous plugins for it, namely Jadclipse (you guessed it, a way to use JAD in Eclipse - see decompiled classes where code is not available :)).

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

CSS selector:

Use a CSS selector of img[src='images/toolbar/b_edit.gif']

This says select element(s) with img tag with attribute src having value of 'images/toolbar/b_edit.gif'


CSS query:

CSS query


VBA:

You can apply the selector with the .querySelector method of document.

IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click

Extract time from moment js object

If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:

moment("2015-01-16T12:00:00").format("hh:mm:ss a")

See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/

How to extract multiple JSON objects from one file?

Added streaming support based on the answer of @dunes:

import re
from json import JSONDecoder, JSONDecodeError

NOT_WHITESPACE = re.compile(r"[^\s]")


def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
    buf = ""
    ex = None
    while True:
        block = file_obj.read(buf_size)
        if not block:
            break
        buf += block
        pos = 0
        while True:
            match = NOT_WHITESPACE.search(buf, pos)
            if not match:
                break
            pos = match.start()
            try:
                obj, pos = decoder.raw_decode(buf, pos)
            except JSONDecodeError as e:
                ex = e
                break
            else:
                ex = None
                yield obj
        buf = buf[pos:]
    if ex is not None:
        raise ex

How do I make a self extract and running installer

Okay I have got it working, hope this information is useful.

  1. First of all I now realize that not only do self-extracting zip start extracting with doubleclick, but they require no extraction application to be installed on the users computer because the extractor code is in the archive itself. This means that you will get a different user experience depending on what you application you use to create the sfx

  2. I went with WinRar as follows, this does not require you to create an sfx file, everything can be created via the gui:

    • Select files, right click and select Add to Archive
    • Use Browse.. to create the archive in the folder above
    • Change Archive Format to Zip
    • Enable Create SFX archive
    • Select Advanced tab
    • Select SFX Options
    • Select Setup tab
    • Enter setup.exe into the Run after Extraction field
    • Select Modes tab
    • Enable Unpack to temporary folder
    • Select text and Icon tab
    • Enter a more appropriate title for your task
    • Select OK
    • Select OK

The resultant exe unzips to a temporary folder and then starts the installer

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

Swift extract regex matches

The fastest way to return all matches and capture groups in Swift 5

extension String {
    func match(_ regex: String) -> [[String]] {
        let nsString = self as NSString
        return (try? NSRegularExpression(pattern: regex, options: []))?.matches(in: self, options: [], range: NSMakeRange(0, count)).map { match in
            (0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : nsString.substring(with: match.range(at: $0)) }
        } ?? []
    }
}

Returns a 2-dimentional array of strings:

"prefix12suffix fix1su".match("fix([0-9]+)su")

returns...

[["fix12su", "12"], ["fix1su", "1"]]

// First element of sub-array is the match
// All subsequent elements are the capture groups

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

try like this. hope it works

drawable-sw720dp-xxhdpi and values-sw720dp-xxhdpi

drawable-sw720dp-xxxhdpi and values-sw720dp-xxxhdpi

link might destroy so pasted ans

reference Android xxx-hdpi real devices

xxxhdpi was only introduced because of the way that launcher icons are scaled on the nexus 5's launcher Because the nexus 5's default launcher uses bigger icons, xxxhdpi was introduced so that icons would still look good on the nexus 5's launcher.

also check these links

Different resolution support android

Application Skeleton to support multiple screen

Is there a list of screen resolutions for all Android based phones and tablets?

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Using ADB to capture the screen

To start recording your device’s screen, run the following command:

adb shell screenrecord /sdcard/example.mp4

This command will start recording your device’s screen using the default settings and save the resulting video to a file at /sdcard/example.mp4 file on your device.

When you’re done recording, press Ctrl+C in the Command Prompt window to stop the screen recording. You can then find the screen recording file at the location you specified. Note that the screen recording is saved to your device’s internal storage, not to your computer.

The default settings are to use your device’s standard screen resolution, encode the video at a bitrate of 4Mbps, and set the maximum screen recording time to 180 seconds. For more information about the command-line options you can use, run the following command:

adb shell screenrecord --help

This works without rooting the device. Hope this helps.

Loop through a comma-separated shell variable

#/bin/bash   
TESTSTR="abc,def,ghij"

for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done

I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

other solution is to set IFS to certain separator

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

How to extract 1 screenshot for a video with ffmpeg at a given time?

FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:

ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg

Let's explain the options:

-i input file           the path to the input file
-ss 01:23:45            seek the position to the specified timestamp
-vframes 1              only handle one video frame
output.jpg              output filename, should have a well-known extension

The -ss parameter accepts a value in the form HH:MM:SS[.xxx] or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.

Android "elevation" not showing a shadow

one other thing that you should be aware of, shadows will not show if you have this line in the manifest:

android:hardwareAccelerated="false"

I tried all of the suggested stuff but it only worked for me when i removed the line, the reason i had the line was because my app works with a number of bitmap images and they were causing the app to crash.

Android Studio doesn't start, fails saying components not installed

If are you using Linux, I noticed that the Android Studio cannot be run with JDK 8. You have to download open Jdk 7 and press alt + shift + t and type:

sudo apt-get install openjdk-7-jre 

When u have downloaded jdk 7 go to terminal then go to android-studio/bin then type

sudo sh ./studio.sh 

Meaning of end='' in the statement print("\t",end='')?

See the documentation for the print function: print()

The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.

An error when I add a variable to a string

You have empty $entry_database variable. As you see in error: ListEmail, Title FROM WHERE ID bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:

SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]

which in your way should become:

SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'

how to create virtual host on XAMPP

I'm a little late to the party, but I wrote this little bash script for Mac that creates a VirtualHost through the terminal:

#!/bin/bash

echo "Welcome to the VirtualHostCreator! Press <RETURN> to continue."

read

echo "Enter the name the VirtualHost you would like to create. No spaces or dashes, please."

read hostname

echo "Enter the document root of the VirtualHost."

read doc_root

echo "Creating VirtualHost \"$hostname\". You may be prompted for your password."

hosts_file="/etc/hosts"
vhosts_file="/Applications/XAMPP/xamppfiles/etc/extra/httpd-vhosts.conf"
restart_command="sudo /Applications/XAMPP/xamppfiles/xampp restart"

cat >> $vhosts_file << EndOfMessage
<VirtualHost ${hostname}>
    ServerName ${hostname}
    DocumentRoot "/Applications/XAMPP/xamppfiles/htdocs/${doc_root}"
</VirtualHost>
EndOfMessage

sudo sh -c "echo \"127.0.0.1       $hostname\" >> $hosts_file"

$restart_command

I'm sure there are a few improvements that can be made, and it only has the two required options for the vhost (server name and document root), but it does the job much more quickly and efficiently than opening and editing all the files manually, and also automatically restarts XAMPP afterwards.

This assumes that you have the default installation location for XAMPP, which can all be changed.

Sending a file over TCP sockets in Python

Remove below code

s.send("Hello server!")

because your sending s.send("Hello server!") to server, so your output file is somewhat more in size.

Postgres: How to convert a json string to text?

An easy way of doing this:

SELECT  ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;

Just convert the json string into a json list

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

NSRange from Swift Range?

My solution is a string extension that first gets the swift range then get's the distance from the start of the string to the start and end of the substring.

These values are then used to calculate the start and length of the substring. We can then apply these values to the NSMakeRange constructor.

This solution works with substrings that consist of multiple words, which a lot of the solutions here using enumerateSubstrings let me down on.

extension String {

    func NSRange(of substring: String) -> NSRange? {
        // Get the swift range 
        guard let range = range(of: substring) else { return nil }

        // Get the distance to the start of the substring
        let start = distance(from: startIndex, to: range.lowerBound) as Int
        //Get the distance to the end of the substring
        let end = distance(from: startIndex, to: range.upperBound) as Int

        //length = endOfSubstring - startOfSubstring
        //start = startOfSubstring
        return NSMakeRange(start, end - start)
    }

}

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

demo - http://jsfiddle.net/victor_007/ywevz8ra/

added border for better view (testing)

more info about white-space

table{
    width:100%;
}
table td{
    white-space: nowrap;  /** added **/
}
table td:last-child{
    width:100%;
}

_x000D_
_x000D_
    table {_x000D_
      width: 100%;_x000D_
    }_x000D_
    table td {_x000D_
      white-space: nowrap;_x000D_
    }_x000D_
    table td:last-child {_x000D_
      width: 100%;_x000D_
    }
_x000D_
<table border="1">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Extract Number from String in Python

Your regex looks correct. Are you sure you haven't made a mistake with the variable names? In your code above you mixup total_hotel_reviews_string and str.

>>> import re
>>> s = "3158 reviews"
>>> 
>>> print(re.findall("\d+", s))
['3158']

Android Studio SDK location

  • Linux (Ubuntu 18.4)

/home/<USER_NAME>/Android/Sdk

  • windows (8.1)

C:\Users\<USER_NAME>\AppData\Local\Android\sdk

(AppData folder is hidden, check folder properties first)

  • macOS (Sierra 10.12.6)

/Users/<USER_NAME>/Library/Android/sdk

How do I get the name of the rows from the index of a data frame?

this seems to work fine :

dataframe.axes[0].tolist()

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

This works perfectly fine for me:

AdapterChart adapterChart = new AdapterChart(getContext(),messageList);
recyclerView.setAdapter(adapterChart);
recyclerView.scrollToPosition(recyclerView.getAdapter().getItemCount()-1);

Android: making a fullscreen application

Add these to Activity of your application.

Android JAVA

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  WindowManager.LayoutParams.FLAG_FULLSCREEN)

;

Android Kotlin

supportActionBar?.hide()
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)

Extracting text from a PDF file using PDFMiner in python?

terrific answer from DuckPuncher, for Python3 make sure you install pdfminer2 and do:

import io

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = io.StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos = set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,
                                  password=password,
                                  caching=caching,
                                  check_extractable=True):
        interpreter.process_page(page)



    fp.close()
    device.close()
    text = retstr.getvalue()
    retstr.close()
    return text

Android API 21 Toolbar Padding

In case someone else stumbles here... you can set padding as well, for instance:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

int padding = 200 // padding left and right

toolbar.setPadding(padding, toolbar.getPaddingTop(), padding, toolbar.getPaddingBottom());

Or contentInset:

toolbar.setContentInsetsAbsolute(toolbar.getContentInsetLeft(), 200);

OperationalError, no such column. Django

If the error persists after doing what @Burhan Khalid said

Try this line: python manage.py migrate --run-syncdb

extract month from date in python

import datetime

a = '2010-01-31'

datee = datetime.datetime.strptime(a, "%Y-%m-%d")


datee.month
Out[9]: 1

datee.year
Out[10]: 2010

datee.day
Out[11]: 31

Converting file into Base64String and back again

Another working example in VB.NET:

Public Function base64Encode(ByVal myDataToEncode As String) As String
    Try
        Dim myEncodeData_byte As Byte() = New Byte(myDataToEncode.Length - 1) {}
        myEncodeData_byte = System.Text.Encoding.UTF8.GetBytes(myDataToEncode)
        Dim myEncodedData As String = Convert.ToBase64String(myEncodeData_byte)
        Return myEncodedData
    Catch ex As Exception
        Throw (New Exception("Error in base64Encode" & ex.Message))
    End Try
    '
End Function

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

How to extract hours and minutes from a datetime.datetime object?

Don't know how you want to format it, but you can do:

print("Created at %s:%s" % (t1.hour, t1.minute))

for example.

Android: Internet connectivity change listener

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)

AngularJS ng-click to go to another page (with Ionic framework)

Based on comments, and due to the fact that @Thinkerer (the OP - original poster) created a plunker for this case, I decided to append another answer with more details.

The first and important change:

// instead of this
$urlRouterProvider.otherwise('/tab/post');

// we have to use this
$urlRouterProvider.otherwise('/tab/posts');

because the states definition is:

.state('tab', {
  url: "/tab",
  abstract: true,
  templateUrl: 'tabs.html'
})

.state('tab.posts', {
  url: '/posts',
  views: {
    'tab-posts': {
      templateUrl: 'tab-posts.html',
      controller: 'PostsCtrl'
    }
  }
})

and we need their concatenated url '/tab' + '/posts'. That's the url we want to use as a otherwise

The rest of the application is really close to the result we need...
E.g. we stil have to place the content into same view targetgood, just these were changed:

.state('tab.newpost', {
  url: '/newpost',
  views: {
    // 'tab-newpost': {
    'tab-posts': {
      templateUrl: 'tab-newpost.html',
      controller: 'NavCtrl'
    }
  }

because .state('tab.newpost' would be replacing the .state('tab.posts' we have to place it into the same anchor:

<ion-nav-view name="tab-posts"></ion-nav-view>  

Finally some adjustments in controllers:

$scope.create = function() {
    $state.go('tab.newpost');
};
$scope.close = function() { 
     $state.go('tab.posts'); 
};

As I already said in my previous answer and comments ... the $state.go() is the only right way how to use ionic or ui-router

Check that all here Final note - I made running just navigation between tab.posts... tab.newpost... the rest would be similar

Extract the maximum value within each group in a dataframe

Using sqldf and standard sql to get the maximum values grouped by another variable

https://cran.r-project.org/web/packages/sqldf/sqldf.pdf

library(sqldf)
sqldf("select max(Value),Gene from df1 group by Gene")

or

Using the excellent Hmisc package for a groupby application of function (max) https://www.rdocumentation.org/packages/Hmisc/versions/4.0-3/topics/summarize

library(Hmisc)
summarize(df1$Value,df1$Gene,max)

How to extract text from an existing docx file using python-docx

Without Installing python-docx

docx is basically is a zip file with several folders and files within it. In the link below you can find a simple function to extract the text from docx file, without the need to rely on python-docx and lxml the latter being sometimes hard to install:

http://etienned.github.io/posts/extract-text-from-word-docx-simply/

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

Extracting just Month and Year separately from Pandas Datetime column

There is two steps to extract year for all the dataframe without using method apply.

Step1

convert the column to datetime :

df['ArrivalDate']=pd.to_datetime(df['ArrivalDate'], format='%Y-%m-%d')

Step2

extract the year or the month using DatetimeIndex() method

 pd.DatetimeIndex(df['ArrivalDate']).year

Extract first item of each sublist

Python includes a function called itemgetter to return the item at a specific index in a list:

from operator import itemgetter

Pass the itemgetter() function the index of the item you want to retrieve. To retrieve the first item, you would use itemgetter(0). The important thing to understand is that itemgetter(0) itself returns a function. If you pass a list to that function, you get the specific item:

itemgetter(0)([10, 20, 30]) # Returns 10

This is useful when you combine it with map(), which takes a function as its first argument, and a list (or any other iterable) as the second argument. It returns the result of calling the function on each object in the iterable:

my_list = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y', 'z']]
list(map(itemgetter(0), my_list)) # Returns ['a', 1, 'x']

Note that map() returns a generator, so the result is passed to list() to get an actual list. In summary, your task could be done like this:

lst2.append(list(map(itemgetter(0), lst)))

This is an alternative method to using a list comprehension, and which method to choose highly depends on context, readability, and preference.

More info: https://docs.python.org/3/library/operator.html#operator.itemgetter

The Import android.support.v7 cannot be resolved

I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20

The support library android-support-v4.jar is causing this conflict, just delete the library under /libs folder of your project, don´t be scared, the library is already contained in the library appcompat_v7, clean and build your project, and your project will work like a charm!

enter image description here

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

I believe James Hunt's answer will solve the problem.

@user3731784: In your new message, the compiler seems to be confused because of the "C:\Program Files\IAR systems\Embedded Workbench 7.0\430\lib\dlib\d1430fn.h" argument. Why are you giving this header file at the middle of other compiler switches? Please correct this and try again. Also, it probably is a good idea to give the source file name after all the compiler switches and not at the beginning.

Attach parameter to button.addTarget action in Swift

Swift 4.0 code (Here we go again)

The called action should marked like this because that is the syntax for swift function for exporting functions into objective c language.

@objc func deleteAction(sender: UIButton) {
}

create some working button:

let deleteButton = UIButton(type: .roundedRect)
deleteButton.setTitle("Delete", for: [])
deleteButton.addTarget(self, action: #selector( 
MyController.deleteAction(sender:)), for: .touchUpInside)

Custom Listview Adapter with filter Android

First you create the EditText in the xml file and assign an id, eg con_pag_etPesquisa. After that, we will create two lists, where one is the list view and the other to receive the same content but will remain as a backup. Before moving objects to lists first initializes Them the below:

//Declaring

public EditText etPesquisa;

public ContasPagarAdapter adapterNormal;

public List<ContasPagar> lstBkp;

public List<ContasPagar> lstCp;

//Within the onCreate method, type the following:

etPesquisa = (EditText) findViewById(R.id.con_pag_etPesquisa);

etPesquisa.addTextChangedListener(new TextWatcher(){

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
        filter(String.valueOf(cs));
    }
    @Override
    public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3){

    // TODO Auto-generated method stub
    }
    @Override
    public void afterTextChanged(Editable e){

    }

});

//Before moving objects to lists first initializes them as below:

lstCp = new ArrayList<ContasPagar>();

lstBkp = new ArrayList<ContasPagar>();


//When you add objects to the main list, repeat the procedure also for bkp list, as follows:

lstCp.add(cp);

lstBkp.add(cp);


//Now initializes the adapter and let the listener, as follows:

adapterNormal = new ContasPagarAdapter(ContasPagarActivity.this, lstCp);

lvContasPagar.setAdapter(adapterNormal);
                    lvContasPagar.setOnItemClickListener(verificaClickItemContasPagar(lstCp));


//Now create the methods inside actito filter the text entered by the user, as follows:

public void filter(String charText){

    charText = charText.toLowerCase();

    lstCp.clear();

    if (charText.length() == 0){

        lstCp.addAll(lstBkp);

        appendAddItem(lstBkp);

    } 

    else {

        for (int i = 0; i < lstBkp.size(); i++){

            if((lstBkp.get(i).getNome_lancamento() + " - " + String.valueOf(lstBkp.get(i).getCodigo())).toLowerCase().contains(charText)){

                lstCp.add(lstBkp.get(i));

            }

        }

        appendAddItem(lstCp);
    }
}

private void appendAddItem(final List<ContasPagar> novaLista){
    runOnUiThread(new Runnable(){

        @Override
            public void run(){
                adapterNormal.notifyDataSetChanged();               
            }
        });
    }

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

Find elements inside forms and iframe using Java and Selenium WebDriver

On Selenium >= 3.41 (C#) the rigth syntax is:

webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));

Print the data in ResultSet along with column names

ResultSet resultSet = statement.executeQuery("SELECT * from foo");
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (resultSet.next()) {
    for (int i = 1; i <= columnsNumber; i++) {
        if (i > 1) System.out.print(",  ");
        String columnValue = resultSet.getString(i);
        System.out.print(columnValue + " " + rsmd.getColumnName(i));
    }
    System.out.println("");
}

Reference : Printing the result of ResultSet

Checking Maven Version

you can use just

     <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version></version>
    </dependency>

How to find the highest value of a column in a data frame in R?

Here's a dplyr solution:

library(dplyr)

# find max for each column
summarise_each(ozone, funs(max(., na.rm=TRUE)))

# sort by Solar.R, descending
arrange(ozone, desc(Solar.R))

UPDATE: summarise_each() has been deprecated in favour of a more featureful family of functions: mutate_all(), mutate_at(), mutate_if(), summarise_all(), summarise_at(), summarise_if()

Here is how you could do:

# find max for each column
ozone %>%
         summarise_if(is.numeric, funs(max(., na.rm=TRUE)))%>%
         arrange(Ozone)

or

ozone %>%
         summarise_at(vars(1:6), funs(max(., na.rm=TRUE)))%>%
         arrange(Ozone)

How to change default install location for pip

You can set the following environment variable:

PIP_TARGET=/path/to/pip/dir

https://pip.pypa.io/en/stable/user_guide/#environment-variables

How do I do an OR filter in a Django query?

It is worth to note that it's possible to add Q expressions.

For example:

from django.db.models import Q

query = Q(first_name='mark')
query.add(Q(email='[email protected]'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)

queryset = User.objects.filter(query)

This ends up with a query like :

(first_name = 'mark' or email = '[email protected]') and last_name = 'doe'

This way there is no need to deal with or operators, reduce's etc.

Limit results in jQuery UI Autocomplete

I did it in following way :

success: function (result) {
response($.map(result.d.slice(0,10), function (item) {
return {
// Mapping to Required columns (Employee Name and Employee No)
label: item.EmployeeName,
value: item.EmployeeNo
}
}
));

Python 3.6 install win32api?

Take a look at this answer: ImportError: no module named win32api

You can use

pip install pypiwin32

Accessing Websites through a Different Port?

Perhaps this is obvious, but FWIW this will only work if the web server is serving requests for that website on the alternate port. It's not at all uncommon for a webserver to only serve a site on port 80.

Android set bitmap to Imageview

    //decode base64 string to image
    imageBytes = Base64.decode(encodedImage, Base64.DEFAULT);
    Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
    image.setImageBitmap(decodedImage);

  //setImageBitmap is imp

Rendering React Components from Array of Objects

I have an answer that might be a bit less confusing for newbies like myself. You can just use map within the components render method.

render () {
   return (
       <div>
           {stations.map(station => <div key={station}> {station} </div>)} 
       </div>
   );
}

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

I am new to spring spent an hour trying to figure this out.

go to --- > application.properties

add these :

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

How to change the height of a <br>?

I know this is an old question however for me it worked by actually using an empty paragraph with margins:

<p class="" style="margin: 4px;"></p>

Increasing or decreasing the margin size will increase or decrease the distance between elements just like a border would do but adjustable.

On top of that, it is browser compatible.

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

With the GnuWin32 tools I found the openssl.cnf under C:\gnuwin32\share

set OPENSSL_CONF=C:\gnuwin32\share\openssl.cnf

Virtual/pure virtual explained

Simula, C++, and C#, which use static method binding by default, the programmer can specify that particular methods should use dynamic binding by labeling them as virtual. Dynamic method binding is central to object-oriented programming.

Object oriented programming requires three fundamental concepts: encapsulation, inheritance, and dynamic method binding.

Encapsulation allows the implementation details of an abstraction to be hidden behind a simple interface.

Inheritance allows a new abstraction to be defined as an extension or refinement of some existing abstraction, obtaining some or all of its characteristics automatically.

Dynamic method binding allows the new abstraction to display its new behavior even when used in a context that expects the old abstraction.

Easy way to turn JavaScript array into comma-separated list?

I think this should do it:

var arr = ['contains,comma', 3.14, 'contains"quote', "more'quotes"]
var item, i;
var line = [];

for (i = 0; i < arr.length; ++i) {
    item = arr[i];
    if (item.indexOf && (item.indexOf(',') !== -1 || item.indexOf('"') !== -1)) {
        item = '"' + item.replace(/"/g, '""') + '"';
    }
    line.push(item);
}

document.getElementById('out').innerHTML = line.join(',');

fiddle

Basically all it does is check if the string contains a comma or quote. If it does, then it doubles all the quotes, and puts quotes on the ends. Then it joins each of the parts with a comma.

What is an unhandled promise rejection?

When I instantiate a promise, I'm going to generate an asynchronous function. If the function goes well then I call the RESOLVE then the flow continues in the RESOLVE handler, in the THEN. If the function fails, then terminate the function by calling REJECT then the flow continues in the CATCH.

In NodeJs are deprecated the rejection handler. Your error is just a warning and I read it inside node.js github. I found this.

DEP0018: Unhandled promise rejections

Type: Runtime

Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

git pull while not in a git directory

You can write a script like this:

cd /X/Y
git pull

You can name it something like gitpull.
If you'd rather have it do arbitrary directories instead of /X/Y:

cd $1
git pull

Then you can call it with gitpull /X/Z
Lastly, you can try finding repositories. I have a ~/git folder which contains repositories, and you can use this to do a pull on all of them.

g=`find /X -name .git`
for repo in ${g[@]}
do
    cd ${repo}
    cd ..
    git pull
done

CSS align one item right with flexbox

To align some elements (headerElement) in the center and the last element to the right (headerEnd).

.headerElement {
    margin-right: 5%;
    margin-left: 5%;
}
.headerEnd{
    margin-left: auto;
}

PHP cURL not working - WAMP on Windows 7 64 bit

Works for me:

  • Go to this link
  • Download *php_curl-5.4.3-VC9-x64.zip* under "Fixed curl extensions:"
  • Replace the php_curl.dll file in the ext folder.

This worked for me.

Any way to write a Windows .bat file to kill processes?

Here I wrote an example command that you can paste in your cmd command line prompt and is written for chrome.exe.

FOR /F "tokens=2 delims= " %P IN ('tasklist /FO Table /M "chrome*" /NH') DO (TASKKILL /PID %P)

The for just takes all the PIDs listed on the below tasklist command and executes TASKKILL /PID on every PID

tasklist /FO Table /M "chrome*" /NH

If you use the for in a batch file just use %%P instead of %P

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

The most correct way is to use HttpContext.Current.Server.MapPath("~/App_Data");. This means you can only retrieve the path from a method where the HttpContext is available. It makes sense: the App_Data directory is a web project folder structure [1].

If you need the path to ~/App_Data from a class where you don't have access to the HttpContext you can always inject a provider interface using your IoC container:

public interface IAppDataPathProvider
{
    string GetAppDataPath();
}

Implement it using your HttpApplication:

public class AppDataPathProvider : IAppDataPathProvider
{
    public string GetAppDataPath()
    {
        return MyHttpApplication.GetAppDataPath();
    }
}

Where MyHttpApplication.GetAppDataPath looks like:

public class MyHttpApplication : HttpApplication
{
    // of course you can fetch&store the value at Application_Start
    public static string GetAppDataPath()
    {
        return HttpContext.Current.Server.MapPath("~/App_Data");
    }
}

[1] http://msdn.microsoft.com/en-us/library/ex526337%28v=vs.100%29.aspx

How to replace local branch with remote branch entirely in Git?

The selected answer is absolutely correct, however it did not leave me with the latest commit/pushes ...

So for me:

git reset --hard dev/jobmanager-tools
git pull  ( did not work as git was not sure what branch i wanted)

Since I know I want to temporarily set my upstream branch for a few weeks to a specific branch ( same as the one i switched to / checked out earlier and did a hard reset on )

So AFTER reset

git branch --set-upstream-to=origin/dev/jobmanager-tools
git pull
git status    ( says--> on branch  dev/jobmanager-tools 

java - iterating a linked list

iterate LinkedList by using iterator

LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add(“Mumbai”);
linkedList.add(“Delhi”);
linkedList.add(“Noida”);
linkedList.add(“Gao”);
linkedList.add(“Patna”);

Iterator<String>  itr = linkedList.iterator();
 while (itr.hasNext()) {
 System.out.println(“Element is =”+itr.next());

 }

Reference : Java Linkedlist Examples

Android XML Percent Symbol

You can escape % using %% for XML parser, but it is shown twice in device.

To show it once, try following format: \%%

For Example

<string name="zone_50">Fat Burning (50\%% to 60\%%)</string> 

is shown as Fat Burning (50% to 60%) in device

Copy every nth line from one sheet to another

insert a new column and put a series in 1,2,3,4, etc. Then create another new column and use the command =if(int(a1/7)=(a1/7),1,0) you should get a 1 in every 7th row, filter the column on the 1

RegEx pattern any two letters followed by six numbers

Everything you need here can be found in this quickstart guide. A straightforward solution would be [A-Za-z][A-Za-z]\d\d\d\d\d\d or [A-Za-z]{2}\d{6}.

If you want to accept only capital letters then replace [A-Za-z] with [A-Z].

How to output a multiline string in Bash?

Here documents are often used for this purpose.

cat << EOF
usage: up [--level <n>| -n <levels>][--help][--version]

Report bugs to: 
up home page:
EOF

They are supported in all Bourne-derived shells including all versions of Bash.

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

iPhone UITextField - Change placeholder text color

For those using Monotouch (Xamarin.iOS), here's Adam's answer, translated to C#:

public class MyTextBox : UITextField
{
    public override void DrawPlaceholder(RectangleF rect)
    {
        UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
        new NSString(this.Placeholder).DrawString(rect, Font);
    }
}

What is Common Gateway Interface (CGI)?

A CGI script is a console/shell program. In Windows, when you use a "Command Prompt" window, you execute console programs. When a web server executes a CGI script it provides input to the console/shell program using environment variables or "standard input". Standard input is like typing data into a console/shell program; in the case of a CGI script, the web server does the typing. The CGI script writes data out to "standard output" and that output is sent to the client (the web browser) as a HTML page. Standard output is like the output you see in a console/shell program except the web server reads it and sends it out.

A CGI script can be executed from a browser. The URI typically includes a query string that is provided to the CGI script. If the method is "get" then the query string is provided to the CGI Script in an environment variable called QUERY_STRING. If the method is "post" then the query string is provided to the CGI Script using standard input (the CGI Script reads the query string from standard input).

An early use of CGI scripts was to process forms. In the beginning of HTML, HTML forms typically had an "action" attribute and a button designated as the "submit" button. When the submit button is pushed the URI specified in the "action" attribute would be sent to the server with the data from the form sent as a query string. If the "action" specifies a CGI script then the CGI script would be executed and it then produces a HTML page.

RFC 3875 "The Common Gateway Interface (CGI)" partially defines CGI using C, as in saying that environment variables "are accessed by the C library routine getenv() or variable environ".

If you are developing a CGI script using C/C++ and use Microsoft Visual Studio to do that then you would develop a console program.

What's the difference between implementation and compile in Gradle?

tl;dr

Just replace:

  • compile with implementation (if you don't need transitivity) or api (if you need transitivity)
  • testCompile with testImplementation
  • debugCompile with debugImplementation
  • androidTestCompile with androidTestImplementation
  • compileOnly is still valid. It was added in 3.0 to replace provided and not compile. (provided introduced when Gradle didn't have a configuration name for that use-case and named it after Maven's provided scope.)

It is one of the breaking changes coming with Android Gradle plugin 3.0 that Google announced at IO17.

The compile configuration is now deprecated and should be replaced by implementation or api

From the Gradle documentation:

dependencies {
    api 'commons-httpclient:commons-httpclient:3.1'
    implementation 'org.apache.commons:commons-lang3:3.5'
}

Dependencies appearing in the api configurations will be transitively exposed to consumers of the library, and as such will appear on the compile classpath of consumers.

Dependencies found in the implementation configuration will, on the other hand, not be exposed to consumers, and therefore not leak into the consumers' compile classpath. This comes with several benefits:

  • dependencies do not leak into the compile classpath of consumers anymore, so you will never accidentally depend on a transitive dependency
  • faster compilation thanks to reduced classpath size
  • less recompilations when implementation dependencies change: consumers would not need to be recompiled
  • cleaner publishing: when used in conjunction with the new maven-publish plugin, Java libraries produce POM files that distinguish exactly between what is required to compile against the library and what is required to use the library at runtime (in other words, don't mix what is needed to compile the library itself and what is needed to compile against the library).

The compile configuration still exists, but should not be used as it will not offer the guarantees that the api and implementation configurations provide.


Note: if you are only using a library in your app module -the common case- you won't notice any difference.
you will only see the difference if you have a complex project with modules depending on each other, or you are creating a library.

Open a link in browser with java button?

try {
    Desktop.getDesktop().browse(new URL("http://www.google.com").toURI());
} catch (Exception e) {}

note: you have to include necessary imports from java.net

Python, remove all non-alphabet chars from string

It is advisable to use PyPi regex module if you plan to match specific Unicode property classes. This library has also proven to be more stable, especially handling large texts, and yields consistent results across various Python versions. All you need to do is to keep it up-to-date.

If you install it (using pip intall regex or pip3 install regex), you may use

import regex
print ( regex.sub(r'\P{L}+', '', 'ABCLac1-2!???3§4“5def”') )
// => ABCLac???def

to remove all chunks of 1 or more characters other than Unicode letters from text. See an online Python demo. You may also use "".join(regex.findall(r'\p{L}+', 'ABCLac1-2!???3§4“5def”')) to get the same result.

In Python re, in order to match any Unicode letter, one may use the [^\W\d_] construct (Match any unicode letter?).

So, to remove all non-letter characters, you may either match all letters and join the results:

result = "".join(re.findall(r'[^\W\d_]', text))

Or, remove all chars other than those matched with [^\W\d_]:

result = re.sub(r'([^\W\d_])|.', r'\1', text, re.DOTALL)

See the regex demo online. However, you may get inconsistent results across various Python versions because the Unicode standard is evolving, and the set of chars matched with \w will depend on the Python version. Using PyPi regex library is highly recommended to get consistent results.

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

Those seem to be MySQL data types.

According to the documentation they take:

  1. tinyint = 1 byte
  2. smallint = 2 bytes
  3. mediumint = 3 bytes
  4. int = 4 bytes
  5. bigint = 8 bytes

And, naturally, accept increasingly larger ranges of numbers.

Auto-fit TextView for Android

Convert the text view to an image, and the scale the image within the boundaries.

Here's an example on how to convert a view to an Image: Converting a view to Bitmap without displaying it in Android?

The problem is, your text will not be selectable, but it should do the trick. I haven't tried it, so I'm not sure how it would look (because of the scaling).

Verifying that a string contains only letters in C#

You can loop on the chars of string and check using the Char Method IsLetter but you can also do a trick using String method IndexOfAny to search other charaters that are not suppose to be in the string.

Use Robocopy to copy only changed files?

Looks like /e option is what you need, it'll skip same files/directories.

robocopy c:\data c:\backup /e

If you run the command twice, you'll see the second round is much faster since it skips a lot of things.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Can I do it dynamically?

Create view class:

public class View {
    static class Public { }
    static class ExtendedPublic extends Public { }
    static class Internal extends ExtendedPublic { }
}

Annotate you model

@Document
public class User {

    @Id
    @JsonView(View.Public.class)
    private String id;

    @JsonView(View.Internal.class)
    private String email;

    @JsonView(View.Public.class)
    private String name;

    @JsonView(View.Public.class)
    private Instant createdAt = Instant.now();
    // getters/setters
}

Specify the view class in your controller

@RequestMapping("/user/{email}")
public class UserController {

    private final UserRepository userRepository;

    @Autowired
    UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    @JsonView(View.Internal.class)
    public @ResponseBody Optional<User> get(@PathVariable String email) {
        return userRepository.findByEmail(email);
    }

}

Data example:

{"id":"5aa2496df863482dc4da2067","name":"test","createdAt":"2018-03-10T09:35:31.050353800Z"}

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

How to Specify "Vary: Accept-Encoding" header in .htaccess

This was driving me crazy, but it seems that aularon's edit was missing the colon after "Vary". So changing "Vary Accept-Encoding" to "Vary: Accept-Encoding" fixed the issue for me.

I would have commented below the post, but it doesn't seem like it will let me.

Anyhow, I hope this saves someone the same trouble I was having.

Check if value exists in enum in TypeScript

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

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

becomes:

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

So you just need to do:

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

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

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

Or you can just do an any cast:

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

Resetting a form in Angular 2 after submit

form: NgForm;

form.reset()

This didn't work for me. It cleared the values but the controls raised an error.

But what worked for me was creating a hidden reset button and clicking the button when we want to clear the form.

<button class="d-none" type="reset" #btnReset>Reset</button>

And on the component, define the ViewChild and reference it in code.

@ViewChild('btnReset') btnReset: ElementRef<HTMLElement>;

Use this to reset the form.

this.btnReset.nativeElement.click();

Notice that the class d-none sets display: none; on the button.

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

Is there a replacement for unistd.h for Windows (Visual C)?

Since we can't find a version on the Internet, let's start one here.
Most ports to Windows probably only need a subset of the complete Unix file.
Here's a starting point. Please add definitions as needed.

#ifndef _UNISTD_H
#define _UNISTD_H    1

/* This is intended as a drop-in replacement for unistd.h on Windows.
 * Please add functionality as neeeded.
 * https://stackoverflow.com/a/826027/1202830
 */

#include <stdlib.h>
#include <io.h>
#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */

#define srandom srand
#define random rand

/* Values for the second argument to access.
   These may be OR'd together.  */
#define R_OK    4       /* Test for read permission.  */
#define W_OK    2       /* Test for write permission.  */
//#define   X_OK    1       /* execute permission - unsupported in windows*/
#define F_OK    0       /* Test for existence.  */

#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */

#ifdef _WIN64
#define ssize_t __int64
#else
#define ssize_t long
#endif

#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8            int8_t;
typedef __int16           int16_t; 
typedef __int32           int32_t;
typedef __int64           int64_t;
typedef unsigned __int8   uint8_t;
typedef unsigned __int16  uint16_t;
typedef unsigned __int32  uint32_t;
typedef unsigned __int64  uint64_t;

#endif /* unistd.h  */

How to ignore a particular directory or file for tslint?

Starting from tslint v5.8.0 you can set an exclude property under your linterOptions key in your tslint.json file:

{
  "extends": "tslint:latest",
  "linterOptions": {
      "exclude": [
          "bin",
          "**/__test__",
          "lib/*generated.js"
      ]
  }
}

More information on this here.

How do I add a simple jQuery script to WordPress?

You can use WordPress predefined function to add script file to WordPress plugin.

wp_enqueue_script( 'script', plugins_url('js/demo_script.js', __FILE__), array('jquery'));

Look at the post which helps you to understand that how easily you can implement jQuery and CSS in WordPress plugin.

Referencing a string in a string array resource with xml

Unfortunately:

  • It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.

  • It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.

What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.

Here's the code I was hoping would complete this task:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());  
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(),   android.R.layout.simple_list_item_1);  
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);  


for (int i = 0; i < 16; i++) {  
    if (prefs.getBoolean("itemKey[i]", true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
} 

What I did:

  • I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.

  • To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.

Here's the new code:

for (int i = 0; i < 16; i++) {  
        if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
}

Angular Material: mat-select not selecting default

A comparison between a number and a string use to be false, so, cast you selected value to a string within ngOnInit and it will work.

I had same issue, I filled the mat-select with an enum, using

Object.keys(MyAwesomeEnum).filter(k => !isNaN(Number(k)));

and I had the enum value I wanted to select...

I spent few hours struggling my mind trying to identify why it wasn't working. And I did it just after rendering all the variables being used in the mat-select, the keys collection and the selected... if you have ["0","1","2"] and you want to select 1 (which is a number) 1=="1" is false and because of that nothing is selected.

so, the solution is to cast you selected value to a string within ngOnInit and it will work.

How do I pass a value from a child back to the parent form?

Many ways to skin the cat here and @Mitch's suggestion is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child.

MySQL order by before group by

Just use the max function and group function

    select max(taskhistory.id) as id from taskhistory
            group by taskhistory.taskid
            order by taskhistory.datum desc

Best C++ IDE or Editor for Windows

I've tried SlickEdit, Notepad++, emacs, jEdit and Visual Studio. VS wins hands-down for Best Windows IDE.

jEdit is probably the best GUI cross-platform editor/almost-IDE, and emacs is probably the best terminal cross-platform editor/almost-IDE. The advantage with using these is that when you jump to a Mac or Linux box, you know how they work.

I tried Eclipse, but it ran like a no-legged dog it was so slow, so I didn't use it much. Maybe tech is better now, but eh.

How can I plot with 2 different y-axes?

Another alternative which is similar to the accepted answer by @BenBolker is redefining the coordinates of the existing plot when adding a second set of points.

Here is a minimal example.

Data:

x  <- 1:10
y1 <- rnorm(10, 100, 20)
y2 <- rnorm(10, 1, 1)

Plot:

par(mar=c(5,5,5,5)+0.1, las=1)

plot.new()
plot.window(xlim=range(x), ylim=range(y1))
points(x, y1, col="red", pch=19)
axis(1)
axis(2, col.axis="red")
box()

plot.window(xlim=range(x), ylim=range(y2))
points(x, y2, col="limegreen", pch=19)
axis(4, col.axis="limegreen")

example

jsPDF multi page PDF with HTML renderer

 var doc = new jsPDF('p', 'mm');

 var imgData = canvas.toDataURL('image/png');
 var pageHeight= doc.internal.pageSize.getHeight();
 var pageWidth= doc.internal.pageSize.getWidth();

 var imgheight = $('divName').height() * 25.4 / 96; //px to mm
 var pagecount = Math.ceil(imgheight / pageHeight);

 /* add initial page */
 doc.addPage('l','mm','a4');
 doc.addImage(imgData, 'PNG', 2, 0, pageWidth-4, 0);

 /* add extra pages if the div size is larger than a a4 size */
 if (pagecount > 0) {
     var j = 1;
     while (j != pagecount) {
         doc.addPage('l','mm','a4');
         doc.addImage(imgData, 'PNG', 2, -(j * pageHeight), pageWidth-4, 0);
         j++;
     }
 }

Command CompileSwift failed with a nonzero exit code in Xcode 10

ERROR = Command CompileSwiftSources failed with a nonzero exit code

In my case When I found this error, I got cramped with compilation. But when I see some related problem answers. I found a duplication file on my project. Where the same viewController was there as a class file. So yeah when I realized it I changed it name to new one. And yeah things changed!!!

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

I will just give the analogy with which I understand memory consistency models (or memory models, for short). It is inspired by Leslie Lamport's seminal paper "Time, Clocks, and the Ordering of Events in a Distributed System". The analogy is apt and has fundamental significance, but may be overkill for many people. However, I hope it provides a mental image (a pictorial representation) that facilitates reasoning about memory consistency models.

Let’s view the histories of all memory locations in a space-time diagram in which the horizontal axis represents the address space (i.e., each memory location is represented by a point on that axis) and the vertical axis represents time (we will see that, in general, there is not a universal notion of time). The history of values held by each memory location is, therefore, represented by a vertical column at that memory address. Each value change is due to one of the threads writing a new value to that location. By a memory image, we will mean the aggregate/combination of values of all memory locations observable at a particular time by a particular thread.

Quoting from "A Primer on Memory Consistency and Cache Coherence"

The intuitive (and most restrictive) memory model is sequential consistency (SC) in which a multithreaded execution should look like an interleaving of the sequential executions of each constituent thread, as if the threads were time-multiplexed on a single-core processor.

That global memory order can vary from one run of the program to another and may not be known beforehand. The characteristic feature of SC is the set of horizontal slices in the address-space-time diagram representing planes of simultaneity (i.e., memory images). On a given plane, all of its events (or memory values) are simultaneous. There is a notion of Absolute Time, in which all threads agree on which memory values are simultaneous. In SC, at every time instant, there is only one memory image shared by all threads. That's, at every instant of time, all processors agree on the memory image (i.e., the aggregate content of memory). Not only does this imply that all threads view the same sequence of values for all memory locations, but also that all processors observe the same combinations of values of all variables. This is the same as saying all memory operations (on all memory locations) are observed in the same total order by all threads.

In relaxed memory models, each thread will slice up address-space-time in its own way, the only restriction being that slices of each thread shall not cross each other because all threads must agree on the history of every individual memory location (of course, slices of different threads may, and will, cross each other). There is no universal way to slice it up (no privileged foliation of address-space-time). Slices do not have to be planar (or linear). They can be curved and this is what can make a thread read values written by another thread out of the order they were written in. Histories of different memory locations may slide (or get stretched) arbitrarily relative to each other when viewed by any particular thread. Each thread will have a different sense of which events (or, equivalently, memory values) are simultaneous. The set of events (or memory values) that are simultaneous to one thread are not simultaneous to another. Thus, in a relaxed memory model, all threads still observe the same history (i.e., sequence of values) for each memory location. But they may observe different memory images (i.e., combinations of values of all memory locations). Even if two different memory locations are written by the same thread in sequence, the two newly written values may be observed in different order by other threads.

[Picture from Wikipedia] Picture from Wikipedia

Readers familiar with Einstein’s Special Theory of Relativity will notice what I am alluding to. Translating Minkowski’s words into the memory models realm: address space and time are shadows of address-space-time. In this case, each observer (i.e., thread) will project shadows of events (i.e., memory stores/loads) onto his own world-line (i.e., his time axis) and his own plane of simultaneity (his address-space axis). Threads in the C++11 memory model correspond to observers that are moving relative to each other in special relativity. Sequential consistency corresponds to the Galilean space-time (i.e., all observers agree on one absolute order of events and a global sense of simultaneity).

The resemblance between memory models and special relativity stems from the fact that both define a partially-ordered set of events, often called a causal set. Some events (i.e., memory stores) can affect (but not be affected by) other events. A C++11 thread (or observer in physics) is no more than a chain (i.e., a totally ordered set) of events (e.g., memory loads and stores to possibly different addresses).

In relativity, some order is restored to the seemingly chaotic picture of partially ordered events, since the only temporal ordering that all observers agree on is the ordering among “timelike” events (i.e., those events that are in principle connectible by any particle going slower than the speed of light in a vacuum). Only the timelike related events are invariantly ordered. Time in Physics, Craig Callender.

In C++11 memory model, a similar mechanism (the acquire-release consistency model) is used to establish these local causality relations.

To provide a definition of memory consistency and a motivation for abandoning SC, I will quote from "A Primer on Memory Consistency and Cache Coherence"

For a shared memory machine, the memory consistency model defines the architecturally visible behavior of its memory system. The correctness criterion for a single processor core partitions behavior between “one correct result” and “many incorrect alternatives”. This is because the processor’s architecture mandates that the execution of a thread transforms a given input state into a single well-defined output state, even on an out-of-order core. Shared memory consistency models, however, concern the loads and stores of multiple threads and usually allow many correct executions while disallowing many (more) incorrect ones. The possibility of multiple correct executions is due to the ISA allowing multiple threads to execute concurrently, often with many possible legal interleavings of instructions from different threads.

Relaxed or weak memory consistency models are motivated by the fact that most memory orderings in strong models are unnecessary. If a thread updates ten data items and then a synchronization flag, programmers usually do not care if the data items are updated in order with respect to each other but only that all data items are updated before the flag is updated (usually implemented using FENCE instructions). Relaxed models seek to capture this increased ordering flexibility and preserve only the orders that programmers “require” to get both higher performance and correctness of SC. For example, in certain architectures, FIFO write buffers are used by each core to hold the results of committed (retired) stores before writing the results to the caches. This optimization enhances performance but violates SC. The write buffer hides the latency of servicing a store miss. Because stores are common, being able to avoid stalling on most of them is an important benefit. For a single-core processor, a write buffer can be made architecturally invisible by ensuring that a load to address A returns the value of the most recent store to A even if one or more stores to A are in the write buffer. This is typically done by either bypassing the value of the most recent store to A to the load from A, where “most recent” is determined by program order, or by stalling a load of A if a store to A is in the write buffer. When multiple cores are used, each will have its own bypassing write buffer. Without write buffers, the hardware is SC, but with write buffers, it is not, making write buffers architecturally visible in a multicore processor.

Store-store reordering may happen if a core has a non-FIFO write buffer that lets stores depart in a different order than the order in which they entered. This might occur if the first store misses in the cache while the second hits or if the second store can coalesce with an earlier store (i.e., before the first store). Load-load reordering may also happen on dynamically-scheduled cores that execute instructions out of program order. That can behave the same as reordering stores on another core (Can you come up with an example interleaving between two threads?). Reordering an earlier load with a later store (a load-store reordering) can cause many incorrect behaviors, such as loading a value after releasing the lock that protects it (if the store is the unlock operation). Note that store-load reorderings may also arise due to local bypassing in the commonly implemented FIFO write buffer, even with a core that executes all instructions in program order.

Because cache coherence and memory consistency are sometimes confused, it is instructive to also have this quote:

Unlike consistency, cache coherence is neither visible to software nor required. Coherence seeks to make the caches of a shared-memory system as functionally invisible as the caches in a single-core system. Correct coherence ensures that a programmer cannot determine whether and where a system has caches by analyzing the results of loads and stores. This is because correct coherence ensures that the caches never enable new or different functional behavior (programmers may still be able to infer likely cache structure using timing information). The main purpose of cache coherence protocols is maintaining the single-writer-multiple-readers (SWMR) invariant for every memory location. An important distinction between coherence and consistency is that coherence is specified on a per-memory location basis, whereas consistency is specified with respect to all memory locations.

Continuing with our mental picture, the SWMR invariant corresponds to the physical requirement that there be at most one particle located at any one location but there can be an unlimited number of observers of any location.

font awesome icon in select option

You can simply add a FontAwesome icon to your select dropdown as text. You only need a few things in CSS only, the FontAwesome CSS and the unicode. For example &#xf26e;:

_x000D_
_x000D_
select {_x000D_
  font-family: 'FontAwesome', 'Second Font name'_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<select>_x000D_
  <option>Hi, &#xf042;</option>_x000D_
  <option>Hi, &#xf043;</option>_x000D_
  <option>Hi, &#xf044;</option>_x000D_
  <option>Hi, &#xf045;</option>_x000D_
  <option>Hi, &#xf046;</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Working fiddle

The unicodes can be found when you click on an icon: Fontawesome

According to the comment below and issue on Github, the unicode in select elements won't work on OSX (yet).


Update: from the Github issue, adding multiple attribute to select element makes it work on:

OSX El Capitan 10.11.4

  • Chrome version 50.0.2661.75 (64-bit)
  • Sarafi version 9.1
  • Firefox version 45.0.2

_x000D_
_x000D_
select{_x000D_
  font-family: FontAwesome, sans-serif;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<select multiple>_x000D_
  <option>&#xf26e 500px</option>_x000D_
  <option>&#xf042 Adjust</option>_x000D_
  <option>&#xf170 Adn</option>_x000D_
  <option>&#xf037 Align-center</option>_x000D_
  <option>&#xf039 Align-justify</option>_x000D_
  <option>&#xf036 Align-left</option>_x000D_
  <option>&#xf038 Align-right</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

JSFiddle

Bind event to right mouse click

Just use the event-handler. Something like this should work:

$('.js-my-element').bind('contextmenu', function(e) {
     e.preventDefault();
     alert('The eventhandler will make sure, that the contextmenu dosn&#39;t appear.');
});

What is the difference between :focus and :active?

There are four cases.

  1. By default, active and focus are both off.
  2. When you tab to cycle through focusable elements, they will enter :focus (without active).
  3. When you click on a non-focusable element, it enters :active (without focus).
  4. When you click on a focusable element it enters :active:focus (active and focus simultaneously).

Example:

<div>
  I cannot be focused.
</div>

<div tabindex="0">
  I am focusable.
</div>

div:focus {
  background: green;
}

div:active {
  color: orange;
}

div:focus:active {
  font-weight: bold;
}

When the page loads both are in case 1. When you press tab you will focus the second div and see it exhibit case 2. When you click on the first div you see case 3. When you click the second div, you see case 4.


Whether an element is focusable or not is another question. Most are not by default. But, it's safe to assume <a>, <input>, <textarea> are focusable by default.

How can I get the assembly file version

Use this:

((AssemblyFileVersionAttribute)Attribute.GetCustomAttribute(
    Assembly.GetExecutingAssembly(), 
    typeof(AssemblyFileVersionAttribute), false)
).Version;

Or this:

new Version(System.Windows.Forms.Application.ProductVersion);

Cannot download Docker images behind a proxy

Your APT proxy settings are not related to Docker.

Docker uses the HTTP_PROXY environment variable, if present. For example:

sudo HTTP_PROXY=http://192.168.1.1:3128/ docker pull busybox

But instead, I suggest you have a look at your /etc/default/dockerconfiguration file: you should have a line to uncomment (and maybe adjust) to get your proxy settings applied automatically. Then restart the Docker server:

service docker restart

Creating a mock HttpServletRequest out of a url string?

You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.

In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.

Truncate (not round off) decimal numbers in javascript

The answer by @kirilloid seems to be the correct answer, however, the main code needs to be updated. His solution doesn't take care of negative numbers (which someone did mention in the comment section but has not been updated in the main code).

Updating that to a complete final tested solution:

Number.prototype.toFixedDown = function(digits) {
    var re = new RegExp("([-]*\\d+\\.\\d{" + digits + "})(\\d)"),
    m = this.toString().match(re);
    return m ? parseFloat(m[1]) : this.valueOf();
};

Sample Usage:

var x = 3.1415629;
Logger.log(x.toFixedDown(2)); //or use whatever you use to log

Fiddle: JS Number Round down

PS: Not enough repo to comment on that solution.

Most efficient way to concatenate strings?

From Chinh Do - StringBuilder is not always faster:

Rules of Thumb

  • When concatenating three dynamic string values or less, use traditional string concatenation.

  • When concatenating more than three dynamic string values, use StringBuilder.

  • When building a big string from several string literals, use either the @ string literal or the inline + operator.

Most of the time StringBuilder is your best bet, but there are cases as shown in that post that you should at least think about each situation.

Case statement with multiple values in each 'when' block

Another nice way to put your logic in data is something like this:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end

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

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

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

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

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

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

npm install typescript

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

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

How can I unstage my files again after making a local commit?

"Reset" is the way to undo changes locally. When committing, you first select changes to include with "git add"--that's called "staging." And once the changes are staged, then you "git commit" them.

To back out from either the staging or the commit, you "reset" the HEAD. On a branch, HEAD is a git variable that points to the most recent commit. So if you've staged but haven't committed, you "git reset HEAD." That backs up to the current HEAD by taking changes off the stage. It's shorthand for "git reset --mixed HEAD~0."

If you've already committed, then the HEAD has already advanced, so you need to back up to the previous commit. Here you "reset HEAD~1" or "reset HEAD^1" or "reset HEAD~" or "reset HEAD^"-- all reference HEAD minus one.

Which is the better symbol, ~ or ^? Think of the ~ tilde as a single stream -- when each commit has a single parent and it's just a series of changes in sequence, then you can reference back up the stream using the tilde, as HEAD~1, HEAD~2, HEAD~3, for parent, grandparent, great-grandparent, etc. (technically it's finding the first parent in earlier generations).

When there's a merge, then commits have more than one parent. That's when the ^ caret comes into play--you can remember because it shows the branches coming together. Using the caret, HEAD^1 would be the first parent and HEAD^2 would be the second parent of a single commit--mother and father, for example.

So if you're just going back one hop on a single-parent commit, then HEAD~ and HEAD^ are equivalent--you can use either one.

Also, the reset can be --soft, --mixed, or --hard. A soft reset just backs out the commit--it resets the HEAD, but it doesn't check out the files from the earlier commit, so all changes in the working directory are preserved. And --soft reset doesn't even clear the stage (also known as the index), so all the files that were staged will still be on stage.

A --mixed reset (the default) also does not check out the files from the earlier commit, so all changes are preserved, but the stage is cleared. That's why a simple "git reset HEAD" will clear off the stage.

A --hard reset resets the HEAD, and it clears the stage, but it also checks out all the files from the earlier commit and so it overwrites any changes.

If you've pushed the commit to a remote repository, then reset doesn't work so well. You can reset locally, but when you try to push to the remote, git will see that your local HEAD is behind the HEAD in the remote branch and will refuse to push. You may be able to force the push, but git really does not like doing that.

Alternatively, you can stash your changes if you want to keep them, check out the earlier commit, un-stash the changes, stage them, create a new commit, and then push that.

Running Python on Windows for Node.js dependencies

This helped: https://www.npmjs.com/package/node-gyp

I followed these steps:

npm install -g node-gyp

then:

npm install --global --production windows-build-tools

Android - get children inside a View?

I'm just going to provide this answer as an alternative @IHeartAndroid's recursive algorithm for discovering all child Views in a view hierarchy. Note that at the time of this writing, the recursive solution is flawed in that it will contains duplicates in its result.

For those who have trouble wrapping their head around recursion, here's a non-recursive alternative. You get bonus points for realizing this is also a breadth-first search alternative to the depth-first approach of the recursive solution.

private List<View> getAllChildrenBFS(View v) {
    List<View> visited = new ArrayList<View>();
    List<View> unvisited = new ArrayList<View>();
    unvisited.add(v);

    while (!unvisited.isEmpty()) {
        View child = unvisited.remove(0);
        visited.add(child);
        if (!(child instanceof ViewGroup)) continue;
        ViewGroup group = (ViewGroup) child;
        final int childCount = group.getChildCount();
        for (int i=0; i<childCount; i++) unvisited.add(group.getChildAt(i));
    }

    return visited;
}

A couple of quick tests (nothing formal) suggest this alternative is also faster, although that has most likely to do with the number of new ArrayList instances the other answer creates. Also, results may vary based on how vertical/horizontal the view hierarchy is.

Cross-posted from: Android | Get all children elements of a ViewGroup

nodejs - first argument must be a string or Buffer - when using response.write with http.request

response.statusCode is a number, e.g. response.statusCode === 200, not '200'. As the error message says, write expects a string or Buffer object, so you must convert it.

res.write(response.statusCode.toString());

You are also correct about your callback comment though. res.end(); should be inside the callback, just below your write calls.

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

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

Hashing with SHA1 Algorithm in C#

You can "compute the value for the specified byte array" using ComputeHash:

var hash = sha1.ComputeHash(temp);

If you want to analyse the result in string representation, then you will need to format the bytes using the {0:X2} format specifier.

Change URL parameters

This is the modern way to change URL parameters:

function setGetParam(key,value) {
  if (history.pushState) {
    var params = new URLSearchParams(window.location.search);
    params.set(key, value);
    var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.toString();
    window.history.pushState({path:newUrl},'',newUrl);
  }
}

How to get just the parent directory name of a specific file

    //get the parentfolder name
    File file = new File( System.getProperty("user.dir") + "/.");
    String parentPath = file.getParentFile().getName();

How to get first object out from List<Object> using Linq

You can do

Component depCountry = lstComp
                       .Select(x => x.ComponentValue("Dep"))
                       .FirstOrDefault();

Alternatively if you are wanting this for the entire dictionary of values, you can even tie it back to the key

var newDictionary = dic.Select(x => new 
            {
               Key = x.Key,
               Value = x.Value.Select( y => 
                      {
                          depCountry = y.ComponentValue("Dep")
                      }).FirstOrDefault()
             }
             .Where(x => x.Value != null)
             .ToDictionary(x => x.Key, x => x.Value());

This will give you a new dictionary. You can access the values

var myTest = newDictionary[key1].depCountry     

Convert string to datetime

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put the line $this->db->order_by("course_name","desc"); at top of your query. Like

$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();

Fit Image in ImageButton in Android

I'm using the following code in xml

android:adjustViewBounds="true"
android:scaleType="centerInside"

Bitwise and in place of modulus operator

This is specifically a special case because computers represent numbers in base 2. This is generalizable:

(number)base % basex

is equivilent to the last x digits of (number)base.

How to get input text value from inside td

Maybe this will help.

var inputVal = $(this).closest('tr').find("td:eq(x) input").val();

Writing a dictionary to a text file?

import json

with open('tokenler.json', 'w') as file:
     file.write(json.dumps(mydict, ensure_ascii=False))

ASP.NET MVC - Getting QueryString values

Query string parameters can be accepted simply by using an argument on the action - i.e.

public ActionResult Foo(string someValue, int someOtherValue) {...}

which will accept a query like .../someroute?someValue=abc&someOtherValue=123

Other than that, you can look at the request directly for more control.

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

C# - Insert a variable number of spaces into a string? (Formatting an output file)

I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:

string.Empty.PadRight(totalLength, (char)32);

An alternative approach: Create all spaces manually within a custom method and call it:

private static string GetSpaces(int totalLength)
    {
        string result = string.Empty;
        for (int i = 0; i < totalLength; i++)
        {
            result += " ";
        }
        return result;
    }

And call it in your code to create white spaces: GetSpaces(14);

Maven 3 warnings about build.plugins.plugin.version

I'm using a parent pom for my projects and wanted to specify the versions in one place, so I used properties to specify the version:

parent pom:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ....
    <properties>
        <maven-compiler-plugin-version>2.3.2</maven-compiler-plugin-version>
    </properties>
    ....
</project>

project pom:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ....
    <build>
        <finalName>helloworld</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin-version}</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

See also: https://www.allthingsdigital.nl/2011/04/10/maven-3-and-the-versions-dilemma/

base_url() function not working in codeigniter

In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):

$autoload['helper'] = array('url');

Or, manually:

$this->load->helper('url');

Once it's loaded, be sure to keep in mind that base_url() doesn't implicitly print or echo out anything, rather it returns the value to be printed:

echo base_url();

Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:

If this (base_url) is not set then CodeIgniter will guess the protocol, domain and path to your installation.

application/config/config.php, line 13

How to get current SIM card number in Android?

Getting the Phone Number, IMEI, and SIM Card ID

TelephonyManager tm = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);        

For SIM card, use the getSimSerialNumber()

    //---get the SIM card ID---
    String simID = tm.getSimSerialNumber();
    if (simID != null)
        Toast.makeText(this, "SIM card ID: " + simID, 
        Toast.LENGTH_LONG).show();

Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)

    //---get the phone number---
    String telNumber = tm.getLine1Number();
    if (telNumber != null)        
        Toast.makeText(this, "Phone number: " + telNumber, 
        Toast.LENGTH_LONG).show();

IMEI number of the phone, use the getDeviceId()

    //---get the IMEI number---
    String IMEI = tm.getDeviceId();
    if (IMEI != null)        
        Toast.makeText(this, "IMEI number: " + IMEI, 
        Toast.LENGTH_LONG).show();

Permissions needed

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

Get element from within an iFrame

You can use this function to query for any element on the page, regardless of if it is nested inside of an iframe (or many iframes):

function querySelectorAllInIframes(selector) {
  let elements = [];

  const recurse = (contentWindow = window) => {

    const iframes = contentWindow.document.body.querySelectorAll('iframe');
    iframes.forEach(iframe => recurse(iframe.contentWindow));
    
    elements = elements.concat(contentWindow.document.body.querySelectorAll(selector));
  }

  recurse();

  return elements;
};

querySelectorAllInIframes('#elementToBeFound');

Note: Keep in mind that each of the iframes on the page will need to be of the same-origin, or this function will throw an error.

Opening new window in HTML for target="_blank"

You don't have that kind of control with a bare a tag. But you can hook up the tag's onclick handler to call window.open(...) with the right parameters. See here for examples: https://developer.mozilla.org/En/DOM/Window.open

I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.

Count Rows in Doctrine QueryBuilder

You can also get the number of data by using the count function.

$query = $this->dm->createQueryBuilder('AppBundle:Items')
                    ->field('isDeleted')->equals(false)
                    ->getQuery()->count();

Maven: mvn command not found

I think the tutorial passed by @emdhie will help a lot. How install maven

But, i followed and still getting mvn: command not found

I found this solution to know what was wrong in my configuration:

I opened the command line and called this command:

../apache-maven-3.5.3/bin/mvn --version

After that i got the correct JAVA_HOME and saw that my JAVA_HOME was wrong.

Hope this helps.

Git push error: "origin does not appear to be a git repository"

I'll still share my short answer humbly, knowing that I'm super late to answer this question.

Here's, a simple and clean explanation that solved my issue

Also, since I was using the SSH key I used the following command:

for instance it would look like:

If you are using the HTTPS URL, refer to the answer provided by @sunny-jim above.

Do correct me if I'm wrong. Thanks.

pip install access denied on Windows

In case of windows, in cmd try to run pip install using python executable

e.g.

python -m pip install mitmproxy

this should work, at least it worked for me for other package installation.

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

Difference between <input type='submit' /> and <button type='submit'>text</button>

With <button>, you can use img tags, etc. where text is

<button type='submit'> text -- can be img etc.  </button>

with <input> type, you are limited to text

How do I catch a numpy warning like it's an exception (not just for testing)?

It seems that your configuration is using the print option for numpy.seterr:

>>> import numpy as np
>>> np.array([1])/0   #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0   #'print' mode
Warning: divide by zero encountered in divide
array([0])

This means that the warning you see is not a real warning, but it's just some characters printed to stdout(see the documentation for seterr). If you want to catch it you can:

  1. Use numpy.seterr(all='raise') which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.
  2. Use numpy.seterr(all='warn'), which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.

Once you actually have a warning, you can use the warnings module to control how the warnings should be treated:

>>> import warnings
>>> 
>>> warnings.filterwarnings('error')
>>> 
>>> try:
...     warnings.warn(Warning())
... except Warning:
...     print 'Warning was raised as an exception!'
... 
Warning was raised as an exception!

Read carefully the documentation for filterwarnings since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings which is a context manager which automatically resets the original filterwarnings function:

>>> import warnings
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('error')
...     try:
...         warnings.warn(Warning())
...     except Warning: print 'Raised!'
... 
Raised!
>>> try:
...     warnings.warn(Warning())
... except Warning: print 'Not raised!'
... 
__main__:2: Warning: 

How to change or add theme to Android Studio?

For additional themes I visited https://plugins.jetbrains.com/search?headline=164-theme&tags=Theme I was able to download one of them. I closed all my tabs opened and simply dragged and dropped the jar file. That was the way Android Studio prompted to restart. I tried importing the jar file as mentioned previously but it simply didn't work.

How to print a groupby object

In python 3

k = None
for name_of_the_group, group in dict(df_group):
    if(k != name_of_the_group):
        print ('\n', name_of_the_group)
        print('..........','\n')
    print (group)
    k = name_of_the_group

In more interactive way

Opposite of append in jquery

Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.

extra qualification error in C++

This is because you have the following code:

class JSONDeserializer
{
    Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString);
};

This is not valid C++ but Visual Studio seems to accept it. You need to change it to the following code to be able to compile it with a standard compliant compiler (gcc is more compliant to the standard on this point).

class JSONDeserializer
{
    Value ParseValue(TDR type, const json_string& valueString);
};

The error come from the fact that JSONDeserializer::ParseValue is a qualified name (a name with a namespace qualification), and such a name is forbidden as a method name in a class.

MySQL InnoDB not releasing disk space after deleting data rows from table

MySQL doesn't reduce the size of ibdata1. Ever. Even if you use optimize table to free the space used from deleted records, it will reuse it later.

An alternative is to configure the server to use innodb_file_per_table, but this will require a backup, drop database and restore. The positive side is that the .ibd file for the table is reduced after an optimize table.

'console' is undefined error for Internet Explorer

For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:

  • If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)

    window.console = { debug : function() {}, ...};

  • Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !

    window.console = { debug : window.console.log, ...};

Not sure about the assert support in various IE versions, but any suggestions are welcome. Also posted this answer here: How can I use console logging in Internet Explorer?

How do I get the currently-logged username from a Windows service in .NET?

Completing the answer from @xanblax

private static string getUserName()
    {
        SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
        {
            foreach (System.Management.ManagementObject Process in searcher.Get())
            {
                if (Process["ExecutablePath"] != null &&
                    string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
                {
                    string[] OwnerInfo = new string[2];
                    Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

                    return OwnerInfo[0];
                }
            }
        }
        return "";
    }

How to move the layout up when the soft keyboard is shown android

Try this in the android manifest file corresponding to the activity.

<activity android:windowSoftInputMode="adjustPan"> </activity>

Why do people hate SQL cursors so much?

Cursors tend to be used by beginning SQL developers in places where set-based operations would be better. Particularly when people learn SQL after learning a traditional programming language, the "iterate over these records" mentality tends to lead people to use cursors inappropriately.

Most serious SQL books include a chapter enjoining the use of cursors; well-written ones make it clear that cursors have their place but shouldn't be used for set-based operations.

There are obviously situations where cursors are the correct choice, or at least A correct choice.

How to change the Push and Pop animations in a navigation based app

@Magnus answer, only then for Swift (2.0)

    let transition = CATransition()
    transition.duration = 0.5
    transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    transition.type = kCATransitionPush
    transition.subtype = kCATransitionFromTop
    self.navigationController!.view.layer.addAnimation(transition, forKey: nil)
    let writeView : WriteViewController = self.storyboard?.instantiateViewControllerWithIdentifier("WriteView") as! WriteViewController
    self.navigationController?.pushViewController(writeView, animated: false)

Some sidenotes:

You can do this as well with Segue, just implement this in prepareForSegue or shouldPerformSegueWithIdentifier. However, this will keep the default animation in it as well. To fix this you have to go to the storyboard, click the Segue, and uncheck the box 'Animates'. But this will limit your app for IOS 9.0 and above (atleast when I did it in Xcode 7).

When doing in a segue, the last two lines should be replaced with:

self.navigationController?.popViewControllerAnimated(false)

Even though I set false, it kind of ignores it.

How can I add new keys to a dictionary?

your_dict = {}

To add new key:

  1. your_dict[key]=value

  2. your_dict.update(key=value)

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

Java: Static Class?

  • Final class and private constructor (good but not essential)
  • Public static methods

Error: 'int' object is not subscriptable - Python

'int' object is not subscriptable is TypeError in Python. To better understand how this error occurs, let us consider the following example:

list1 = [1, 2, 3]
print(list1[0][0])

If we run the code, you will receive the same TypeError in Python3.

TypeError: 'int' object is not subscriptable

Here the index of the list is out of range. If the code was modified to:

print(list1[0])

The output will be 1(as indexing in Python Lists starts at zero), as now the index of the list is in range.

1

When the code(given alongside the question) is run, the TypeError occurs and it points to line 4 of the code :

int([x[age1]])

The intention may have been to create a list of an integer number(although creating a list for a single number was not at all required). What was required was that to just assign the input(which in turn converted to integer) to a variable.

Hence, it's better to code this way:

name = input("What's your name? ")
age = int(input('How old are you? '))
twenty_one = 21 - age
if(twenty_one < 0):
    print('Hi {0}, you are above 21 years' .format(name))
elif(twenty_one == 0):
    print('Hi {0}, you are 21 years old' .format(name))
else:
    print('Hi {0}, you will be 21 years in {1} year(s)' .format(name, twenty_one))

The output:

What's your name? Steve
How old are you? 21
Hi Steve, you are 21 years old

calling another method from the main method in java

You can do it multiple ways. Here are two. Cheers!

package learningjava;

public class helloworld {
    public static void main(String[] args) {
        new helloworld().go();
        // OR
        helloworld.get();
    }

    public void go(){
        System.out.println("Hello World");
    }
    public static void get(){
        System.out.println("Hello World, Again");
    }
}

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

unable to start mongodb local server

To resolve the issue in Windows, the below steps work for me:

For example mongoDB version 3.6 is installed, and the install path of MongoDB is "D:\Program Files\MongoDB".

Create folder D:\mongodb\logs, then create file mongodb.log inside this folder.

Run cmd.exe as administrator,

D:\Program Files\MongoDB\Server\3.6\bin>taskkill /F /IM mongod.exe
D:\Program Files\MongoDB\Server\3.6\bin>mongod.exe --logpath D:\mongodb\logs\mongodb.log --logappend --dbpath D:\mongodb\data --directoryperdb --serviceName MongoDB --remove
D:\Program Files\MongoDB\Server\3.6\bin>mongod --logpath "D:\mongodb\logs\mongodb.log" --logappend --dbpath "D:\mongodb\data" --directoryperdb --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install

Remove these two files mongod.lock and storage.bson under the folder "D:\mongodb\data".

Then type net start MongoDB in the cmd using administrator privilege, the issue will be solved.

How to download and save an image in Android

Edit as of 30.12.2015 - The Ultimate Guide to image downloading


last major update: Mar 31 2016


TL;DR a.k.a. stop talking, just give me the code!!

Skip to the bottom of this post, copy the BasicImageDownloader (javadoc version here) into your project, implement the OnImageLoaderListener interface and you're done.

Note: though the BasicImageDownloader handles possible errors and will prevent your app from crashing in case anything goes wrong, it will not perform any post-processing (e.g. downsizing) on the downloaded Bitmaps.


Since this post has received quite a lot of attention, I have decided to completely rework it to prevent the folks from using deprecated technologies, bad programming practices or just doing silly things - like looking for "hacks" to run network on the main thread or accept all SSL certs.

I've created a demo project named "Image Downloader" that demonstrates how to download (and save) an image using my own downloader implementation, the Android's built-in DownloadManager as well as some popular open-source libraries. You can view the complete source code or download the project on GitHub.

Note: I have not adjusted the permission management for SDK 23+ (Marshmallow) yet, thus the project is targeting SDK 22 (Lollipop).

In my conclusion at the end of this post I will share my humble opinion about the proper use-case for each particular way of image downloading I've mentioned.

Let's start with an own implementation (you can find the code at the end of the post). First of all, this is a BasicImageDownloader and that's it. All it does is connecting to the given url, reading the data and trying to decode it as a Bitmap, triggering the OnImageLoaderListener interface callbacks when appropriate. The advantage of this approach - it is simple and you have a clear overview of what's going on. A good way to go if all you need is downloading/displaying and saving some images, whilst you don't care about maintaining a memory/disk cache.

Note: in case of large images, you might need to scale them down.

--

Android DownloadManager is a way to let the system handle the download for you. It's actually capable of downloading any kind of files, not just images. You may let your download happen silently and invisible to the user, or you can enable the user to see the download in the notification area. You can also register a BroadcastReceiver to get notified after you download is complete. The setup is pretty much straightforward, refer to the linked project for sample code.

Using the DownloadManager is generally not a good idea if you also want to display the image, since you'd need to read and decode the saved file instead of just setting the downloaded Bitmap into an ImageView. The DownloadManager also does not provide any API for you app to track the download progress.

--

Now the introduction of the great stuff - the libraries. They can do much more than just downloading and displaying images, including: creating and managing the memory/disk cache, resizing images, transforming them and more.

I will start with Volley, a powerful library created by Google and covered by the official documentation. While being a general-purpose networking library not specializing on images, Volley features quite a powerful API for managing images.

You will need to implement a Singleton class for managing Volley requests and you are good to go.

You might want to replace your ImageView with Volley's NetworkImageView, so the download basically becomes a one-liner:

((NetworkImageView) findViewById(R.id.myNIV)).setImageUrl(url, MySingleton.getInstance(this).getImageLoader());

If you need more control, this is what it looks like to create an ImageRequest with Volley:

     ImageRequest imgRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
             @Override
             public void onResponse(Bitmap response) {
                    //do stuff
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.ARGB_8888, 
             new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
                   //do stuff
                }
            });

It is worth mentioning that Volley features an excellent error handling mechanism by providing the VolleyError class that helps you to determine the exact cause of an error. If your app does a lot of networking and managing images isn't its main purpose, then Volley it a perfect fit for you.

--

Square's Picasso is a well-known library which will do all of the image loading stuff for you. Just displaying an image using Picasso is as simple as:

 Picasso.with(myContext)
       .load(url)
       .into(myImageView); 

By default, Picasso manages the disk/memory cache so you don't need to worry about that. For more control you can implement the Target interface and use it to load your image into - this will provide callbacks similar to the Volley example. Check the demo project for examples.

Picasso also lets you apply transformations to the downloaded image and there are even other libraries around that extend those API. Also works very well in a RecyclerView/ListView/GridView.

--

Universal Image Loader is an another very popular library serving the purpose of image management. It uses its own ImageLoader that (once initialized) has a global instance which can be used to download images in a single line of code:

  ImageLoader.getInstance().displayImage(url, myImageView);

If you want to track the download progress or access the downloaded Bitmap:

 ImageLoader.getInstance().displayImage(url, myImageView, opts, 
 new ImageLoadingListener() {
     @Override
     public void onLoadingStarted(String imageUri, View view) {
                     //do stuff
                }

      @Override
      public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                   //do stuff
                }

      @Override
      public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                   //do stuff
                }

      @Override
      public void onLoadingCancelled(String imageUri, View view) {
                   //do stuff
                }
            }, new ImageLoadingProgressListener() {
      @Override
      public void onProgressUpdate(String imageUri, View view, int current, int total) {
                   //do stuff
                }
            });

The opts argument in this example is a DisplayImageOptions object. Refer to the demo project to learn more.

Similar to Volley, UIL provides the FailReason class that enables you to check what went wrong on download failure. By default, UIL maintains a memory/disk cache if you don't explicitly tell it not to do so.

Note: the author has mentioned that he is no longer maintaining the project as of Nov 27th, 2015. But since there are many contributors, we can hope that the Universal Image Loader will live on.

--

Facebook's Fresco is the newest and (IMO) the most advanced library that takes image management to a new level: from keeping Bitmaps off the java heap (prior to Lollipop) to supporting animated formats and progressive JPEG streaming.

To learn more about ideas and techniques behind Fresco, refer to this post.

The basic usage is quite simple. Note that you'll need to call Fresco.initialize(Context); only once, preferable in the Application class. Initializing Fresco more than once may lead to unpredictable behavior and OOM errors.

Fresco uses Drawees to display images, you can think of them as of ImageViews:

    <com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/drawee"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    fresco:fadeDuration="500"
    fresco:actualImageScaleType="centerCrop"
    fresco:placeholderImage="@drawable/placeholder_grey"
    fresco:failureImage="@drawable/error_orange"
    fresco:placeholderImageScaleType="fitCenter"
    fresco:failureImageScaleType="centerInside"
    fresco:retryImageScaleType="centerCrop"
    fresco:progressBarImageScaleType="centerInside"
    fresco:progressBarAutoRotateInterval="1000"
    fresco:roundAsCircle="false" />

As you can see, a lot of stuff (including transformation options) gets already defined in XML, so all you need to do to display an image is a one-liner:

 mDrawee.setImageURI(Uri.parse(url));

Fresco provides an extended customization API, which, under circumstances, can be quite complex and requires the user to read the docs carefully (yes, sometimes you need to RTFM).

I have included examples for progressive JPEG's and animated images into the sample project.


Conclusion - "I have learned about the great stuff, what should I use now?"

Note that the following text reflects my personal opinion and should not be taken as a postulate.

  • If you only need to download/save/display some images, don't plan to use them in a Recycler-/Grid-/ListView and don't need a whole bunch of images to be display-ready, the BasicImageDownloader should fit your needs.
  • If your app saves images (or other files) as a result of a user or an automated action and you don't need the images to be displayed often, use the Android DownloadManager.
  • In case your app does a lot of networking, transmits/receives JSON data, works with images, but those are not the main purpose of the app, go with Volley.
  • Your app is image/media-focused, you'd like to apply some transformations to images and don't want to bother with complex API: use Picasso (Note: does not provide any API to track the intermediate download status) or Universal Image Loader
  • If your app is all about images, you need advanced features like displaying animated formats and you are ready to read the docs, go with Fresco.

In case you missed that, the Github link for the demo project.


And here's the BasicImageDownloader.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;

public class BasicImageDownloader {

    private OnImageLoaderListener mImageLoaderListener;
    private Set<String> mUrlsInProgress = new HashSet<>();
    private final String TAG = this.getClass().getSimpleName();

    public BasicImageDownloader(@NonNull OnImageLoaderListener listener) {
        this.mImageLoaderListener = listener;
    }

    public interface OnImageLoaderListener {
        void onError(ImageError error);      
        void onProgressChange(int percent);
        void onComplete(Bitmap result);
    }


    public void download(@NonNull final String imageUrl, final boolean displayProgress) {
        if (mUrlsInProgress.contains(imageUrl)) {
            Log.w(TAG, "a download for this url is already running, " +
                    "no further download will be started");
            return;
        }

        new AsyncTask<Void, Integer, Bitmap>() {

            private ImageError error;

            @Override
            protected void onPreExecute() {
                mUrlsInProgress.add(imageUrl);
                Log.d(TAG, "starting download");
            }

            @Override
            protected void onCancelled() {
                mUrlsInProgress.remove(imageUrl);
                mImageLoaderListener.onError(error);
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mImageLoaderListener.onProgressChange(values[0]);
            }

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap bitmap = null;
            HttpURLConnection connection = null;
            InputStream is = null;
            ByteArrayOutputStream out = null;
            try {
                connection = (HttpURLConnection) new URL(imageUrl).openConnection();
                if (displayProgress) {
                    connection.connect();
                    final int length = connection.getContentLength();
                    if (length <= 0) {
                        error = new ImageError("Invalid content length. The URL is probably not pointing to a file")
                                .setErrorCode(ImageError.ERROR_INVALID_FILE);
                        this.cancel(true);
                    }
                    is = new BufferedInputStream(connection.getInputStream(), 8192);
                    out = new ByteArrayOutputStream();
                    byte bytes[] = new byte[8192];
                    int count;
                    long read = 0;
                    while ((count = is.read(bytes)) != -1) {
                        read += count;
                        out.write(bytes, 0, count);
                        publishProgress((int) ((read * 100) / length));
                    }
                    bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());
                } else {
                    is = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                }
            } catch (Throwable e) {
                if (!this.isCancelled()) {
                    error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                    this.cancel(true);
                }
            } finally {
                try {
                    if (connection != null)
                        connection.disconnect();
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                    if (is != null)
                        is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }

            @Override
            protected void onPostExecute(Bitmap result) {
                if (result == null) {
                    Log.e(TAG, "factory returned a null result");
                    mImageLoaderListener.onError(new ImageError("downloaded file could not be decoded as bitmap")
                            .setErrorCode(ImageError.ERROR_DECODE_FAILED));
                } else {
                    Log.d(TAG, "download complete, " + result.getByteCount() +
                            " bytes transferred");
                    mImageLoaderListener.onComplete(result);
                }
                mUrlsInProgress.remove(imageUrl);
                System.gc();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    public interface OnBitmapSaveListener {
        void onBitmapSaved();
        void onBitmapSaveError(ImageError error);
    }


    public static void writeToDisk(@NonNull final File imageFile, @NonNull final Bitmap image,
                               @NonNull final OnBitmapSaveListener listener,
                               @NonNull final Bitmap.CompressFormat format, boolean shouldOverwrite) {

    if (imageFile.isDirectory()) {
        listener.onBitmapSaveError(new ImageError("the specified path points to a directory, " +
                "should be a file").setErrorCode(ImageError.ERROR_IS_DIRECTORY));
        return;
    }

    if (imageFile.exists()) {
        if (!shouldOverwrite) {
            listener.onBitmapSaveError(new ImageError("file already exists, " +
                    "write operation cancelled").setErrorCode(ImageError.ERROR_FILE_EXISTS));
            return;
        } else if (!imageFile.delete()) {
            listener.onBitmapSaveError(new ImageError("could not delete existing file, " +
                    "most likely the write permission was denied")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    }

    File parent = imageFile.getParentFile();
    if (!parent.exists() && !parent.mkdirs()) {
        listener.onBitmapSaveError(new ImageError("could not create parent directory")
                .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
        return;
    }

    try {
        if (!imageFile.createNewFile()) {
            listener.onBitmapSaveError(new ImageError("could not create file")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    } catch (IOException e) {
        listener.onBitmapSaveError(new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION));
        return;
    }

    new AsyncTask<Void, Void, Void>() {

        private ImageError error;

        @Override
        protected Void doInBackground(Void... params) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(imageFile);
                image.compress(format, 100, fos);
            } catch (IOException e) {
                error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                this.cancel(true);
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            listener.onBitmapSaveError(error);
        }

        @Override
        protected void onPostExecute(Void result) {
            listener.onBitmapSaved();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }

public static Bitmap readFromDisk(@NonNull File imageFile) {
    if (!imageFile.exists() || imageFile.isDirectory()) return null;
    return BitmapFactory.decodeFile(imageFile.getAbsolutePath());
}

public interface OnImageReadListener {
    void onImageRead(Bitmap bitmap);
    void onReadFailed();
}

public static void readFromDiskAsync(@NonNull File imageFile, @NonNull final OnImageReadListener listener) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapFactory.decodeFile(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null)
                listener.onImageRead(bitmap);
            else
                listener.onReadFailed();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageFile.getAbsolutePath());
}

    public static final class ImageError extends Throwable {

        private int errorCode;
        public static final int ERROR_GENERAL_EXCEPTION = -1;
        public static final int ERROR_INVALID_FILE = 0;
        public static final int ERROR_DECODE_FAILED = 1;
        public static final int ERROR_FILE_EXISTS = 2;
        public static final int ERROR_PERMISSION_DENIED = 3;
        public static final int ERROR_IS_DIRECTORY = 4;


        public ImageError(@NonNull String message) {
            super(message);
        }

        public ImageError(@NonNull Throwable error) {
            super(error.getMessage(), error.getCause());
            this.setStackTrace(error.getStackTrace());
        }

        public ImageError setErrorCode(int code) {
            this.errorCode = code;
            return this;
        }

        public int getErrorCode() {
            return errorCode;
        }
      }
   }

How to change the default port of mysql from 3306 to 3360

In Windows 8.1 x64 bit os, Currently I am using MySQL version :

Server version: 5.7.11-log MySQL Community Server (GPL)

For changing your MySQL port number, Go to installation directory, my installation directory is :

C:\Program Files\MySQL\MySQL Server 5.7

open the my-default.ini Configuration Setting file in any text editor.

search the line in the configuration file.

# port = .....

replace it with :

port=<my_new_port_number>

like my self changed to :

port=15800

To apply the changes don't forget to immediate either restart the MySQL Server or your OS.

Hope this would help many one.

Shell script to check if file exists

One liner to check file exist or not -

awk 'BEGIN {print getline < "file.txt" < 0 ? "File does not exist" : "File Exists"}'

How to clear all data in a listBox?

If you are using CListBox as pointer (*) use this line: pList1->ResetContent();

Correct MySQL configuration for Ruby on Rails Database.yml file

Use 'utf8mb4' as encoding to cover all unicode (including emojis)

default: &default
  adapter: mysql2
  encoding: utf8mb4
  collation: utf8mb4_bin
  username: <%= ENV.fetch("MYSQL_USERNAME") %>
  password: <%= ENV.fetch("MYSQL_PASSWORD") %>
  host:     <%= ENV.fetch("MYSQL_HOST") %>

(Reference1) (Reference2)

Discard all and get clean copy of latest revision?

hg status will show you all the new files, and then you can just rm them.

Normally I want to get rid of ignored and unversioned files, so:

hg status -iu                          # to show 
hg status -iun0 | xargs -r0 rm         # to destroy

And then follow that with:

hg update -C -r xxxxx

which puts all the versioned files in the right state for revision xxxx


To follow the Stack Overflow tradition of telling you that you don't want to do this, I often find that this "Nuclear Option" has destroyed stuff I care about.

The right way to do it is to have a 'make clean' option in your build process, and maybe a 'make reallyclean' and 'make distclean' too.

Windows Batch Files: if else

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

shorthand If Statements: C#

Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:

var redirectUrl =
      status == LoginStatusEnum.Success ? "/SecretPage"
    : status == LoginStatusEnum.Failure ? "/LoginFailed"
    : status == LoginStatusEnum.Sms ? "/2-StepSms"
    : status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
    : "/404-Error";

instead of

string redirectUrl;
switch (status)
{
    case LoginStatusEnum.Success:
        redirectUrl = "/SecretPage";
        break;
    case LoginStatusEnum.Failure:
        redirectUrl = "/LoginFailed";
        break;
    case LoginStatusEnum.Sms:
        redirectUrl = "/2-StepSms";
        break;
    case LoginStatusEnum.EmailNotConfirmed:
        redirectUrl = "/EmailNotConfirmed";
        break;
    default:
        redirectUrl = "/404-Error";
        break;
}

Convert month name to month number in SQL Server

SELECT DATEPART(MM,'january '+'01 1900')
SELECT MONTH('january ' + '01 1900')
SELECT month(dateadd(month,DATEDIFF(month,0,'january 01 2015'),0))

SQL Error: ORA-00933: SQL command not properly ended

Semicolon ; on the end of command had caused the same error on me.

cmd.CommandText = "INSERT INTO U_USERS_TABLE (USERNAME, PASSWORD, FIRSTNAME, LASTNAME) VALUES ("
                + "'" + txtUsername.Text + "',"
                + "'" + txtPassword.Text + "',"
                + "'" + txtFirstname.Text + "',"
                + "'" + txtLastname.Text + "');"; <== Semicolon in "" is the cause.
                                                      Removing it will be fine.

Hope it helps.

best way to create object

Decide if you need an immutable object or not.

If you put public properties in your class, the state of every instance can be changed at every time in your code. So your class could be like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Person(){}
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

In that case, having a Person(string name, int age) constructor is not so useful.

The second option is to implement an immutable type. For example:

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    //Other properties, methods, events...
}

Now you have a constructor that sets the state for the instance, once, at creation time. Note that now setters for properties are private, so you can't change the state after your object is instantiated.

A best practice is to define classes as immutable every time if possible. To understand advantages of immutable classes I suggest you read this article.

Starting Docker as Daemon on Ubuntu

I had the same issue on 14.04 with docker 1.9.1.

The upstart service command did work when I used sudo, even though I was root:

$ whoami
root
$ service docker status
status: Unbekannter Auftrag: docker

$ sudo service docker status
docker start/running, process 7394

It seems to depend on the environment variables.

service docker status works when becoming root with su -, but not when only using su:

$ su
Password:
$ service docker status
status: unknown job: docker
$ exit
$ su -
Password:
$ service docker status
docker start/running, process 2342

TypeError: Missing 1 required positional argument: 'self'

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example -

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

How do I use Join-Path to combine more than two strings into a file path?

If you are still using .NET 2.0, then [IO.Path]::Combine won't have the params string[] overload which you need to join more than two parts, and you'll see the error Cannot find an overload for "Combine" and the argument count: "3".

Slightly less elegant, but a pure PowerShell solution is to manually aggregate path parts:

Join-Path C: (Join-Path  "Program Files" "Microsoft Office")

or

Join-Path  (Join-Path  C: "Program Files") "Microsoft Office"

Python Accessing Nested JSON Data

Places is a list and not a dictionary. This line below should therefore not work:

print data['places']['latitude']

You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:

print data['places'][0]['post code']

What is the fastest factorial function in JavaScript?

Since a factorial is simply degenerative multiplication from the number given down to 1, it would indeed be easier to just loop through the multiplication:

Math.factorial = function(n) {

  if (n === 0||n === 1) {

    return 1;

  } else {

    for(var i = n; i > 0; --i) { //always make sure to decrement the value BEFORE it's tacked onto the original as a product
      n *= i;
    }

    return n;

  }

}

Javascript string/integer comparisons

Always remember when we compare two strings. the comparison happens on chacracter basis. so '2' > '12' is true because the comparison will happen as '2' > '1' and in alphabetical way '2' is always greater than '1' as unicode. SO it will comeout true. I hope this helps.

CSS: How to position two elements on top of each other, without specifying a height?

Here's some reusable css that will preserve the height of each element without using position: absolute:

.stack {
    display: grid;
}
.stack > * {
    grid-row: 1;
    grid-column: 1;
}

The first element in your stack is the background, and the second is the foreground.

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

Java function for arrays like PHP's join()?

If you were looking for what to use in android, it is:

String android.text.TextUtils.join(CharSequence delimiter, Object[] tokens)

for example:

String joined = TextUtils.join(";", MyStringArray);

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

Example using Hyperlink in WPF

If you want your application to open the link in a web browser you need to add a HyperLink with the RequestNavigate event set to a function that programmatically opens a web-browser with the address as a parameter.

<TextBlock>           
    <Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
        Click here
    </Hyperlink>
</TextBlock>

In the code-behind you would need to add something similar to this to handle the RequestNavigate event:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    // for .NET Core you need to add UseShellExecute = true
    // see https://docs.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.useshellexecute#property-value
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

In addition you will also need the following imports:

using System.Diagnostics;
using System.Windows.Navigation;

It will look like this in your application:

oO

Error: Module not specified (IntelliJ IDEA)

this is how I fix this issue
1.open my project structure

2.click module enter image description here 3.click plus button enter image description here 4.click import module,and find the module's pom enter image description here
5.make sure you select the module you want to import,then next next finish:) enter image description here

How to make this Header/Content/Footer layout using CSS?

Here is how to to that:

The header and footer are 30px height.

The footer is stuck to the bottom of the page.

HTML:

<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>

CSS:

#header {
    height: 30px;
}
#footer {
    height: 30px;
    position: absolute;
    bottom: 0;
}
body {
    height: 100%;
    margin-bottom: 30px;
}

Try it on jsfiddle: http://jsfiddle.net/Usbuw/

Convert string to number and add one

I believe you should add 1 after passing it to parseInt

$('.load_more').live("click",function() { //When user clicks
          var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;   
          alert(newcurrentpageTemp);
          dosomething();
      });

http://jsfiddle.net/GfqMM/

Android fastboot waiting for devices

try to use compiler generated fastboot when this happes. the file path is out/host/linux(or other)/bin/fastboot and sudo is also needed. it works in most of the time.

.htaccess: where is located when not in www base dir

. (dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess files, then they are probably in the root folder for the website.

If you are using a command line (terminal) to access, then they will only show up if you use:

ls -a

If you are using a GUI application, look for a setting to "show hidden files" or something similar.

If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):

cd /
find . -name ".htaccess"

This will list out any files it finds with that name.

Like Operator in Entity Framework?

Update: In EF 6.2 there is a like operator

Where(obj => DbFunctions.Like(obj.Column , "%expression%")

How to access remote server with local phpMyAdmin client?

Delete complete entries of /etc/http/conf.d/phpMyAdmin.conf

And below entires in above file,

_x000D_
_x000D_
<Directory /usr/share/phpMyAdmin/>_x000D_
   AddDefaultCharset UTF-8_x000D_
_x000D_
   <IfModule mod_authz_core.c>_x000D_
     # Apache 2.4_x000D_
     <RequireAny>_x000D_
       #ADD following line:_x000D_
       Require all granted_x000D_
       Require ip 127.0.0.1_x000D_
       Require ip ::1_x000D_
     </RequireAny>_x000D_
   </IfModule>_x000D_
   <IfModule !mod_authz_core.c>_x000D_
     # Apache 2.2_x000D_
     #CHANGE following 2 lines:_x000D_
     Order Allow,Deny_x000D_
     Allow from All_x000D_
     Allow from 127.0.0.1_x000D_
     Allow from ::1_x000D_
   </IfModule>_x000D_
</Directory>
_x000D_
_x000D_
_x000D_

Then,

run below command in MySQL prompt,

GRANT ALL ON *.* to root@localhost IDENTIFIED BY 'root@<password>'

GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'root@<password>'

For reference: Allow IP to Access Secured PhpMyAdmin

Get the IP address of the machine

I found the ioctl solution problematic on os x (which is POSIX compliant so should be similiar to linux). However getifaddress() will let you do the same thing easily, it works fine for me on os x 10.5 and should be the same below.

I've done a quick example below which will print all of the machine's IPv4 address, (you should also check the getifaddrs was successful ie returns 0).

I've updated it show IPv6 addresses too.

#include <stdio.h>      
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h> 
#include <string.h> 
#include <arpa/inet.h>

int main (int argc, const char * argv[]) {
    struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
        if (!ifa->ifa_addr) {
            continue;
        }
        if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
            printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
        } else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6
            // is a valid IP6 Address
            tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
            char addressBuffer[INET6_ADDRSTRLEN];
            inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
            printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
        } 
    }
    if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
    return 0;
}

Import text file as single character string

Too bad that Sharon's solution cannot be used anymore. I've added Josh O'Brien's solution with asieira's modification to my .Rprofile file:

read.text = function(pathname)
{
    return (paste(readLines(pathname), collapse="\n"))
}

and use it like this: txt = read.text('path/to/my/file.txt'). I couldn't replicate bumpkin's (28 oct. 14) finding, and writeLines(txt) showed the contents of file.txt. Also, after write(txt, '/tmp/out') the command diff /tmp/out path/to/my/file.txt reported no differences.

Read/write files within a Linux kernel module

You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:

Includes:

#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>

Opening a file (similar to open):

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}

Close a file (similar to close):

void file_close(struct file *file) 
{
    filp_close(file, NULL);
}

Reading data from a file (similar to pread):

int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_read(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}   

Writing data to a file (similar to pwrite):

int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size) 
{
    mm_segment_t oldfs;
    int ret;

    oldfs = get_fs();
    set_fs(get_ds());

    ret = vfs_write(file, data, size, &offset);

    set_fs(oldfs);
    return ret;
}

Syncing changes a file (similar to fsync):

int file_sync(struct file *file) 
{
    vfs_fsync(file, 0);
    return 0;
}

[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.

Check if ADODB connection is open

This topic is old but if other people like me search a solution, this is a solution that I have found:

Public Function DBStats() As Boolean
    On Error GoTo errorHandler
        If Not IsNull(myBase.Version) Then 
            DBStats = True
        End If
        Exit Function
    errorHandler:
        DBStats = False  
End Function

So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":

Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false

Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

It sounds like your error comes from an attempt to run something like this (which works in Linux)

NODE_ENV=development node foo.js

the equivalent in Windows would be

SET NODE_ENV=development
node foo.js

running in the same command shell. You mentioned set NODE_ENV did not work, but wasn't clear how/when you executed it.

Call a PHP function after onClick HTML event

<div id="sample"></div>   
 <form>
        <fieldset>
            <legend>Add New Contact</legend>
            <input type="text" name="fullname" placeholder="First name and last name" required /> <br />
            <input type="email" name="email" placeholder="[email protected]" required /> <br />
            <input type="text" name="phone" placeholder="Personal phone number: mobile, home phone etc." required /> <br />
            <input type="submit" name="submit" id= "submitButton" class="button" value="Add Contact" onClick="" />
            <input type="button" name="cancel" class="button" value="Reset" />
        </fieldset>
    </form>

<script>

    $(document).ready(function(){
         $("#submitButton").click(function(){
            $("#sample").load(filenameofyourfunction?the the variable you need);
         });
    });

</script>

Validate decimal numbers in JavaScript - IsNumeric()

Since jQuery 1.7, you can use jQuery.isNumeric():

$.isNumeric('-1');      // true
$.isNumeric('-1.5');    // true
$.isNumeric('0');       // true
$.isNumeric('0.42');    // true
$.isNumeric('.42');     // true
$.isNumeric('0x89f');   // true (valid hexa number)
$.isNumeric('99,999');  // false
$.isNumeric('#abcdef'); // false
$.isNumeric('1.2.3');   // false
$.isNumeric('');        // false
$.isNumeric('blah');    // false

Just note that unlike what you said, 0x89f is a valid number (hexa)

Map implementation with duplicate keys

You could simply pass an array of values for the value in a regular HashMap, thus simulating duplicate keys, and it would be up to you to decide what data to use.

You may also just use a MultiMap, although I do not like the idea of duplicate keys myself.

Javascript: Unicode string to hex

how do you get "\u6f22\u5b57" from ?? in JavaScript?

These are JavaScript Unicode escape sequences e.g. \u12AB. To convert them, you could iterate over every code unit in the string, call .toString(16) on it, and go from there.

However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA in the output wherever possible.

Also note that ASCII symbols such as A, b, and - probably don’t need to be escaped.

I’ve written a small JavaScript library that does all this for you, called jsesc. It has lots of options to control the output.

Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97


Your question was tagged as utf-8. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js (online demo).

Android; Check if file exists without creating a new one

When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.

File file = new File(filePath);
if(file.exists()) 
    //do something

Installing SciPy with pip

Besides all of these answers, If you install python of 32bit on your 64bit machine, you have to download scipy of 32-bit irrespective of your machine. http://www.lfd.uci.edu/~gohlke/pythonlibs/ In the above URL you can download the packages and command is: pip install

Adding values to a C# array

You can't do this directly. However, you can use Linq to do this:

List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();

If the array terms wasn't empty in the beginning, you can convert it to List first then do your stuf. Like:

    List<int> termsLst = terms.ToList();
    for (int runs = 0; runs < 400; runs++)
    {
        termsLst.Add(runs);
    }
    terms = termsLst.ToArray();

Note: don't miss adding 'using System.Linq;' at the begaining of the file.

How to center icon and text in a android button with width set to "fill parent"

You could put the button over a LinearLayout

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/activity_login_fb_height"
        android:background="@mipmap/bg_btn_fb">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/lblLoginFb"
                android:textColor="@color/white"
                android:drawableLeft="@mipmap/icon_fb"
                android:textSize="@dimen/activity_login_fb_textSize"
                android:text="Login with Facebook"
                android:gravity="center" />
        </LinearLayout>
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/btnLoginFb"
            android:background="@color/transparent"
            />
    </RelativeLayout>

Find what 2 numbers add to something and multiply to something

That's basically a set of 2 simultaneous equations:

x*y = a
X+y = b

(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).

But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

Detect whether there is an Internet connection available on Android

Step 1: Create a class AppStatus in your project(you can give any other name also). Then please paste the given below lines into your code:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;


public class AppStatus {

    private static AppStatus instance = new AppStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        connected = networkInfo != null && networkInfo.isAvailable() &&
                networkInfo.isConnected();
        return connected;


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}

Step 2: Now to check if the your device has network connectivity then just add this code snippet where ever you want to check ...

if (AppStatus.getInstance(this).isOnline()) {

    Toast.makeText(this,"You are online!!!!",8000).show();

} else {

    Toast.makeText(this,"You are not online!!!!",8000).show();
    Log.v("Home", "############################You are not online!!!!");    
}

Difference between git pull and git pull --rebase

Suppose you have two commits in local branch:

      D---E master
     /
A---B---C---F origin/master

After "git pull", will be:

      D--------E  
     /          \
A---B---C---F----G   master, origin/master

After "git pull --rebase", there will be no merge point G. Note that D and E become different commits:

A---B---C---F---D'---E'   master, origin/master

Oracle: is there a tool to trace queries, like Profiler for sql server?

There is a commercial tool FlexTracer which can be used to trace Oracle SQL queries

Http Get using Android HttpURLConnection

Here is a complete AsyncTask class

public class GetMethodDemo extends AsyncTask<String , Void ,String> {
    String server_response;

    @Override
    protected String doInBackground(String... strings) {

        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();

            int responseCode = urlConnection.getResponseCode();

            if(responseCode == HttpURLConnection.HTTP_OK){
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        Log.e("Response", "" + server_response);


    }
}

// Converting InputStream to String

private String readStream(InputStream in) {
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response.toString();
    }

To Call this AsyncTask class

new GetMethodDemo().execute("your web-service url");

How to keep :active css style after clicking an element

If you want to keep your links to look like they are :active class, you should define :visited class same as :active so if you have a links in .example then you do something like this:

a.example:active, a.example:visited {
/* Put your active state style code here */ }

The Link visited Pseudo Class is used to select visited links as says the name.

How to check if $? is not equal to zero in unix shell scripting?

function assert_exit_code {
    rc=$?; if [[ $rc != 0 ]]; then echo "$1" 1>&2; fi
}

...

execute.sh

assert_exit_code "execute.sh has failed"

Simple two column html layout without using tables

I know this is an old post, but figured I'd add my two penneth. How about the seldom used and oft' forgot Description list? With a simple bit of css you can get a really clean markup.

<dl>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
</dl>

take a look at this example http://codepen.io/butlerps/pen/wGmXPL

Insert NULL value into INT column

If the column has the NOT NULL constraint then it won't be possible; but otherwise this is fine:

INSERT INTO MyTable(MyIntColumn) VALUES(NULL);

Validate phone number using javascript

/^1?\s?(\([0-9]{3}\)[- ]?|[0-9]{3}[- ]?)[0-9]{3}[- ]?[0-9]{4}$/

This will validate all US style numbers, with or without the 1, and with or without parenthesis on area code(but if used, used properly. I.E. (902-455-4555 will not work since there is no closing parenthesis. it also allows for either - or a space between sets if wanted.) It will work for the examples provided by op.

How to find out what type of a Mat object is with Mat::type() in OpenCV

In OpenCV header "types_c.h" there are a set of defines which generate these, the format is CV_bits{U|S|F}C<number_of_channels>
So for example CV_8UC3 means 8 bit unsigned chars, 3 colour channels - each of these names map onto an arbitrary integer with the macros in that file.

Edit: See "types_c.h" for example:

#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))

eg.
depth = CV_8U = 0
cn = 3
CV_CN_SHIFT = 3

CV_MAT_DEPTH(0) = 0
(((cn)-1) << CV_CN_SHIFT) = (3-1) << 3 = 2<<3 = 16

So CV_8UC3 = 16 but you aren't supposed to use this number, just check type() == CV_8UC3 if you need to know what type an internal OpenCV array is.
Remember OpenCV will convert the jpeg into BGR (or grey scale if you pass '0' to imread) - so it doesn't tell you anything about the original file.

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

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

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

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

The output will look like this:

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

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

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

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

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

Why do I need to override the equals and hashCode methods in Java?

When you want to store and retrieve your custom object as a key in Map, then you should always override equals and hashCode in your custom Object . Eg:

Person p1 = new Person("A",23);
Person p2 = new Person("A",23);
HashMap map = new HashMap();
map.put(p1,"value 1");
map.put(p2,"value 2");

Here p1 & p2 will consider as only one object and map size will be only 1 because they are equal.

Retrieving the last record in each group - MySQL

What about:

select *, max(id) from messages group by name 

I have tested it on sqlite and it returns all columns and max id value for all names.

C++ for each, pulling from vector elements

C++ does not have the for_each loop feature in its syntax. You have to use c++11 or use the template function std::for_each.

struct Function {
    int input;
    Function(int input): input(input) {}
    void operator()(Attack& attack) {
        if(attack->m_num == input) attack->makeDamage();
    }
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);

Convert array of JSON object strings to array of JS objects

var json = jQuery.parseJSON(s); //If you have jQuery.

Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

Change the above code to

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

Eg:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

And then use the parse function. It'll surely work.

EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

Jquery

The json api

Edit (30 April 2020):

Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")

Running Facebook application on localhost

Ok I'm not sure what's up with these answers but I'll let you know what worked for me as advised by a senior dev at my work. I'm working in Ruby on Rails and using Facebook's JavaScript code to get access tokens.

Problem: To do authentication, Facebook is taking the url from your address bar and comparing that with what they have on file. They don't allow you to use localhost:3000 for whatever reason. However, you can use a completely made-up domain name like yoursite.dev by running a local server and pointing yoursite.dev to 127.0.0.1:3000 or wherever your localhost was pointing to.

Step 1: Install or update Nginx

$ brew install nginx (install) or $ brew upgrade nginx (update)

Step 2: Open up your nginx config file

/usr/local/etc/nginx/nginx.conf (usually here)

/opt/boxen/config/nginx/nginx.conf(if you use Boxen)

Step 3 Add this bit of code into your http {} block

Replace proxy_pass with wherever you want to point yoursite.dev to. In my case it was replacing localhost:3000 or the equivalent 127.0.0.1:3000

server {
  listen       yoursite.dev:80;
  server_name  yoursite.dev;
  location / {
    proxy_pass http://127.0.0.1:3000;
  }
}

Step 4: Edit your hosts file, in /etc/hosts on Mac to include

127.0.0.1   yoursite.dev

This file directs domains to localhost. Nginx listens in on localhost and redirects if it matches a rule.

Step 5: Every time you use your dev environment going forward, you use the yoursite.dev in the address bar instead of localhost:3000 so Facebook logs you in correctly.

Leaflet changing Marker color

A cheap way to change the Leaflet marker colour is to use the CSS filter property. Give the icon an extra class and then change its colour in the stylesheet:

<style>
img.huechange { filter: hue-rotate(120deg); }
</style>
<script>
var marker = L.marker([y, x]).addTo(map);
marker._icon.classList.add("huechange");
</script>

and this will produce a red marker: alter the value given to hue-rotate to alter the colour.

enter image description here

How do I change Bootstrap 3 column order on mobile layout?

In Bootstrap 4, if you want to do something like this:

    Mobile  |   Desktop
-----------------------------
    A       |       A
    C       |   B       C
    B       |       D
    D       |

You need to reverse the order of B then C then apply order-{breakpoint}-first to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:

  • Smaller screens: 12 cols to B and 12 cols to C

  • Larger screens: 12 cols between the sum of them (B + C = 12)

Like this

<div class='row no-gutters'>
    <div class='col-12'>
        A
    </div>
    <div class='col-12'>
        <div class='row no-gutters'>
            <div class='col-12 col-md-6'>
                C
            </div>
            <div class='col-12 col-md-6 order-md-first'>
                B
            </div>
        </div>
    </div>
    <div class='col-12'>
        D
    </div>
</div>

Demo: https://codepen.io/anon/pen/wXLGKa

Replace all whitespace characters

Have you tried the \s?

str.replace(/\s/g, "X");

How can I use jQuery in Greasemonkey?

the @require meta does not work when you want to unbind events on a webpage using jQuery, you have to use a jQuery library included in the webpage and then get it in Greasemonkey with var $ = unsafeWindow.jQuery; How do I unbind jquery event handlers in greasemonkey?

Reading and writing binary file

 sizeof(buffer) == sizeof(char*) 

Use length instead.

Also, better to use fopen with "wb"....

How to parse a String containing XML in Java and retrieve the value of the root node?

Using JDOM:

String xml = "<message>HELLO!</message>";
org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
try {
    org.jdom.Document doc = saxBuilder.build(new StringReader(xml));
    String message = doc.getRootElement().getText();
    System.out.println(message);
} catch (JDOMException e) {
    // handle JDOMException
} catch (IOException e) {
    // handle IOException
}

Using the Xerces DOMParser:

String xml = "<message>HELLO!</message>";
DOMParser parser = new DOMParser();
try {
    parser.parse(new InputSource(new java.io.StringReader(xml)));
    Document doc = parser.getDocument();
    String message = doc.getDocumentElement().getTextContent();
    System.out.println(message);
} catch (SAXException e) {
    // handle SAXException 
} catch (IOException e) {
    // handle IOException 
}

Using the JAXP interfaces:

String xml = "<message>HELLO!</message>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
    db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    try {
        Document doc = db.parse(is);
        String message = doc.getDocumentElement().getTextContent();
        System.out.println(message);
    } catch (SAXException e) {
        // handle SAXException
    } catch (IOException e) {
        // handle IOException
    }
} catch (ParserConfigurationException e1) {
    // handle ParserConfigurationException
}

proper way to logout from a session in PHP

<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.    
session_destroy();

// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>

How to get changes from another branch

git fetch origin our-team

or

git pull origin our-team

but first you should make sure that you already on the branch you want to update to (featurex).

Get first row of dataframe in Python Pandas based on criteria

This tutorial is a very good one for pandas slicing. Make sure you check it out. Onto some snippets... To slice a dataframe with a condition, you use this format:

>>> df[condition]

This will return a slice of your dataframe which you can index using iloc. Here are your examples:

  1. Get first row where A > 3 (returns row 2)

    >>> df[df.A > 3].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

If what you actually want is the row number, rather than using iloc, it would be df[df.A > 3].index[0].

  1. Get first row where A > 4 AND B > 3:

    >>> df[(df.A > 4) & (df.B > 3)].iloc[0]
    A    5
    B    4
    C    5
    Name: 4, dtype: int64
    
  2. Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)

    >>> df[(df.A > 3) & ((df.B > 3) | (df.C > 2))].iloc[0]
    A    4
    B    6
    C    3
    Name: 2, dtype: int64
    

Now, with your last case we can write a function that handles the default case of returning the descending-sorted frame:

>>> def series_or_default(X, condition, default_col, ascending=False):
...     sliced = X[condition]
...     if sliced.shape[0] == 0:
...         return X.sort_values(default_col, ascending=ascending).iloc[0]
...     return sliced.iloc[0]
>>> 
>>> series_or_default(df, df.A > 6, 'A')
A    5
B    4
C    5
Name: 4, dtype: int64

As expected, it returns row 4.

C# Timer or Thread.Sleep

Yes, using a Timer will free up a Thread that is currently spending most of its time sleeping. A Timer will also more accurately fire every minute so you probably won't need to keep track of lastMinute anymore.

Haskell: Converting Int to String

Anyone who is just starting with Haskell and trying to print an Int, use:

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

How to connect to LocalDB in Visual Studio Server Explorer?

Fix doesn't work.

Exactly as in the example illustration, all these steps only provide access to "system" databases, and no option to select existing user databases that you want to access.

The solution to access a local (not Express Edition) Microsoft SQL server instance resides on the SQL Server side:

  1. Open the Run dialog (WinKey + R)
  2. Type: "services.msc"
  3. Select SQL Server Browser
  4. Click Properties
  5. Change "disabled" to either "Manual" or "Automatic"
  6. When the "Start" service button gets enable, click on it.

Done! Now you can select your local SQL Server from the Server Name list in Connection Properties.

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer

jQuery Refresh/Reload Page if Ajax Success after time

location.reload();

You can use the reload function in your if condition for success and the page will reload after the condition is successful.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

I solved this issue by redirecting the user to the FQDN of the server hosting the intranet.

IE probably uses the world's worst algorithm for detecting "intranet" sites ... indeed, specifying server.domain.tld solves the problem for me.

Yes, you read that correctly, IE detects intranet sites not by private IP address, like any dev who has heard of TCP/IP would do, no, by the "host" part of the URL, if it has no domain part, must be internal.

Scary to know the IE devs do not understand the most basic TCP/IP concepts.

Note that this was at a BIG enterprise customer, getting them to change GPO for you is like trying to move the Alps east by 4 meters, not gonna happen.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

In the project into the folder Libraries-->right click --> Add Library --> Mysqlconnector 5.1

how to convert object to string in java

Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.

makefile:4: *** missing separator. Stop

This is because tab is replaced by spaces. To disable this feature go to

gedit->edit->preferences->editor

and remove check for

"replace tab with space"

How to change color of the back arrow in the new material theme?

I just changed the toolbar theme to be @style/ThemeOverlay.AppCompat.Light

and the arrow became dark gray

            <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:gravity="center"
            app:layout_collapseMode="pin"
            app:theme="@style/ThemeOverlay.AppCompat.Light">

Android replace the current fragment with another fragment

Latest Stuff

Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.

Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.

  1. Add Kotlin extension for Fragments to your project.

In your app level build.gradle file add the following,

dependencies {
    def fragment_version = "1.2.5"

    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
  1. Then simple code to replace the fragment,

In your activity

supportFragmentManager.commit {
    replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
    addToBackStack(null)
}

References

Check latest version of Fragment extension

More on Fragments

How to find if div with specific id exists in jQuery?

You can handle it in different ways,

Objective is to check if the div exist then execute the code. Simple.

Condition:

$('#myDiv').length

Note:

#myDiv -> < div id='myDiv' > <br>
.myDiv -> < div class='myDiv' > 

This will return a number every time it is executed so if there is no div it will give a Zero [0], and as we no 0 can be represented as false in binary so you can use it in if statement. And you can you use it as a comparison with a none number. while any there are three statement given below

// Statement 0
// jQuery/Ajax has replace [ document.getElementById with $ sign ] and etc
// if you don't want to use jQuery/ajax 

   if (document.getElementById(name)) { 
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 1
   if ($('#'+ name).length){ // if 0 then false ; if not 0 then true
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 2
    if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1]
           $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>"); 
    }
// Statement 3
    if ($('#'+ name).length > 0 ) {
      $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

// Statement 4
    if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist.
       $("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
    }

Create an Excel file using vbscripts

set objExcel = CreateObject("Excel.Application")
objExcel.Application.DisplayAlerts = False
set objWorkbook=objExcel.workbooks.add()
objExcel.cells(1,1).value = "Test value"
objExcel.cells(1,2).value = "Test data"
objWorkbook.Saveas "c:\testXLS.xls"
objWorkbook.Close
objExcel.workbooks.close
objExcel.quit
set objExcel = nothing `

Start script missing error when running npm start

If you are using babelify and watchify, go to:

package.json

and add this in "scripts":

"scripts": {
    "start": "watchify the-path-to-your-source-jsx-file -v -t [ babelify --presets [ react ] ] -o the-path-to-your-output-js-file"
}

An example would be:

"scripts": {
    "start": "watchify src/main.jsx -v -t [ babelify --presets [ react ] ] -o public/js/main.js"
}

Thanks to Mark Price from DevSlopes