答:
You have to use the utf8mb4 character encoding in your mySQL database in order to use smileys and other such content.

The character set named utf8 uses a maximum of three bytes per
  character and contains only BMP characters. As of MySQL 5.5.3, the
  utf8mb4 character set uses a maximum of four bytes per character
  supports supplementary characters.

Source: https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html

You can either set the data type of the column or of the whole database.

Your can use a query something like:

```<code>ALTER TABLE `your_table` CHANGE `text` `text` VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;
</code>```

Below is a step by step guide to make your tasks easier:

Step 1: Create a backup http://mathiasbynens.be/notes/mysql-utf8mb4#backup

Step 2: Upgrade the MySQL server http://mathiasbynens.be/notes/mysql-utf8mb4#upgrade

Step 3: Modify databases, tables, and columns http://mathiasbynens.be/notes/mysql-utf8mb4#databases-tables-columns

Step 4: Check the maximum length of columns and index keys http://mathiasbynens.be/notes/mysql-utf8mb4#column-index-length

Step 5: Modify connection, client, and server character sets http://mathiasbynens.be/notes/mysql-utf8mb4#character-sets

Step 6: Repair and optimize all tables http://mathiasbynens.be/notes/mysql-utf8mb4#repair-optimize

Title: How insert in database using insert query(mysql) in php

Body:
ककखघगघचछजझ़ंंनधथतणढठटपफफबभमयरलवशश्ँत्रत्रक्षससज्ञाइइईउऊ चजझ़ंनधदथतणढठट पबभमययलवशश ँऋत्रक्षहसषर्टाइउए 123455678990१२३४५६७८९० @()"'-/?₹_+×÷¡¿√♀•∆π™℅¶♂♀【】°℃®©★■◆●

how to insert Smiley and text in database using mysql insert query and so on .

I want to use this in Rest api webservice for mobile app.

Body:
You have to use the utf8mb4 character encoding in your mySQL database in order to use smileys and other such content.

The character set named utf8 uses a maximum of three bytes per
  character and contains only BMP characters. As of MySQL 5.5.3, the
  utf8mb4 character set uses a maximum of four bytes per character
  supports supplementary characters.

Source: https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html

You can either set the data type of the column or of the whole database.

Your can use a query something like:

ALTER TABLE `your_table` CHANGE `text` `text` VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;

Below is a step by step guide to make your tasks easier:

Step 1: Create a backup http://mathiasbynens.be/notes/mysql-utf8mb4#backup

Step 2: Upgrade the MySQL server http://mathiasbynens.be/notes/mysql-utf8mb4#upgrade

Step 3: Modify databases, tables, and columns http://mathiasbynens.be/notes/mysql-utf8mb4#databases-tables-columns

Step 4: Check the maximum length of columns and index keys http://mathiasbynens.be/notes/mysql-utf8mb4#column-index-length

Step 5: Modify connection, client, and server character sets http://mathiasbynens.be/notes/mysql-utf8mb4#character-sets

Step 6: Repair and optimize all tables http://mathiasbynens.be/notes/mysql-utf8mb4#repair-optimize


来源: stackexchange

问:
Android studio error:Execution failed for task ':app:processDebugGoogleServices'
I am building a native android app using android studio. so far i have used firebase and map pages for content, but i keep on getting an error. I saw similar post like mine but those where from some time ago with different versions. I am wondering if somebody knows the solution for this.

Error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
  '>' Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 10.0.1.

App level build.gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "com.me.myproject"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-maps:10.2.1'
    testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Project level build.gradle:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

EDIT: After changing firebase and play services to the same version i get this error(see below) and i am being sent to file v24\values-v24.xml

Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.
  Error:(4) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
  Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.
  Error:(4) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
  Error:Execution failed for task ':app:processDebugResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

答:
Sloppy mistake . You must use Same version .

```<code> compile 'com.google.firebase:firebase-auth:10.2.1' //Use this instead of old .
 compile 'com.google.android.gms:play-services-maps:10.2.1'
</code>```

Then Clean-Rebuild and Run .

ContentLicense: CC BY-SA 3.0

Body:
I am building a native android app using android studio. so far i have used firebase and map pages for content, but i keep on getting an error. I saw similar post like mine but those where from some time ago with different versions. I am wondering if somebody knows the solution for this.

Error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
  '>' Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 10.0.1.

App level build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.2'
    defaultConfig {
        applicationId "com.me.myproject"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.firebase:firebase-auth:10.0.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-maps:10.2.1'
    testCompile 'junit:junit:4.12'
}

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

Project level build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

EDIT: After changing firebase and play services to the same version i get this error(see below) and i am being sent to file v24\values-v24.xml

Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.
  Error:(4) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
  Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'.
  Error:(4) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Colored'.
  Error:Execution failed for task ':app:processDebugResources'.
  com.android.ide.common.process.ProcessException: Failed to execute aapt

Body:
Sloppy mistake . You must use Same version .

 compile 'com.google.firebase:firebase-auth:10.2.1' //Use this instead of old .
 compile 'com.google.android.gms:play-services-maps:10.2.1'

Then Clean-Rebuild and Run .


问:
React CSS Modules, Is not working. Some Idea?
I install all the dependences:

```<code>    "devDependencies": {
      "css-loader": "^0.26.4",
      "sass-loader": "^6.0.3",
      "style-loader": "^0.13.2
    }
</code>```

The bundle detect my import correctly:

```<code>import styles from './styles.scss';
</code>```

and I configure my webpack config:

```<code>module : {
    loaders : [
        {
            test: /\.(sass|scss)$/,
            use: ['style-loader', 'css-loader', 'sass-loader']
        },
        {
            test : /\.jsx?/,
            include : APP_DIR,
            loader : 'babel-loader'
        }
    ]
}
</code>```

But in the final render doesn't appear the classes.
Some idea? Thank you!!!

答:
I know that's not perfect solution, but working:
in my project css are bundled in one bundle.css file and my settings are:

1.In components i got:
   import "./User.css";

2.In webpack config:
var ExtractTextPlugin = require('extract-text-webpack-plugin');

3.And then in webpack config module section:

```<code>module: {
    loaders: [
        { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
        { test: /\.js$/, loader: "source-map-loader", enforce: "pre" },
        {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: "css-loader",
            })
        }
    ]
},
plugins: [
new ExtractTextPlugin('../css/[name].css')
]
</code>```

Body:
I install all the dependences:

    "devDependencies": {
      "css-loader": "^0.26.4",
      "sass-loader": "^6.0.3",
      "style-loader": "^0.13.2
    }

The bundle detect my import correctly:

import styles from './styles.scss';

and I configure my webpack config:

module : {
    loaders : [
        {
            test: /\.(sass|scss)$/,
            use: ['style-loader', 'css-loader', 'sass-loader']
        },
        {
            test : /\.jsx?/,
            include : APP_DIR,
            loader : 'babel-loader'
        }
    ]
}

But in the final render doesn't appear the classes.
Some idea? Thank you!!!

Body:
I know that's not perfect solution, but working:
in my project css are bundled in one bundle.css file and my settings are:

1.In components i got:
   import "./User.css";

2.In webpack config:
var ExtractTextPlugin = require('extract-text-webpack-plugin');

3.And then in webpack config module section:

module: {
    loaders: [
        { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
        { test: /\.js$/, loader: "source-map-loader", enforce: "pre" },
        {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: "css-loader",
            })
        }
    ]
},
plugins: [
new ExtractTextPlugin('../css/[name].css')
]


问:
Ionic 2/ Anuglar 2 how to move parent functions into extended classes
My parent component is too large to manage so I want to move the the functions into the separated child classes that extend the parent.

The parent class contains variables that need to be updated in the child classes as well as I have injected providers into the parent as well.

```<code>    @Component({
    selector: 'events-list',
    templateUrl: 'events-list.html'

})
export class EventsListComponent {
    filterString: string;
    infiniteScroll: any;
    refresher: any;
    eventsList: any[];
    selectedCategoriesList: [Category];
    pageNum: number;
    pageSize: number;
    searchText: string = '';
    noEvents: boolean;
    filterSearchText: string;
    filterStartDate: string;
    filterEndDate: string;
    tabsFilterValue: string = 'all'

    constructor(

        public authSrvc: AuthSrvc,
        public calendarSrvc: CalendarSrvc,
        public eventsSrvc: EventsSrvc,
        public helperSrvc: HelperSrvc,
        public locationSrvc: LocationSrvc,
        public pushSrvc: PushSrvc) {

    }
</code>```

Above is my parent class

```<code>    import {Injectable} from '@angular/core';
import {Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/observable/of';
import {Observable} from 'rxjs/Observable';
import {ModalController, LoadingController, NavController, ToastController, Platform} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {DateFormatPipe} from 'angular2-moment';
import {Category} from '../../../app/app.interfaces';
import * as moment from 'moment';

/** Ionic Native **/
import {GoogleAnalytics} from '@ionic-native/google-analytics';
import {Network} from '@ionic-native/network';

/** Providers **/
import {AuthSrvc} from '../../../../providers/auth-srvc';
import {CalendarSrvc} from '../../../../providers/calendar-srvc';
import {EventsSrvc} from '../../../../providers/events-srvc';
import {HelperSrvc} from '../../../../providers/helper-srvc';
import {LocationSrvc} from '../../../../providers/location-srvc';
import {PushSrvc} from '../../../../providers/push-srvc';

/** Pages **/
import {AuthPage} from '../../../pages/auth/auth-page';

import {EventsListComponent} from '../../../events-components/events-list/events-list';

export class eventsInit extends EventsListComponent {

    constructor(
        loadingCtrl: LoadingController,
        toastCtrl: ToastController,
        modalCtrl: ModalController,
        navCtrl: NavController,
        platform: Platform,
        storage: Storage,

        ga: GoogleAnalytics,
        network: Network,

        authSrvc: AuthSrvc,
        calendarSrvc: CalendarSrvc,
        eventsSrvc: EventsSrvc,
        helperSrvc: HelperSrvc,
        locationSrvc: LocationSrvc,
        pushSrvc: PushSrvc

    ) {
        super(loadingCtrl,
        toastCtrl,
        modalCtrl,
        navCtrl,
        platform,
        storage,

        ga,
        network,

        authSrvc,
        calendarSrvc,
        eventsSrvc,
        helperSrvc,
        locationSrvc,
        pushSrvc);
    }

    ngOnInit()
    {
        console.log('test')
    }
}
</code>```

Above is my child class

this is not working and is always failing with by parameters not being populated or the super call failing. What is the correct way to do this.

/** Update **/

If removing the injectable I always get the error Can't resolve all parameters for eventsInit: (?, ?, ?, ?, ?, ?).

Below is my main module

```<code>    import {NgModule, ErrorHandler} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Ng2ImgFallbackModule} from 'ng2-img-fallback';
import {CloudSettings, CloudModule} from '@ionic/cloud-angular';
import {MomentModule,DateFormatPipe} from 'angular2-moment';
import { IonicStorageModule } from '@ionic/storage';

import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {EnvironmentsModule} from '../environment_variables/environment_variables.module'
import {AppConfig} from '../app/app.config';
import {MyApp} from '../app/app.component';

/** Ionic Native **/
import {Calendar} from '@ionic-native/calendar';
import { Diagnostic } from '@ionic-native/diagnostic';
import {Facebook} from '@ionic-native/facebook';
import {GooglePlus} from '@ionic-native/google-plus';
import { GoogleAnalytics } from '@ionic-native/google-analytics';
import { Keyboard } from '@ionic-native/keyboard';
import { LaunchNavigator, LaunchNavigatorOptions } from '@ionic-native/launch-navigator';
import {Network} from '@ionic-native/network';
import { SocialSharing } from '@ionic-native/social-sharing';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

/** Pages **/
import {AuthPage} from '../pages/auth/auth-page';
import {EventsPage} from '../pages/events/events-page';
import {EventPage} from '../pages/event/event-page';
import {ProfilePage} from '../pages/profile/profile';
import {SettingsPage} from '../pages/settings/settings';

/** Components **/
//Auth
import {LoginComponent} from '../components/auth-components/login/login';
import {ForgotPasswordDirective} from '../components/auth-components/forgot-password';
import {RegisterComponent} from '../components/auth-components/register/register';
import {SocialComponent} from '../components/auth-components/social/social';
import {WalkthroughComponent} from '../components/auth-components/walkthrough/walkthrough';
//Base
import {SidenavComponent} from '../components/sidenav/sidenav';
import {TimeslotFilterComponent} from '../components/timeslot-filter/timeslot-filter';
import {SettingsComponent} from '../components/settings/settings';
import {EventBookComponent} from '../components/event-book/event-book';
//Events
import {EventsFilterComponent} from '../components/events-components/events-filter/events-filter';
import {EventsListComponent} from '../components/events-components/events-list/events-list';
    /** Events Extensions **/
    import {eventsInit} from '../components/events-components/events-list/extensions/events-init';
import {EventsItemComponent} from '../components/events-components/events-item/events-item';
//Event
import {AttendeesListComponent} from '../components/event-components/attendees-list/attendees-list';
import {AttendeesItemComponent} from '../components/event-components/attendees-item/attendees-item';
//Profile
import {ProfileComponent} from '../components/profile/profile';

import {ParallaxHeaderDirective} from '../components/parallax-header';

/** Providers **/
import {EventsSrvc} from '../providers/events-srvc';
import {AuthSrvc} from '../providers/auth-srvc';
import {CalendarSrvc} from '../providers/calendar-srvc';
import {HelperSrvc} from '../providers/helper-srvc';
import {LocationSrvc} from '../providers/location-srvc';
import {PushSrvc} from '../providers/push-srvc';

/** Pipes **/
import {LimitToPipe} from '../pipes/limitTo'

const cloudSettings: CloudSettings = {
    'core': {
        'app_id': 'df0d4e63'
    }
};

class NetworkMock extends Network {
 get type(): string {
    return (super['type'] === null) ? "wifi" : super['type'];
  }
}

@NgModule({
    declarations: [
        MyApp,
        AuthPage,
        LoginComponent,
        ForgotPasswordDirective,
        ParallaxHeaderDirective,
        RegisterComponent,
        SocialComponent,
        WalkthroughComponent,
        SidenavComponent,
        EventsPage,
        EventsListComponent,
        eventsInit,
        EventsItemComponent,
        EventsFilterComponent,
        AttendeesListComponent,
        AttendeesItemComponent,
        EventPage,
        ProfilePage,
        ProfileComponent,
        SettingsPage,
        SettingsComponent,
        TimeslotFilterComponent,
        EventBookComponent,
        LimitToPipe,
    ],
    imports: [
        IonicModule.forRoot(MyApp,
            {
                backButtonText: 'Back',
                backButtonIcon: 'arrow-back',
                iconMode: 'md',
                modalEnter: 'modal-slide-in',
                modalLeave: 'modal-slide-out',
                tabsPlacement: 'bottom',
                pageTransition: 'md',
                mode: 'md'
            }),
            IonicStorageModule.forRoot(),
        CloudModule.forRoot(cloudSettings),
        FormsModule,
        MomentModule,
        EnvironmentsModule,
        Ng2ImgFallbackModule
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        AuthPage,
        EventsPage,
        EventPage,
        ProfilePage,
        SettingsPage,
        EventBookComponent,
        EventsFilterComponent,
        SidenavComponent
    ],
    providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},
    Calendar,
    Diagnostic,
    Facebook,
    GooglePlus,
    DateFormatPipe,
    GoogleAnalytics,
    Keyboard,
    LaunchNavigator,
    { provide: Network, useClass: NetworkMock },
    SocialSharing,
    StatusBar,
    SplashScreen,
    EventsSrvc,
    AuthSrvc,
    CalendarSrvc,
    HelperSrvc,
    EventsSrvc,
    LocationSrvc,
    AppConfig]
})
export class AppModule {

}
</code>```

答:
So after banging the extend class logic into my head and understanding that it wasnt the correct way to break up my code. I went with an attribute based directives with @Hostlistener and @Input variables.

I was able to break up the parent component into much smaller sections and allow the parent component to hold all the variables and pass the updated values to the directives. I went from 1 component over 500 lines to multiple that dont go over 120. Much easier to read, to test and to maintain.

Body:
My parent component is too large to manage so I want to move the the functions into the separated child classes that extend the parent.

The parent class contains variables that need to be updated in the child classes as well as I have injected providers into the parent as well.

    @Component({
    selector: 'events-list',
    templateUrl: 'events-list.html'

})
export class EventsListComponent {
    filterString: string;
    infiniteScroll: any;
    refresher: any;
    eventsList: any[];
    selectedCategoriesList: [Category];
    pageNum: number;
    pageSize: number;
    searchText: string = '';
    noEvents: boolean;
    filterSearchText: string;
    filterStartDate: string;
    filterEndDate: string;
    tabsFilterValue: string = 'all'

    constructor(

        public authSrvc: AuthSrvc,
        public calendarSrvc: CalendarSrvc,
        public eventsSrvc: EventsSrvc,
        public helperSrvc: HelperSrvc,
        public locationSrvc: LocationSrvc,
        public pushSrvc: PushSrvc) {

    }

Above is my parent class

    import {Injectable} from '@angular/core';
import {Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/observable/of';
import {Observable} from 'rxjs/Observable';
import {ModalController, LoadingController, NavController, ToastController, Platform} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {DateFormatPipe} from 'angular2-moment';
import {Category} from '../../../app/app.interfaces';
import * as moment from 'moment';

/** Ionic Native **/
import {GoogleAnalytics} from '@ionic-native/google-analytics';
import {Network} from '@ionic-native/network';

/** Providers **/
import {AuthSrvc} from '../../../../providers/auth-srvc';
import {CalendarSrvc} from '../../../../providers/calendar-srvc';
import {EventsSrvc} from '../../../../providers/events-srvc';
import {HelperSrvc} from '../../../../providers/helper-srvc';
import {LocationSrvc} from '../../../../providers/location-srvc';
import {PushSrvc} from '../../../../providers/push-srvc';

/** Pages **/
import {AuthPage} from '../../../pages/auth/auth-page';

import {EventsListComponent} from '../../../events-components/events-list/events-list';

export class eventsInit extends EventsListComponent {

    constructor(
        loadingCtrl: LoadingController,
        toastCtrl: ToastController,
        modalCtrl: ModalController,
        navCtrl: NavController,
        platform: Platform,
        storage: Storage,

        ga: GoogleAnalytics,
        network: Network,

        authSrvc: AuthSrvc,
        calendarSrvc: CalendarSrvc,
        eventsSrvc: EventsSrvc,
        helperSrvc: HelperSrvc,
        locationSrvc: LocationSrvc,
        pushSrvc: PushSrvc

    ) {
        super(loadingCtrl,
        toastCtrl,
        modalCtrl,
        navCtrl,
        platform,
        storage,

        ga,
        network,

        authSrvc,
        calendarSrvc,
        eventsSrvc,
        helperSrvc,
        locationSrvc,
        pushSrvc);
    }

    ngOnInit()
    {
        console.log('test')
    }
}

Above is my child class

this is not working and is always failing with by parameters not being populated or the super call failing. What is the correct way to do this.

/** Update **/

If removing the injectable I always get the error Can't resolve all parameters for eventsInit: (?, ?, ?, ?, ?, ?).

Below is my main module

    import {NgModule, ErrorHandler} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {Ng2ImgFallbackModule} from 'ng2-img-fallback';
import {CloudSettings, CloudModule} from '@ionic/cloud-angular';
import {MomentModule,DateFormatPipe} from 'angular2-moment';
import { IonicStorageModule } from '@ionic/storage';

import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {EnvironmentsModule} from '../environment_variables/environment_variables.module'
import {AppConfig} from '../app/app.config';
import {MyApp} from '../app/app.component';

/** Ionic Native **/
import {Calendar} from '@ionic-native/calendar';
import { Diagnostic } from '@ionic-native/diagnostic';
import {Facebook} from '@ionic-native/facebook';
import {GooglePlus} from '@ionic-native/google-plus';
import { GoogleAnalytics } from '@ionic-native/google-analytics';
import { Keyboard } from '@ionic-native/keyboard';
import { LaunchNavigator, LaunchNavigatorOptions } from '@ionic-native/launch-navigator';
import {Network} from '@ionic-native/network';
import { SocialSharing } from '@ionic-native/social-sharing';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

/** Pages **/
import {AuthPage} from '../pages/auth/auth-page';
import {EventsPage} from '../pages/events/events-page';
import {EventPage} from '../pages/event/event-page';
import {ProfilePage} from '../pages/profile/profile';
import {SettingsPage} from '../pages/settings/settings';

/** Components **/
//Auth
import {LoginComponent} from '../components/auth-components/login/login';
import {ForgotPasswordDirective} from '../components/auth-components/forgot-password';
import {RegisterComponent} from '../components/auth-components/register/register';
import {SocialComponent} from '../components/auth-components/social/social';
import {WalkthroughComponent} from '../components/auth-components/walkthrough/walkthrough';
//Base
import {SidenavComponent} from '../components/sidenav/sidenav';
import {TimeslotFilterComponent} from '../components/timeslot-filter/timeslot-filter';
import {SettingsComponent} from '../components/settings/settings';
import {EventBookComponent} from '../components/event-book/event-book';
//Events
import {EventsFilterComponent} from '../components/events-components/events-filter/events-filter';
import {EventsListComponent} from '../components/events-components/events-list/events-list';
    /** Events Extensions **/
    import {eventsInit} from '../components/events-components/events-list/extensions/events-init';
import {EventsItemComponent} from '../components/events-components/events-item/events-item';
//Event
import {AttendeesListComponent} from '../components/event-components/attendees-list/attendees-list';
import {AttendeesItemComponent} from '../components/event-components/attendees-item/attendees-item';
//Profile
import {ProfileComponent} from '../components/profile/profile';

import {ParallaxHeaderDirective} from '../components/parallax-header';

/** Providers **/
import {EventsSrvc} from '../providers/events-srvc';
import {AuthSrvc} from '../providers/auth-srvc';
import {CalendarSrvc} from '../providers/calendar-srvc';
import {HelperSrvc} from '../providers/helper-srvc';
import {LocationSrvc} from '../providers/location-srvc';
import {PushSrvc} from '../providers/push-srvc';

/** Pipes **/
import {LimitToPipe} from '../pipes/limitTo'

const cloudSettings: CloudSettings = {
    'core': {
        'app_id': 'df0d4e63'
    }
};

class NetworkMock extends Network {
 get type(): string {
    return (super['type'] === null) ? "wifi" : super['type'];
  }
}

@NgModule({
    declarations: [
        MyApp,
        AuthPage,
        LoginComponent,
        ForgotPasswordDirective,
        ParallaxHeaderDirective,
        RegisterComponent,
        SocialComponent,
        WalkthroughComponent,
        SidenavComponent,
        EventsPage,
        EventsListComponent,
        eventsInit,
        EventsItemComponent,
        EventsFilterComponent,
        AttendeesListComponent,
        AttendeesItemComponent,
        EventPage,
        ProfilePage,
        ProfileComponent,
        SettingsPage,
        SettingsComponent,
        TimeslotFilterComponent,
        EventBookComponent,
        LimitToPipe,
    ],
    imports: [
        IonicModule.forRoot(MyApp,
            {
                backButtonText: 'Back',
                backButtonIcon: 'arrow-back',
                iconMode: 'md',
                modalEnter: 'modal-slide-in',
                modalLeave: 'modal-slide-out',
                tabsPlacement: 'bottom',
                pageTransition: 'md',
                mode: 'md'
            }),
            IonicStorageModule.forRoot(),
        CloudModule.forRoot(cloudSettings),
        FormsModule,
        MomentModule,
        EnvironmentsModule,
        Ng2ImgFallbackModule
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        AuthPage,
        EventsPage,
        EventPage,
        ProfilePage,
        SettingsPage,
        EventBookComponent,
        EventsFilterComponent,
        SidenavComponent
    ],
    providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},
    Calendar,
    Diagnostic,
    Facebook,
    GooglePlus,
    DateFormatPipe,
    GoogleAnalytics,
    Keyboard,
    LaunchNavigator,
    { provide: Network, useClass: NetworkMock },
    SocialSharing,
    StatusBar,
    SplashScreen,
    EventsSrvc,
    AuthSrvc,
    CalendarSrvc,
    HelperSrvc,
    EventsSrvc,
    LocationSrvc,
    AppConfig]
})
export class AppModule {

}


问:
UITableView not displaying data correctly with Index in Swift 3
I have a UITableView in my app project which pulls data from a Array. Also this data has to be indexed. But for some reason the data does not display in the appropriate sections i.e A, B etc. I can't seem to see whats wrong. My data so far is:

```<code>import Foundation
import UIKit

class uniVC: UITableViewController {

    let university = ["Allcat University", "Allday University", "Bejnamin University", "Cat University"]

    var universitySections = [String]()
    var wordsDict = [String:[String]]()

    let wordIndexTitles = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

    func generateWordsDict() {

        for word in university {

            let key = "\(word[word.startIndex])"
            let lower = key.lowercased()

            if var wordValues = wordsDict[lower] {
                wordValues.append(word)
                wordsDict[lower] = wordValues
            } else {
                wordsDict[lower] = [word]
            }

        }

        universitySections = [String](wordsDict.keys)
        universitySections = universitySections.sorted()

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        generateWordsDict()

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
        //Dispose
    }

    // Mark table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return universitySections.count
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return universitySections[section]
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let wordKey = universitySections[section]
        if let wordValues = wordsDict[wordKey] {
            return wordValues.count
        }

        return 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let wordKey = universitySections[indexPath.section]
        if wordsDict[wordKey.lowercased()] != nil {

            cell.textLabel?.text = university[indexPath.row]

        }

        return cell
    }

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return wordIndexTitles
    }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {

        guard let index = universitySections.index(of: title) else {
            return -1
        }

        return index

    }
}
</code>```

Any ideas on this one?

答:
All of things were fine, excepted:

```<code>if wordsDict[wordKey.lowercased()] != nil {
    cell.textLabel?.text = university[indexPath.row]
}
</code>```

I think you made a mistake. Let change to:

```<code>if let wordValues = wordsDict[wordKey] {
    cell.textLabel?.text = wordValues[indexPath.row]
}
</code>```

This is the result:

Body:
I have a UITableView in my app project which pulls data from a Array. Also this data has to be indexed. But for some reason the data does not display in the appropriate sections i.e A, B etc. I can't seem to see whats wrong. My data so far is:

import Foundation
import UIKit

class uniVC: UITableViewController {

    let university = ["Allcat University", "Allday University", "Bejnamin University", "Cat University"]

    var universitySections = [String]()
    var wordsDict = [String:[String]]()

    let wordIndexTitles = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

    func generateWordsDict() {

        for word in university {

            let key = "\(word[word.startIndex])"
            let lower = key.lowercased()

            if var wordValues = wordsDict[lower] {
                wordValues.append(word)
                wordsDict[lower] = wordValues
            } else {
                wordsDict[lower] = [word]
            }

        }

        universitySections = [String](wordsDict.keys)
        universitySections = universitySections.sorted()

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        generateWordsDict()

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()
        //Dispose
    }

    // Mark table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return universitySections.count
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return universitySections[section]
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let wordKey = universitySections[section]
        if let wordValues = wordsDict[wordKey] {
            return wordValues.count
        }

        return 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let wordKey = universitySections[indexPath.section]
        if wordsDict[wordKey.lowercased()] != nil {

            cell.textLabel?.text = university[indexPath.row]

        }

        return cell
    }

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return wordIndexTitles
    }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {

        guard let index = universitySections.index(of: title) else {
            return -1
        }

        return index

    }
}

Any ideas on this one?

Body:
All of things were fine, excepted:

if wordsDict[wordKey.lowercased()] != nil {
    cell.textLabel?.text = university[indexPath.row]
}

I think you made a mistake. Let change to:

if let wordValues = wordsDict[wordKey] {
    cell.textLabel?.text = wordValues[indexPath.row]
}

This is the result:


问:
WooCommerce custom sort (multiple condition)
I am trying to sort products on woocommerce in the following conditions:

unavailable products goes down

rest of products should be ordered randomly

I tried several ways, but the problem is that randomizing first would be lost after availability order, availability first would be lost after randomizing.

Any solution?

答:
You will need to add custom sorting option to products. You can do this by this way:

```<code>function vi_custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['alphabetical'] = 'Sort by name: custom';
    return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'vi_custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'vi_custom_woocommerce_catalog_orderby' );

//Add Alphabetical sorting option to shop page / WC Product Settings
function vi_alphabetical_woocommerce_shop_ordering( $sort_args ) {
  $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

    if ( 'alphabetical' == $orderby_value ) {
        $sort_args['orderby'] = 'meta_value_num';
        $sort_args['order'] = 'asc';
        $sort_args['meta_key'] = '';
    }

    return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'vi_alphabetical_woocommerce_shop_ordering' );
</code>```

For products, which are available, you can assign "> 0" values and for all non-available products, you can assign 0. So they will be automatically sorted and will be gone to bottom.

Body:
You will need to add custom sorting option to products. You can do this by this way:

function vi_custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['alphabetical'] = 'Sort by name: custom';
    return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'vi_custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'vi_custom_woocommerce_catalog_orderby' );

//Add Alphabetical sorting option to shop page / WC Product Settings
function vi_alphabetical_woocommerce_shop_ordering( $sort_args ) {
  $orderby_value = isset( $_GET['orderby'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

    if ( 'alphabetical' == $orderby_value ) {
        $sort_args['orderby'] = 'meta_value_num';
        $sort_args['order'] = 'asc';
        $sort_args['meta_key'] = '';
    }

    return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'vi_alphabetical_woocommerce_shop_ordering' );

For products, which are available, you can assign "> 0" values and for all non-available products, you can assign 0. So they will be automatically sorted and will be gone to bottom.


问:
Database design a simple database for a functional school
So i am having a little trouble in coming up with the entity-relationships for my database however i have some of the design process done be that of minimum caliber. The database will be created so that students can have many courses many to many relationship (obvious i know). The database will need to keep track of homework and attendence daily. However, classes can be just one day of the week or many days.

advisors->(advisorid, firstname, lastname, phone , email)

students->(studentid,firstname, lastname, phone, email)

courses->(courseid, description, startdate, statetime, room)

studentscourses->(studentid, courseid)

Here i am stuck, i am thinking of creating a calendar table, but how will i correlate the data to the homework table and with attendance. If any suggestions that would be great criticism is welcome.

答:
You need to create some more entities to achieve an efficient database design. One solution would be:</p>

```<code>Attendance(id,student_id,course_id,date)

Homework(id, course_offering_id, date) -- course_offering_id: primary key of student courses

-- since many to many relation lies between homework and student
Homework_Student(id, homework_id, student_id)
</code>```

Body:
You need to create some more entities to achieve an efficient database design. One solution would be:

Attendance(id,student_id,course_id,date)

Homework(id, course_offering_id, date) -- course_offering_id: primary key of student courses

-- since many to many relation lies between homework and student
Homework_Student(id, homework_id, student_id)


问:
how to do multiple sums in single query
let's say that I have this tables :

table num1 :

```<code>+----+-----+
| no | val |
+----+-----+
| 1  | 10  |
| 2  | 15  |
| 3  | 20  |
+----+-----+
</code>```

table num2:

```<code>+----+-----+
| no | tot |
+----+-----+
| 1  | 15  |
| 2  | 20  |
| 3  | 25  |
+----+-----+
</code>```

so, i want to select sum value of table nu1.val and table num2.tot in single query

```<code> Select sum(a.val),sum(b.tot) from num1 a, num2 b
</code>```

the query is not working
please help

答:
select Sum((select sum(col_name) from table_name)+(select sum(col_name) from table_name));
Tested BY :- Rahul Panwar</p>

Title: how to do multiple sums in single query

Body:
let's say that I have this tables :

table num1 :

+----+-----+
| no | val |
+----+-----+
| 1  | 10  |
| 2  | 15  |
| 3  | 20  |
+----+-----+

table num2:

+----+-----+
| no | tot |
+----+-----+
| 1  | 15  |
| 2  | 20  |
| 3  | 25  |
+----+-----+

so, i want to select sum value of table nu1.val and table num2.tot in single query

 Select sum(a.val),sum(b.tot) from num1 a, num2 b

the query is not working
please help


问:
importing java com.google.* libraries
I am having issues importing com.google.* libraries.

I am very new to eclipse and do not know how to import these libraries to fix my code errors. Can someone point me in the right direction to importing these libraries?

答:
The following line:

```<code>import com.google.*;
</code>```

should do just fine. However, keep this in mind,

Doing import com.google.* does not import for instance import com.google.appengine.*

You need to have com.google.* on your class path. (Right click on the project and select "Configure class path" to add possibly missing jars / libraries.)

Title: importing java com.google.* libraries

Body:
The following line:

import com.google.*;

should do just fine. However, keep this in mind,

Doing import com.google.* does not import for instance import com.google.appengine.*

You need to have com.google.* on your class path. (Right click on the project and select "Configure class path" to add possibly missing jars / libraries.)

ContentLicense: CC BY-SA 2.5


问:
GitLab CI build sub-projects and deploy them to kubernetes separately
If I have a GitLab project, which contains several sub-folders:

two with java code (from java:alpine, to compile with maven and build containers)

one with nginx config (from openresty:alpine, to build a web server container)

Every of sub-projects has a Dockerfile, deployment.yml, and gitlab-ci.yml.

deployment.yml is similar for every of sub-folders in the project, as all the sub-projects results to a single multi-container kubernetes pod.

How can I set up this project to build and deploy to kubernetes only the container, which I edited by the last commit?

答:
I used a dirty hack like setting several build blocks in .gitlab-ci.yml for every sub-project and setting for every on them only parameter:

```<code>maven-build-akka:
  image: maven:3-jdk-8
  stage: build
  only:
    - /^akka-.*$/
  script:
    - cd akka
    - mvn package -B --settings ../settings.xml
  artifacts:
    paths:
      - akka/target/*.jar
</code>```

And so for docker build stage.

After that, if I push a tag like akka-1.0.3, appropriate pipeline jobs would be launched.

But, there's an issue with only one name for images in GitLab CI registry for a single project, so you should push images somewhere else (GCR, etc.)

Body:
I used a dirty hack like setting several build blocks in .gitlab-ci.yml for every sub-project and setting for every on them only parameter:

maven-build-akka:
  image: maven:3-jdk-8
  stage: build
  only:
    - /^akka-.*$/
  script:
    - cd akka
    - mvn package -B --settings ../settings.xml
  artifacts:
    paths:
      - akka/target/*.jar

And so for docker build stage.

After that, if I push a tag like akka-1.0.3, appropriate pipeline jobs would be launched.

But, there's an issue with only one name for images in GitLab CI registry for a single project, so you should push images somewhere else (GCR, etc.)


问:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'table_Name'
i've checked again and again , but couldn't find any error  </p>

```<code>private void Btn_Save_Click(object sender, EventArgs e)
    {

        SqlConnection c = new SqlConnection(conn);

                c.Open();
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    query = @"INSERT INTO '" + tbpg.Text + "' VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";

                }
        SqlCommand cmd = new SqlCommand(query,c);
        cmd.ExecuteNonQuery();
</code>```

答:
With such a mass of string connactions, you need to output the final value of query during debugging. Otherwise you are basically guessing how it looks.

I did notice a difference in this line:

```<code>+ dgv.Rows[i].Cells["Date"].Value + ","
</code>```

You are using i, rather then 0.

But generally building queries via string connaction is not a good idea. You should be use Parametized Queries. Otherwise you end up on the wrong side of this joke:
https://xkcd.com/327/

Body:
i've checked again and again , but couldn't find any error

private void Btn_Save_Click(object sender, EventArgs e)
    {

        SqlConnection c = new SqlConnection(conn);

                c.Open();
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    query = @"INSERT INTO '" + tbpg.Text + "' VALUES ("
                        + dgv.Rows[0].Cells["Sno"].Value + ", "
                        + dgv.Rows[i].Cells["Date"].Value + ","
                        + dgv.Rows[0].Cells["Particulars"].Value + ", "
                        + dgv.Rows[0].Cells["Credit"].Value + ", "
                        + dgv.Rows[0].Cells["Debit"].Value + ","
                        + dgv.Rows[0].Cells["Balance"].Value +
                        ");";

                }
        SqlCommand cmd = new SqlCommand(query,c);
        cmd.ExecuteNonQuery();

Body:
With such a mass of string connactions, you need to output the final value of query during debugging. Otherwise you are basically guessing how it looks.

I did notice a difference in this line:

+ dgv.Rows[i].Cells["Date"].Value + ","

You are using i, rather then 0.

But generally building queries via string connaction is not a good idea. You should be use Parametized Queries. Otherwise you end up on the wrong side of this joke:
https://xkcd.com/327/


问:
Hibernate cannot merge and persist two instances of entity class
When I try to update Team Hibernate throws exception:

```<code>    Multiple representations of the same entity [Team#1] are being merged.
 Detached: [Team@49a0aef3]; Managed: [Team@bf505c]
</code>```

TeamDAOImpl

```<code>    public void updateTeam(Team team) {
            Team teamToUpdate = getTeam(team.getId());
            teamToUpdate.setName(team.getName());
            team = null; // doesn't help to avoid exception
            getCurrentSession().merge(teamToUpdate);
        }
    public Team getTeam(int id) {
        Team team = (Team) getCurrentSession().get(Team.class, id);
        return team;
    }
</code>```

I have seen most issues related to this exception but haven't found solution that works. How to fix it?

Update:

It seems to be some kind of bug the Hibernate team had to fix. In my case the logic is extremely trivial, I cannot believe Hibernate unable to update current entity. There has to be a way.

答: Fixed it by removing CascadeType from source entity.

Body:
When I try to update Team Hibernate throws exception:

    Multiple representations of the same entity [Team#1] are being merged.
 Detached: [Team@49a0aef3]; Managed: [Team@bf505c]

TeamDAOImpl

    public void updateTeam(Team team) {
            Team teamToUpdate = getTeam(team.getId());
            teamToUpdate.setName(team.getName());
            team = null; // doesn't help to avoid exception
            getCurrentSession().merge(teamToUpdate);
        }
    public Team getTeam(int id) {
        Team team = (Team) getCurrentSession().get(Team.class, id);
        return team;
    }

I have seen most issues related to this exception but haven't found solution that works. How to fix it?

Update:

It seems to be some kind of bug the Hibernate team had to fix. In my case the logic is extremely trivial, I cannot believe Hibernate unable to update current entity. There has to be a way.


问:
python regex to match both english and telugu/devanagari words
I need some help in getting words from a mix of language it contains english and telugu language, here is my code so far

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
sentence="hello world యూనియన్ యూనియన్"
sentence=sentence.decode('utf-8')
for m in re.finditer(ur'(\w|\’\w|\'\w)+', sentence, re.UNICODE):
    start, end = m.span()
    word = m.group().encode('utf-8')
    print start, end, word
</code>```

the result i'm expecting is

```<code>0 5 hello
6 11 world
11 17 యూనియన్
17 23 యూనియన్
</code>```

but the result i get is

```<code>0 5 hello
6 11 world
12 13 య
14 15 న
16 18 యన
20 21 య
22 23 న
24 26 యన
</code>```

the code split every character of the langauge and give independent start and end lengths. is there any way that i can get the result in the above format as words instead of characters

答:
I strongly suggest you to avoid using regex on non UTF characters it may seriously go out of your control. Why don't you just build some custom method using string properties and methods?

Here what I would do:

```<code>sentence="hello world యూనియన్ యూనియన్"
res = sentence.split();
last_index = 0;
for word in res:
    start = sentence.index(word, last_index )
    end = start + len(word)
    last_index = end
    print(start, end, word)
</code>```

You can take a look at the example running here.

ContentLicense: CC BY-SA 4.0

Body:
I need some help in getting words from a mix of language it contains english and telugu language, here is my code so far

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
sentence="hello world యూనియన్ యూనియన్"
sentence=sentence.decode('utf-8')
for m in re.finditer(ur'(\w|\’\w|\'\w)+', sentence, re.UNICODE):
    start, end = m.span()
    word = m.group().encode('utf-8')
    print start, end, word

the result i'm expecting is

0 5 hello
6 11 world
11 17 యూనియన్
17 23 యూనియన్

but the result i get is

0 5 hello
6 11 world
12 13 య
14 15 న
16 18 యన
20 21 య
22 23 న
24 26 యన

the code split every character of the langauge and give independent start and end lengths. is there any way that i can get the result in the above format as words instead of characters

Body:
I strongly suggest you to avoid using regex on non UTF characters it may seriously go out of your control. Why don't you just build some custom method using string properties and methods?

Here what I would do:

sentence="hello world యూనియన్ యూనియన్"
res = sentence.split();
last_index = 0;
for word in res:
    start = sentence.index(word, last_index )
    end = start + len(word)
    last_index = end
    print(start, end, word)

You can take a look at the example running here.


问:
Encoding URL with German Characters
In my app I receive a URL such as

```<code>http://www.wassersportlotse.de/php/lib/smart_image_resizer/image.php/Mühlendammschleuse.jpg?image=/media/images/uploads/Mühlendammschleuse.jpg
</code>```

When there are no German characters in the fullurl I can just use it without encoding and it works fine. However if I receive a URL such as the one above it doesn't work (the ü is causing the problem). Below I have tried to encode the seperate parts of the URI to no avail. As alway advice is very much appreciated.

```<code>public ImageDownloader(String fullurl) throws URISyntaxException{
    URI uri = new URI(fullurl);

    path = uri.getPath();
    path = URLEncoder.encode(path);

    query = uri.getQuery();
    query = URLEncoder.encode(query);

    auth = uri.getAuthority();

    url = "http://" + auth + path + query;

}
</code>```

答:
Have your tried unsing:

```<code>android.net.Uri.encode(urlString, ":/");
</code>```

It encodes the string but skips ":" and "/".

Title: Encoding URL with German Characters

Body:
In my app I receive a URL such as

http://www.wassersportlotse.de/php/lib/smart_image_resizer/image.php/Mühlendammschleuse.jpg?image=/media/images/uploads/Mühlendammschleuse.jpg

When there are no German characters in the fullurl I can just use it without encoding and it works fine. However if I receive a URL such as the one above it doesn't work (the ü is causing the problem). Below I have tried to encode the seperate parts of the URI to no avail. As alway advice is very much appreciated.

public ImageDownloader(String fullurl) throws URISyntaxException{
    URI uri = new URI(fullurl);

    path = uri.getPath();
    path = URLEncoder.encode(path);

    query = uri.getQuery();
    query = URLEncoder.encode(query);

    auth = uri.getAuthority();

    url = "http://" + auth + path + query;

}

Body:
Have your tried unsing:

android.net.Uri.encode(urlString, ":/");

It encodes the string but skips ":" and "/".


问:
How to hide and show modal boxes in angular2
I used the ng2 modal but it is not getting opened or hide through ts,
my template,

```<code>    <modal  id='saveeditsmodal'>
  <modal-header>
        <h4 class="modal-title">Editing item(s) in Recently Viewed</h4>
       </modal-header>
      <!-- Modal content-->
      <modal-content>
        <div class="modal-body">
          <p>You have unsaved changes.</p>
        </div>
         <div class="modal-body">
          <p>Are you sure you want to discard these changes?</p>
        </div>
               </modal-content>
     <modal-footer>
          <button type="button" class="btn btn-primary" data-dismiss="modal">Stay On List</button>
          <button type="button" class="btn btn-default" data-dismiss="modal" (click)='closebox()'>Discard</button>
  </modal-footer>
  </modal>
</code>```

My ts,

```<code>$('#saveeditsmodal').show();
</code>```

Actually this is ng2 model ,i am not sure about the process to hide or show,can anyone suggest help.Thanks.

答:
Better way of doing is:

Template Side :

```<code><modal  id='saveeditsmodal' #saveEditModal>
.....
</modal>

<button (click)='saveEditModal.open()'>Show Modal</button>
<button (click)='saveEditModal.close()'>Hide Modal</button>
</code>```

Component Side :

```<code>@ViewChild('saveEditModal') saveEditModal;
......
this.saveEditModal.open();
this.saveEditModal.close();
</code>```

Body:
I used the ng2 modal but it is not getting opened or hide through ts,
my template,

    <modal  id='saveeditsmodal'>
  <modal-header>

Editing item(s) in Recently Viewed

       </modal-header>

      <modal-content>

You have unsaved changes.

Are you sure you want to discard these changes?

               </modal-content>
     <modal-footer>
          <button type="button" class="btn btn-primary" data-dismiss="modal">Stay On List</button>
          <button type="button" class="btn btn-default" data-dismiss="modal" (click)='closebox()'>Discard</button>
  </modal-footer>
  </modal>

My ts,

$('#saveeditsmodal').show();

Actually this is ng2 model ,i am not sure about the process to hide or show,can anyone suggest help.Thanks.

Body:
Better way of doing is:

Template Side :

<modal  id='saveeditsmodal' #saveEditModal>
.....
</modal>

<button (click)='saveEditModal.open()'>Show Modal</button>
<button (click)='saveEditModal.close()'>Hide Modal</button>

Component Side :

@ViewChild('saveEditModal') saveEditModal;
......
this.saveEditModal.open();
this.saveEditModal.close();


问:
TokenMismatchException when posting a form using laravel5.4
TokenMismatchException in VerifyCsrfToken.php line 68,when i try to post a form.

```<code><form method="post" action="url('add')" >
{{ csrf_field() }}
<input type="text" name="title" />
<input type="submit" value="Add" />
</form>
</code>```

Its was working fine before i added this package.

答:
Instead of {{ Form::open() }} either you can manually add hidden input field in the form just like Andranik Petrosyan suggested

But still I would like you to try

{!! csrf_field() !!} instead of {{ csrf_field() }}

Body:
TokenMismatchException in VerifyCsrfToken.php line 68,when i try to post a form.

<form method="post" action="url('add')" >
{{ csrf_field() }}
<input type="text" name="title" />
<input type="submit" value="Add" />
</form>

Its was working fine before i added this package.


问:
Semi-transparency in ActionScript 3.0 shapes?
I'm trying to make a modal pop up in my Flash application, not unlike the ASP.NET version seen here.

I've already got the dialog box made, but I'm trying to add a semi-transparent gray rectangle over everything behind the pop-up, again like the one used in ASP.NET.  Is there a way to do this in ActionScript? It needs to be semi-transparent, not fully, so you can still partially see what's behind it.  I'm assuming you could apply this property to a Shape class somehow, but I can't figure it out.

Thanks in advance for the help.

答:
Use the "alpha" property of the Shape class
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/DisplayObject.html#alpha</p>


问:
editButtonItem doesn't change Edit/Done title
I use a default Bar Button Item editButtonItem here:

```<code>@property (nonatomic, assign) BOOL isEditing;

- (void)viewDidLoad {
  [super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self setupInterface];
}

- (void)setupInterface {
    if (self.dataElement) {
        self.isEditing = NO;
        self.nameTextField.text = self.dataElement.name;;
    } else {
      self.isEditing = YES;
      self.deleteButton.hidden = YES;
    }
  }

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
  editing = self.isEditing;
  [super setEditing:editing animated:YES];
  if (editing) {
    [self saveAction];
    [self.navigationController popViewControllerAnimated:YES];
  } else {
    self.isEditing = !self.isEditing;
  }
}

- (void)setIsEditing:(BOOL)isEditing {
  _isEditing = isEditing;

    if (isEditing) {
      self.deleteButton.hidden = NO;
      self.nameTextField.userInteractionEnabled = YES;
    } else {
      self.deleteButton.hidden = YES;
      self.nameTextField.userInteractionEnabled = NO;
    }
}
</code>```

However it doesn't change title of a button from Edit to Done.
I know, that it can be changed automatically and don't want to assign it like:
self.editButtonItem.title = @"Done";

答:
to change the navigationItem button into Done button use this,

```<code>[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleDone];
</code>```

to change the navigationItem button into Edit button use this,

```<code>[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleBordered];
</code>```

If you have added the button through IB Storyboard, then make sure to set the identifier. Then add in your code do the following:

```<code>editButton.title = @"Done";
//or
editButton.title = @"Edit";
</code>```

Body:
I use a default Bar Button Item editButtonItem here:

@property (nonatomic, assign) BOOL isEditing;

- (void)viewDidLoad {
  [super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self setupInterface];
}

- (void)setupInterface {
    if (self.dataElement) {
        self.isEditing = NO;
        self.nameTextField.text = self.dataElement.name;;
    } else {
      self.isEditing = YES;
      self.deleteButton.hidden = YES;
    }
  }

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
  editing = self.isEditing;
  [super setEditing:editing animated:YES];
  if (editing) {
    [self saveAction];
    [self.navigationController popViewControllerAnimated:YES];
  } else {
    self.isEditing = !self.isEditing;
  }
}

- (void)setIsEditing:(BOOL)isEditing {
  _isEditing = isEditing;

    if (isEditing) {
      self.deleteButton.hidden = NO;
      self.nameTextField.userInteractionEnabled = YES;
    } else {
      self.deleteButton.hidden = YES;
      self.nameTextField.userInteractionEnabled = NO;
    }
}

However it doesn't change title of a button from Edit to Done.
I know, that it can be changed automatically and don't want to assign it like:
self.editButtonItem.title = @"Done";

Body:
to change the navigationItem button into Done button use this,

[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleDone];

to change the navigationItem button into Edit button use this,

[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleBordered];

If you have added the button through IB Storyboard, then make sure to set the identifier. Then add in your code do the following:

editButton.title = @"Done";
//or
editButton.title = @"Edit";


问:
Prevent tooltip in converting HTML Entities

<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />```

The above code for tooltip displays "PROJECT>". But what I need is to display the text as is "PROJECT&GT"

Is there a way to do this? I'm using angular.

答:
you can try something like this:
create angular filter :

```<code>angular.module('ppvApp.event').filter('escapeHtml', function() {

    var charMap= {
        "&": "&",
        "<": "<",
        ">": ">",
        '"': '"',
        "'": ''',
        "/": '/'
    };

    return function(str) {
        return String(str).replace(/[&<>"'\/]/g, function(s) {
            return charMap[s];
        });
    }
});
</code>```

and then use it as:

```<code> <input ng-model="test" placeholder="pre" type="text" title="{{'PROJECT&GT' | escapeHtml}}" />
</code>```

Body:
<input ng-model="test" placeholder="pre" type="text" title="PROJECT&GT" />

The above code for tooltip displays "PROJECT>". But what I need is to display the text as is "PROJECT&GT"

Is there a way to do this? I'm using angular.

Body:
you can try something like this:
create angular filter :

angular.module('ppvApp.event').filter('escapeHtml', function() {

    var charMap= {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
    };

    return function(str) {
        return String(str).replace(/[&<>"'\/]/g, function(s) {
            return charMap[s];
        });
    }
});

and then use it as:

 <input ng-model="test" placeholder="pre" type="text" title="{{'PROJECT&GT' | escapeHtml}}" />


问:
How do I know when a copy job is done?
I'm using

```<code>File.Copy(source, dest);
</code>```

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?

答: File.Copy is not asynchronous.  It has completed when the call finishes.

Title: How do I know when a copy job is done?

Body:
I'm using

File.Copy(source, dest);

I need to know when this copy job is done processing so that it can move on to another task.

Is there any callback function I could use in this particular case?


问:
How to change font in webview for loadRequest
```<code>- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *string = [NSString stringWithFormat:@"document.body.style.zoom = %@;", [UIFont fontWithName:centuryGothicBold size:5]];
    [self.longNewsWebView stringByEvaluatingJavaScriptFromString:string];
}
</code>```

答:
Finally got a answer for my question  after long research

```<code>- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self stopProgressHUD];
NSString *cssString = [[[[@"body { font-family:" stringByAppendingString:centuryGothicRegular] stringByAppendingString:@"; font-size:"] stringByAppendingString:[NSString stringWithFormat:@"%ld",normalFont]] stringByAppendingString:@"}\""] ; //1

NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; // 2
NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString]; // 3
NSLog(@"javascriptWithCSSString: \n %@", javascriptWithCSSString);
NSString *loadedContent = [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString];
NSLog(@"loaded ocntent: %@", loadedContent);
</code>```

}

centuryGothicRegular is the name of font which where declare as constant.
  normalFont is font size which is also declare as integer constant

Body:
Finally got a answer for my question  after long research

- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self stopProgressHUD];
NSString *cssString = [[[[@"body { font-family:" stringByAppendingString:centuryGothicRegular] stringByAppendingString:@"; font-size:"] stringByAppendingString:[NSString stringWithFormat:@"%ld",normalFont]] stringByAppendingString:@"}\""] ; //1

NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; // 2
NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString]; // 3
NSLog(@"javascriptWithCSSString: \n %@", javascriptWithCSSString);
NSString *loadedContent = [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString];
NSLog(@"loaded ocntent: %@", loadedContent);

}

centuryGothicRegular is the name of font which where declare as constant.
  normalFont is font size which is also declare as integer constant


问:
Angular2 applying Pipe after data is received
I have an Object that is used to manage the data received from the back end.
It is initiated with all the fields as display: false, and if I receive that specific field from the server, I will eventually change it to true.

filterGroups (initial):

```<code>export let filterGroups: any = {
    genericFilters: {
        iboId: {
            'display': false,
            'template': ''
        },
        iboCode: {
            'display': false,
            'template': 'text/iboCode'
        },
        iboName: {
            'display': false,
            'template': 'text_input_iboName'
        },
        iboSurname: {
            'display': false,
            'template': 'text_input_iboSurname'
        },
        iboRank: {
            'display': false,
            'template': 'select/multi_iboRank',
        },
        iboEmail: {
            'display': false,
            'template': 'text_input_iboEmail'
        },
        iboNewsletter: {
            'display': false,
            'template': 'select/simple_iboNewsletter',
        },
    },
    orderFilters: {
        iboTotalOrders: {
            'display': false,
            'template': 'compound/iboTotalOrders',
        }
    },
    peFilters: {
        iboTotalPE: {
            'display': false,
            'template': 'checkbox/iboTotalPE',
        }
    },
};
</code>```

In my template, I want to have as many div as filter groups. In this case we have 3 filter groups: genericFilters, orderFilters and peFilters.

This Object will be modified as soon as I receive data from the server (which I call in my constructor).

And so, my filterGroups will look like this after I have received the data from my async call.

filterGroups (after async call):

```<code>export let filterGroups: any = {
    genericFilters: {
        iboId: {
            'display': true,
            'template': ''
        },
        iboCode: {
            'display': true,
            'template': 'text/iboCode'
        },
        iboName: {
            'display': true,
            'template': 'text_input_iboName'
        },
        iboSurname: {
            'display': true,
            'template': 'text_input_iboSurname'
        },
        iboRank: {
            'display': false,
            'template': 'select/multi_iboRank',
        },
        iboEmail: {
            'display': true,
            'template': 'text_input_iboEmail'
        },
        iboNewsletter: {
            'display': false,
            'template': 'select/simple_iboNewsletter',
        },
    },
    orderFilters: {
        iboTotalOrders: {
            'display': true,
            'template': 'compound/iboTotalOrders',
        }
    },
    peFilters: {
        iboTotalPE: {
            'display': false,
            'template': 'checkbox/iboTotalPE',
        }
    },
};
</code>```

Now, in my template I have this:

Template (HTML):

```<code><div *ngFor="let group of filterGroups | keysCheckDisplay">
    <div>
        <h4>{{group.key}}</h4>
    </div>
</div>
</code>```

And, obviusly, here is my @Pipe.

@Pipe:

```<code>import { PipeTransform, Pipe } from '@angular/core';
import { isNullOrUndefined } from 'util';

@Pipe({name: 'keysCheckDisplay'})
export class KeysCheckDisplayPipe implements PipeTransform {
    transform(value, args: string[]): any {
        let keys = [];
        for (let key in value) {
            if (!isNullOrUndefined(value[key])) {
                let display = false;
                for (let keyChild in value[key]) {
                    if (!isNullOrUndefined(value[key][keyChild]) && value[key][keyChild]['display'] === true) {
                        display = true;
                        break;
                    }
                }
                if (display === true) {
                    keys.push({key: key, value: value[key]});
                }
            }
        }
        return keys;
    }
}
</code>```

In this @Pipe as you can see I do several things:

Loop through the filterGroups object

Check for each group within the object if exists a child with display: true.

The functionality:

I want this @Pipe to loop through my Objectand return me the 'filter groups' that have at least 1 element with display: true.

The Issue:

The @Pipe is getting the first version of the filterGroups object, and is ignoring the fact that the object changes as soon as I receive the data from the server.

The @Pipe works fine if I modify the initial values of the filterGroups object.

What I have tried:

Research, research, research

I changed the @Pipe to inpure, but I hate this solution because of awful performance and also it entered an infinite loop.

I have also tried this approach:
*ngFor="let group of filterGroups | async | keysCheckDisplay".
But it throwed the following error:

Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

Possible solutions?

Modify the @Pipe?

Modify the initial object?

Create a second @Pipe to loop through the first Pipe's result?

I hope it was detailed and clear, if not, please don't esitate to comment asking for more details and I will gladly update the post.

Thank you beforehand!

答:
A pure pipe is only called when the data changes. This means when "data" is a new object instance. If only the content of the object is modified, then Angular change detection won't recognize it as change and won't call the pipe.

Possible approaches

make the pipe impure: usually quite a burden for performance

copy the object like:

```<code>var tmp = this.data; this.data = {}; Object.assign(this.data, tmp);
</code>```

add an additional parameter to the pipe and update the parameter value

```<code>*ngFor="let item of data | myPipe:counter"
</code>```

```<code>// updated `data`
// this.counter++;
</code>```

Body:
I have an Object that is used to manage the data received from the back end.
It is initiated with all the fields as display: false, and if I receive that specific field from the server, I will eventually change it to true.

filterGroups (initial):

export let filterGroups: any = {
    genericFilters: {
        iboId: {
            'display': false,
            'template': ''
        },
        iboCode: {
            'display': false,
            'template': 'text/iboCode'
        },
        iboName: {
            'display': false,
            'template': 'text_input_iboName'
        },
        iboSurname: {
            'display': false,
            'template': 'text_input_iboSurname'
        },
        iboRank: {
            'display': false,
            'template': 'select/multi_iboRank',
        },
        iboEmail: {
            'display': false,
            'template': 'text_input_iboEmail'
        },
        iboNewsletter: {
            'display': false,
            'template': 'select/simple_iboNewsletter',
        },
    },
    orderFilters: {
        iboTotalOrders: {
            'display': false,
            'template': 'compound/iboTotalOrders',
        }
    },
    peFilters: {
        iboTotalPE: {
            'display': false,
            'template': 'checkbox/iboTotalPE',
        }
    },
};

In my template, I want to have as many div as filter groups. In this case we have 3 filter groups: genericFilters, orderFilters and peFilters.

This Object will be modified as soon as I receive data from the server (which I call in my constructor).

And so, my filterGroups will look like this after I have received the data from my async call.

filterGroups (after async call):

export let filterGroups: any = {
    genericFilters: {
        iboId: {
            'display': true,
            'template': ''
        },
        iboCode: {
            'display': true,
            'template': 'text/iboCode'
        },
        iboName: {
            'display': true,
            'template': 'text_input_iboName'
        },
        iboSurname: {
            'display': true,
            'template': 'text_input_iboSurname'
        },
        iboRank: {
            'display': false,
            'template': 'select/multi_iboRank',
        },
        iboEmail: {
            'display': true,
            'template': 'text_input_iboEmail'
        },
        iboNewsletter: {
            'display': false,
            'template': 'select/simple_iboNewsletter',
        },
    },
    orderFilters: {
        iboTotalOrders: {
            'display': true,
            'template': 'compound/iboTotalOrders',
        }
    },
    peFilters: {
        iboTotalPE: {
            'display': false,
            'template': 'checkbox/iboTotalPE',
        }
    },
};

Now, in my template I have this:

Template (HTML):

{{group.key}}

And, obviusly, here is my @Pipe.

@Pipe:

import { PipeTransform, Pipe } from '@angular/core';
import { isNullOrUndefined } from 'util';

@Pipe({name: 'keysCheckDisplay'})
export class KeysCheckDisplayPipe implements PipeTransform {
    transform(value, args: string[]): any {
        let keys = [];
        for (let key in value) {
            if (!isNullOrUndefined(value[key])) {
                let display = false;
                for (let keyChild in value[key]) {
                    if (!isNullOrUndefined(value[key][keyChild]) && value[key][keyChild]['display'] === true) {
                        display = true;
                        break;
                    }
                }
                if (display === true) {
                    keys.push({key: key, value: value[key]});
                }
            }
        }
        return keys;
    }
}

In this @Pipe as you can see I do several things:

Loop through the filterGroups object

Check for each group within the object if exists a child with display: true.

The functionality:

I want this @Pipe to loop through my Objectand return me the 'filter groups' that have at least 1 element with display: true.

The Issue:

The @Pipe is getting the first version of the filterGroups object, and is ignoring the fact that the object changes as soon as I receive the data from the server.

The @Pipe works fine if I modify the initial values of the filterGroups object.

What I have tried:

Research, research, research

I changed the @Pipe to inpure, but I hate this solution because of awful performance and also it entered an infinite loop.

I have also tried this approach:
*ngFor="let group of filterGroups | async | keysCheckDisplay".
But it throwed the following error:

Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

Possible solutions?

Modify the @Pipe?

Modify the initial object?

Create a second @Pipe to loop through the first Pipe's result?

I hope it was detailed and clear, if not, please don't esitate to comment asking for more details and I will gladly update the post.

Thank you beforehand!

Body:
A pure pipe is only called when the data changes. This means when "data" is a new object instance. If only the content of the object is modified, then Angular change detection won't recognize it as change and won't call the pipe.

Possible approaches

make the pipe impure: usually quite a burden for performance

copy the object like:

var tmp = this.data; this.data = {}; Object.assign(this.data, tmp);

add an additional parameter to the pipe and update the parameter value

*ngFor="let item of data | myPipe:counter"

// updated `data`
// this.counter++;


问:
MySQL: Compare two tables and find only matching data/filter first table by matched columns in second
I have sales data that contains Cust_ID, Invoice_Date, Invoice, Item_Number (and plenty other fields). This table has multiple records per Customer's Invoice, because each record holds different Item_Number info. Let's call this table sales_main.

I have a second table that contains only three of the fields mentioned above, namely Cust_ID, Invoice_Date, and Invoice. This table only contains one row per customer. Let's call this table sales_filter.

What I want to do is essentially use the second table as a filter on the first, so as to keep only rows from table sales_main (and all its columns) where the Cust_ID, Invoice_Date and Invoice columns in sales_filter and sales_main are an exact match.

So if sales_filter has a row that contains:

"1024", "24/02/2016", 533

and sales_main has four rows that match all three criteria, all four rows are returned in the result set. Same for any other rows in sales_main that match all three columns in any row from sales_filter exactly.

But I just cannot figure out what code to use to do this!

答:
You need to join those two tables based on those 3 columns then it will return all the records with matched condition

```<code>select * from sales_main sm join sales_filter sf on (sm.Cust_ID=sf.Cust_ID and sm.Invoice_Date=sf.Invoice_Date and  sm.Invoice=sf.Invoice)
</code>```

You can select the fields whichever you want in select

Body:
You need to join those two tables based on those 3 columns then it will return all the records with matched condition

select * from sales_main sm join sales_filter sf on (sm.Cust_ID=sf.Cust_ID and sm.Invoice_Date=sf.Invoice_Date and  sm.Invoice=sf.Invoice)

You can select the fields whichever you want in select


问:
How do I eliminate all the parenthesis in a txt files?
I have a txt file, single COLUMN, taken from excel, of the following type:

AMANDA (LOUDLY SPEAKING)
JEFF
STEVEN (TEASINGLY)
AMANDA
DOC BRIAN GREEN

As output I want:

AMANDA
JEFF
STEVEN
AMANDA
DOC BRIAN GREEN

I tried with a for cycle on all the column and then:

```<code>            if (str[i] == '('):
                return str.split('(')
</code>```

but it's clearly not working.
Do you have any possible solution? I would then need an output file as my original txt, so with each name for each line in a single column.

Thanks everyone!
(I am using PyCharm 3.2)

答:
You can split the string into a list using a regular expression that matches everything in parentheses or a full word, remove all elements from the list which contain parentheses and then join the list to a string again. The advantage is that there will be no double spaces in the result string where a word in parantheses was removed.</p>

```<code>import re
text = "AMANDA (LOUDLY SPEAKING) JEFF STEVEN (TEASINGLY) AMANDA DOC BRIAN GREEN"
words = re.findall("\(.*?\)|[^\s]+",text)
print " ".join([x for x in words if "(" not in x])
</code>```

Body:
I have a txt file, single COLUMN, taken from excel, of the following type:

AMANDA (LOUDLY SPEAKING)
JEFF
STEVEN (TEASINGLY)
AMANDA
DOC BRIAN GREEN

As output I want:

AMANDA
JEFF
STEVEN
AMANDA
DOC BRIAN GREEN

I tried with a for cycle on all the column and then:

            if (str[i] == '('):
                return str.split('(')

but it's clearly not working.
Do you have any possible solution? I would then need an output file as my original txt, so with each name for each line in a single column.

Thanks everyone!
(I am using PyCharm 3.2)

Body:
You can split the string into a list using a regular expression that matches everything in parentheses or a full word, remove all elements from the list which contain parentheses and then join the list to a string again. The advantage is that there will be no double spaces in the result string where a word in parantheses was removed.

import re
text = "AMANDA (LOUDLY SPEAKING) JEFF STEVEN (TEASINGLY) AMANDA DOC BRIAN GREEN"
words = re.findall("\(.*?\)|[^\s]+",text)
print " ".join([x for x in words if "(" not in x])


问:
Dynamically change editTexts position based on screen Size / DPI
I would like to change the position of one element (editText) in my UI when the user taps it. The positioning should be ~20 dp under the actionBar, no matter screen-size or DPI the device is using.

How do I accomplish this using only (java)code? Please try to give a more exact answer. I have seen other examples similar to this but none that explains an exakt scenario? I was thinking of a start like the code below? Then what?:

```<code>  DisplayMetrics dm = new DisplayMetrics();
  mSearchField = (EditText)v.findViewById (R.id.something);

  getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            int [] loc = new int[2];
            mSearchField.getLocationOnScreen(loc);
            int distance = dm.heightPixels - loc[1];
</code>```

答:
Get the Display height and width using DisplayMetrics.</p>

```<code>DisplayMetrics displayMetrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;
        Log.e("width",width+""+height);
</code>```

Body:
I would like to change the position of one element (editText) in my UI when the user taps it. The positioning should be ~20 dp under the actionBar, no matter screen-size or DPI the device is using.

How do I accomplish this using only (java)code? Please try to give a more exact answer. I have seen other examples similar to this but none that explains an exakt scenario? I was thinking of a start like the code below? Then what?:

  DisplayMetrics dm = new DisplayMetrics();
  mSearchField = (EditText)v.findViewById (R.id.something);

  getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            int [] loc = new int[2];
            mSearchField.getLocationOnScreen(loc);
            int distance = dm.heightPixels - loc[1];

Body:
Get the Display height and width using DisplayMetrics.

DisplayMetrics displayMetrics = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;
        Log.e("width",width+""+height);


问:
Adding Legend to plot in R
Hi I wish to create a legend for the following lines, but I am unsure how to.

```<code>lines1<- lines(salesARIMAPredict$pred, lty = 5, col = "Blue")
lines(salesARIMAPredict$pred+2*salesARIMAPredict$se, col = "Red") #Confidence Interval of 95%
lines(salesARIMAPredict$pred-2*salesARIMAPredict$se, col = "Red")
</code>```

See Attached

Many Thanks Saif

答:
You should do some basic research before asking questions: https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/legend.html

Edit:

For you I created this simple example:

```<code>ts.plot(ldeaths)
lines(ldeaths+100, col ="red")
legend("top", c("ldeaths", "+100"), col = c("black", "red"), lty = 1)
</code>```

Title: Adding Legend to plot in R

Body:
Hi I wish to create a legend for the following lines, but I am unsure how to.

lines1<- lines(salesARIMAPredict$pred, lty = 5, col = "Blue")
lines(salesARIMAPredict$pred+2*salesARIMAPredict$se, col = "Red") #Confidence Interval of 95%
lines(salesARIMAPredict$pred-2*salesARIMAPredict$se, col = "Red")

See Attached

Many Thanks Saif

Body:
You should do some basic research before asking questions: https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/legend.html

Edit:

For you I created this simple example:

ts.plot(ldeaths)
lines(ldeaths+100, col ="red")
legend("top", c("ldeaths", "+100"), col = c("black", "red"), lty = 1)


问:
Scale sprite kit game for all devices
When creating my game in spriteKit I used the game size 1080x1920. Now however If I am to run it on Ipad it looks bizarre. Is there an easy fix? I am simply worried that my app will get rejected. Thank you in advance?

答:
When you present the scene's you also set the aspect ratio.

example :

```<code>if let scene = SKScene(fileNamed: "GameScene") {
    // Set the scale mode to scale to fit the window
    scene.scaleMode = .aspectFill

    // Present the scene
    view.presentScene(scene)
}
</code>```

There are 4 different aspect radios you can set

aspectFit

aspectFill

fill

resizeFill

You can find out about the 4 different types here in the apple documents.

It looks to me that you currently have it set to aspectFill but you would be better off using aspectFit. This will create a black bar on the top and bottom on some devices but it will keep the aspect ratio the same.

If you want it to look good on all devices(no black bar) you would need to check which device it is running on then update the size and position of your sprites accordingly.

Title: Scale sprite kit game for all devices

Body:
When you present the scene's you also set the aspect ratio.

example :

if let scene = SKScene(fileNamed: "GameScene") {
    // Set the scale mode to scale to fit the window
    scene.scaleMode = .aspectFill

    // Present the scene
    view.presentScene(scene)
}

There are 4 different aspect radios you can set

aspectFit

aspectFill

fill

resizeFill

You can find out about the 4 different types here in the apple documents.

It looks to me that you currently have it set to aspectFill but you would be better off using aspectFit. This will create a black bar on the top and bottom on some devices but it will keep the aspect ratio the same.

If you want it to look good on all devices(no black bar) you would need to check which device it is running on then update the size and position of your sprites accordingly.


问:
Discord.net 1.0 - How to get Messages to delete?
so I am having problems with my command. It doesn't seem to show any problems, but when I go to use the command i get this back from my bot.

"ERROR:  The input text has too few parameters."

I don't know if I should be using IUserMessage, or SocketMessage, i've tried both and usually get the same error.

I don't know where I went wrong? I have tried to fix this for a while and i'm at a brick wall in trying to figure this out. Any help would be appreciated.

```<code>    [Command("purge")]
    [Summary("deletes set amount of text")]
    [RequireUserPermission(GuildPermission.Administrator)]
    [RequireBotPermission(GuildPermission.Administrator)]
    public async Task PurgeChat(IUserMessage msg, int amount)
    {
        int messagesDeleted = 0;
        var purgeMessage = await msg.Channel.SendMessageAsync("_purging in progress, give me a minute.._");
        var lastMessageID = purgeMessage.Id;

        try
        {
            var stop = false;
            while (amount > messagesDeleted)
            {
                var messages = await msg.Channel.GetMessagesAsync(lastMessageID, Direction.Before, 15).OfType<IUserMessage>().ToList();
                foreach (IUserMessage message in messages)
                {
                    await message.DeleteAsync();
                    messagesToDelete++;
                    if (messagesDeleted >= amount || messages.Count == 0)
                    {
                        stop = true;
                        break;
                    }
                    lastMessageID = messages.Last().Id;
                }
                if (stop || messages.Count == 0)
                {
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            if (ex.Message != "The server responded with error 404 (NotFound): \"Unknown Message\"")
            {
                await Context.Channel.SendMessageAsync("Something fucked up while trying to delete messages, you are going to have to manually Delete them for now. or try again");
            }
        }
        finally
        {
            await purgeMessage.ModifyAsync(x => x.Content = "_Purge Completed, this message will self destruct in 5 seconds_");
            await Task.Factory.StartNew(async () =>
             {
                 await Task.Delay(5000);
                 await purgeMessage.DeleteAsync();
             });
        }
    }
</code>```

答:
```<code>[Command("purge", RunMode = RunMode.Async)]
[Summary("Deletes the specified amount of messages.")]
[RequireUserPermission(GuildPermission.Administrator)]
[RequireBotPermission(ChannelPermission.ManageMessages)]
public async Task PurgeChat(uint amount)
{
    var messages = await this.Context.Channel.GetMessagesAsync((int)amount + 1).Flatten();

    await this.Context.Channel.DeleteMessagesAsync(messages);
    const int delay = 5000;
    var m = await this.ReplyAsync($"Purge completed. _This message will be deleted in {delay / 1000} seconds._");
    await Task.Delay(delay);
    await m.DeleteAsync();
}
</code>```

Body:
so I am having problems with my command. It doesn't seem to show any problems, but when I go to use the command i get this back from my bot.

"ERROR:  The input text has too few parameters."

I don't know if I should be using IUserMessage, or SocketMessage, i've tried both and usually get the same error.

I don't know where I went wrong? I have tried to fix this for a while and i'm at a brick wall in trying to figure this out. Any help would be appreciated.

    [Command("purge")]
    [Summary("deletes set amount of text")]
    [RequireUserPermission(GuildPermission.Administrator)]
    [RequireBotPermission(GuildPermission.Administrator)]
    public async Task PurgeChat(IUserMessage msg, int amount)
    {
        int messagesDeleted = 0;
        var purgeMessage = await msg.Channel.SendMessageAsync("_purging in progress, give me a minute.._");
        var lastMessageID = purgeMessage.Id;

        try
        {
            var stop = false;
            while (amount > messagesDeleted)
            {
                var messages = await msg.Channel.GetMessagesAsync(lastMessageID, Direction.Before, 15).OfType<IUserMessage>().ToList();
                foreach (IUserMessage message in messages)
                {
                    await message.DeleteAsync();
                    messagesToDelete++;
                    if (messagesDeleted >= amount || messages.Count == 0)
                    {
                        stop = true;
                        break;
                    }
                    lastMessageID = messages.Last().Id;
                }
                if (stop || messages.Count == 0)
                {
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            if (ex.Message != "The server responded with error 404 (NotFound): \"Unknown Message\"")
            {
                await Context.Channel.SendMessageAsync("Something fucked up while trying to delete messages, you are going to have to manually Delete them for now. or try again");
            }
        }
        finally
        {
            await purgeMessage.ModifyAsync(x => x.Content = "_Purge Completed, this message will self destruct in 5 seconds_");
            await Task.Factory.StartNew(async () =>
             {
                 await Task.Delay(5000);
                 await purgeMessage.DeleteAsync();
             });
        }
    }


问:
Does Action Cable 5 require Redis?
I use:

```<code>rails (5.0.2)
actioncable (5.0.2)
puma (3.8.2)
</code>```

I have a Rails 5 Action Cable demo chat and a year ago it didn't work without Redis - and now it does! (after bundle update).

In other words, I succedeed to make my demo chat to work in development mode without Redis. I set the config/cable.yml like this:

```<code>development:
  adapter: async

test:
  adapter: async

production:
  adapter: async
</code>```

and start rails c. That's it - the chat is working, no problem. So Redis is obviously not needed anymore - unlike a year-ago times?

Also I found a way to make my demo chat to work with Redis. To do so I change the config/cable.yml like this:

```<code>redis: &redis
  adapter: redis
  url: redis://localhost:6379/1

production: *redis
development: *redis
test: *redis
</code>```

than add gem 'redis', '~>3.2' to my Gemfile (+ bundle install), start Redis redis-server and then rails c.

So my questions are:

Does Action Cable 5 require Redis to work? (looks like don't but I'm not sure).

If (apparently) Action Cable 5 can work with or without Redis - what's the difference?

What is gem 'redis', '~>3.2'? What is it for?

Generally I have no idea what is now the proper usage of Action Cable 5 in terms of Redis usage (non-usage?). Is there any difference for the development or production mode?

答:
Does Action Cable 5 require Redis?

No. According to the documentation, it's able to use other adapters.

Action Cable provides a subscription adapter interface to process its
  pubsub internals. By default, asynchronous, inline, PostgreSQL,
  evented Redis, and non-evented Redis adapters are included. The
  default adapter in new Rails applications is the asynchronous (async)
  adapter.

Questions:

Does Action Cable 5 require Redis to work? (looks like don't but I'm
  not sure).

No.

If (apparently) Action Cable 5 can work with or without Redis - what's the difference?

In case of ActionCable there in no differences, it uses an abstraction adapter and does not depend on transport protocol.

What is gem 'redis', '~>3.2'? What is it for?

It's for redis and provides an interface for communication with redis-server.

Title: Does Action Cable 5 require Redis?

Body:
I use:

rails (5.0.2)
actioncable (5.0.2)
puma (3.8.2)

I have a Rails 5 Action Cable demo chat and a year ago it didn't work without Redis - and now it does! (after bundle update).

In other words, I succedeed to make my demo chat to work in development mode without Redis. I set the config/cable.yml like this:

development:
  adapter: async

test:
  adapter: async

production:
  adapter: async

and start rails c. That's it - the chat is working, no problem. So Redis is obviously not needed anymore - unlike a year-ago times?

Also I found a way to make my demo chat to work with Redis. To do so I change the config/cable.yml like this:

redis: &redis
  adapter: redis
  url: redis://localhost:6379/1

production: *redis
development: *redis
test: *redis

than add gem 'redis', '~>3.2' to my Gemfile (+ bundle install), start Redis redis-server and then rails c.

So my questions are:

Does Action Cable 5 require Redis to work? (looks like don't but I'm not sure).

If (apparently) Action Cable 5 can work with or without Redis - what's the difference?

What is gem 'redis', '~>3.2'? What is it for?

Generally I have no idea what is now the proper usage of Action Cable 5 in terms of Redis usage (non-usage?). Is there any difference for the development or production mode?