问:
SQL Server Merge multiple insert on not matched by target
I have two tables for merge , one is source and other is target. Data in Source is the output from CTE.

I am trying to insert data into Target but i have two conditions to insert the data in target table.

I am using Merge to update existing data and to insert new row. Target table include historical data.

Status in Source will be either 1 or 2 and status in Target will be either R or S.

Here are the sample of the process that I need to perform.

Below is the data in source and target table and also few condition i need to check.

Source

```<code>| ID    |Name | Cond| Status |
+-------+-----+-----+--------+
|   1   | A   | XYZ | 1      |
</code>```

Target

```<code>| ID    |Name | Cond| Status |  cdate
+-------+-----+-----+--------+
|   1   | A   | XYZ | R      | 4/09/2019 4:34:28
</code>```

Condition 1: now If there is some changes on Source data then source.status=2 and if target.id=source.id and target.status='R' then , target need to be updated with source data.

Source

```<code>    | ID    |Name | Cond| Status |
    +-------+-----+-----+--------+
    |   1   | B   | MNO | 2      |
</code>```

Target

```<code>    | ID    |Name | Cond| Status |   cdate
    +-------+-----+-----+--------+
    |   1   | B   | MNO | R      | 4/09/2019 4:34:28
</code>```

Condition 2: after execution of one stored procedure, target.status is changed to 'S'.

Now if target.status = 'S' and source.status = 2 and (target.name != source.name or target.cond != source.cond), a new row needs to be inserted into target with target.status as 'R'.

Source

```<code>    | ID    |Name | Cond| Status |
    +-------+-----+-----+--------+
    |   1   | B   | MNO | 2      |
</code>```

Target

```<code>    | ID    |Name | Cond| Status |
    +-------+-----+-----+--------+
    |   1   | A   | XYZ | S      | 4/09/2019 4:34:28
    |   1   | B   | MNO | R      | 6/09/2019 7:34:28
</code>```

To achieve the result I used MERGE as below :

```<code>MERGE table_1 AS TARGET
USING data_from_cte AS SOURCE ON (TARGET.ID = SOURCE.ID AND Target.status = 'R')

--WHEN RECORDS ARE MATCHED, UPDATE THE RECORDS IF THERE IS ANY CHANGE
WHEN MATCHED AND TARGET.STATUS = 'R'
    THEN UPDATE
             SET TARGET.name = SOURCE.name,
                 TARGET.cond = SOURCE.cond,

--WHEN NO RECORDS ARE MATCHED, INSERT THE INCOMING RECORDS FROM SOURCE TABLE TO TARGET TABLE
WHEN MATCHED AND TARGET.STATUS = 'S' AND source.status = 2
             AND (target.name != source.name OR target.cond != source.cond)
    THEN INSERT (id, name, cond, status)
         VALUES (SOURCE.ID, SOURCE.name, SOURCE.cond, 'R')

WHEN NOT MATCHED BY TARGET
    THEN INSERT (id, name, cond, status)
         VALUES (SOURCE.ID, SOURCE.name, SOURCE.cond, 'R');
</code>```

Issue here is: I cannot compare target column and source column in WHEN MATCHED condition of MERGE statement.

How can I solve this problem using MERGE statement or using IF ... ELSE statement ?

答:
You seem pretty close, there. You got a bit confused because you needed to check the existense of an S row with exists and you tried to do this through the merge syntax. This can't be done: you can only INSERT on WHEN NOT MATCHED BY TARGET. Try this:

```<code>;MERGE table_1 AS TARGET
USING data_from_cte AS SOURCE -- (add WHERE source.status = 2 to your CTE)
ON (TARGET.ID = SOURCE.ID AND Target.status = 'R')

--WHEN RECORDS ARE MATCHED, UPDATE THE RECORDS IF THERE IS ANY CHANGE
WHEN MATCHED AND TARGET.STATUS = 'R' AND operation='update'
    THEN UPDATE
             SET TARGET.name = SOURCE.name,
                 TARGET.cond = SOURCE.cond,

--WHEN NO RECORDS ARE MATCHED AND NO SAME S ROW EXISTS, INSERT THE INCOMING RECORDS FROM SOURCE TABLE TO TARGET TABLE
WHEN NOT MATCHED AND not exists(select 1 from table_1 t1 where t1.ID = SOURCE.ID AND t1.status = 'S' and t1.name = source.name and t1.cond = source.cond)
    THEN INSERT (id, name, cond, status)
         VALUES (SOURCE.ID, SOURCE.name, SOURCE.cond, 'R')
</code>```

The second (WHEN NOT MATCHED...) condition is changed, but also don't forget to add a WHERE source.status = 2 clause to your CTE

Body:
I have two tables for merge , one is source and other is target. Data in Source is the output from CTE.

I am trying to insert data into Target but i have two conditions to insert the data in target table.

I am using Merge to update existing data and to insert new row. Target table include historical data.

Status in Source will be either 1 or 2 and status in Target will be either R or S.

Here are the sample of the process that I need to perform.

Below is the data in source and target table and also few condition i need to check.

Source

| ID    |Name | Cond| Status |
+-------+-----+-----+--------+
|   1   | A   | XYZ | 1      |

Target

| ID    |Name | Cond| Status |  cdate
+-------+-----+-----+--------+
|   1   | A   | XYZ | R      | 4/09/2019 4:34:28

Condition 1: now If there is some changes on Source data then source.status=2 and if target.id=source.id and target.status='R' then , target need to be updated with source data.

Source

    | ID    |Name | Cond| Status |
    +-------+-----+-----+--------+
    |   1   | B   | MNO | 2      |

Target

    | ID    |Name | Cond| Status |   cdate
    +-------+-----+-----+--------+
    |   1   | B   | MNO | R      | 4/09/2019 4:34:28

Condition 2: after execution of one stored procedure, target.status is changed to 'S'.

Now if target.status = 'S' and source.status = 2 and (target.name != source.name or target.cond != source.cond), a new row needs to be inserted into target with target.status as 'R'.

Source

    | ID    |Name | Cond| Status |
    +-------+-----+-----+--------+
    |   1   | B   | MNO | 2      |

Target

    | ID    |Name | Cond| Status |
    +-------+-----+-----+--------+
    |   1   | A   | XYZ | S      | 4/09/2019 4:34:28
    |   1   | B   | MNO | R      | 6/09/2019 7:34:28

To achieve the result I used MERGE as below :

MERGE table_1 AS TARGET
USING data_from_cte AS SOURCE ON (TARGET.ID = SOURCE.ID AND Target.status = 'R')

--WHEN RECORDS ARE MATCHED, UPDATE THE RECORDS IF THERE IS ANY CHANGE
WHEN MATCHED AND TARGET.STATUS = 'R'
    THEN UPDATE
             SET TARGET.name = SOURCE.name,
                 TARGET.cond = SOURCE.cond,

--WHEN NO RECORDS ARE MATCHED, INSERT THE INCOMING RECORDS FROM SOURCE TABLE TO TARGET TABLE
WHEN MATCHED AND TARGET.STATUS = 'S' AND source.status = 2
             AND (target.name != source.name OR target.cond != source.cond)
    THEN INSERT (id, name, cond, status)
         VALUES (SOURCE.ID, SOURCE.name, SOURCE.cond, 'R')

WHEN NOT MATCHED BY TARGET
    THEN INSERT (id, name, cond, status)
         VALUES (SOURCE.ID, SOURCE.name, SOURCE.cond, 'R');

Issue here is: I cannot compare target column and source column in WHEN MATCHED condition of MERGE statement.

How can I solve this problem using MERGE statement or using IF ... ELSE statement ?

Body:
You seem pretty close, there. You got a bit confused because you needed to check the existense of an S row with exists and you tried to do this through the merge syntax. This can't be done: you can only INSERT on WHEN NOT MATCHED BY TARGET. Try this:

;MERGE table_1 AS TARGET
USING data_from_cte AS SOURCE -- (add WHERE source.status = 2 to your CTE)
ON (TARGET.ID = SOURCE.ID AND Target.status = 'R')

--WHEN RECORDS ARE MATCHED, UPDATE THE RECORDS IF THERE IS ANY CHANGE
WHEN MATCHED AND TARGET.STATUS = 'R' AND operation='update'
    THEN UPDATE
             SET TARGET.name = SOURCE.name,
                 TARGET.cond = SOURCE.cond,

--WHEN NO RECORDS ARE MATCHED AND NO SAME S ROW EXISTS, INSERT THE INCOMING RECORDS FROM SOURCE TABLE TO TARGET TABLE
WHEN NOT MATCHED AND not exists(select 1 from table_1 t1 where t1.ID = SOURCE.ID AND t1.status = 'S' and t1.name = source.name and t1.cond = source.cond)
    THEN INSERT (id, name, cond, status)
         VALUES (SOURCE.ID, SOURCE.name, SOURCE.cond, 'R')

The second (WHEN NOT MATCHED...) condition is changed, but also don't forget to add a WHERE source.status = 2 clause to your CTE


来源: stackexchange

问:
Use a generic string as the key of an object
I want to define an object O that is generic over some type argument T extends string in such a way that the object O always has a key with the value of T.

```<code>type O<T extends string> = { [t in T]: string };

function f<T extends string>(t: T, o: O<T>) {
    const x = o[t];
    return x === "hello";
}

let s = f("a", { a: "" })

if (s === "Hello") {

}
</code>```

This is what I tried but it doesn't actually work since O[T] is not inferred to string. This means that the last if has an error because TypeScript the comparison will always be false.

TypeScript Playground Link

答:
O[T] will not directly show up as string but it will behave as string for all intents and purposes:

```<code>type O<T extends string> = { [t in T]: string };

function f<T extends string>(t: T, o: O<T>) {
    let x = o[t];
    let s: string = x; // assignable to string
    x = "S" // string can be assigned to it
    return x;
}
let s: string = f("a", {a: ""}) // outside it is string
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to define an object O that is generic over some type argument T extends string in such a way that the object O always has a key with the value of T.

type O<T extends string> = { [t in T]: string };

function f<T extends string>(t: T, o: O<T>) {
    const x = o[t];
    return x === "hello";
}

let s = f("a", { a: "" })

if (s === "Hello") {

}

This is what I tried but it doesn't actually work since O[T] is not inferred to string. This means that the last if has an error because TypeScript the comparison will always be false.

TypeScript Playground Link

Body:
O[T] will not directly show up as string but it will behave as string for all intents and purposes:

type O<T extends string> = { [t in T]: string };

function f<T extends string>(t: T, o: O<T>) {
    let x = o[t];
    let s: string = x; // assignable to string
    x = "S" // string can be assigned to it
    return x;
}
let s: string = f("a", {a: ""}) // outside it is string


问:
Write a python code to create a new csv column from existing column using conditional statements
I'm new to python coding and wanted to create a new column based on the condition statement on existing columns.

I use python 2.7 version and run the code on CentOs.

```<code>import pandas as pd
file1 = pd.read_csv("/root/Documents/temp_file_{}.csv".format(timestr))
file1['FileName'] = ''
file1['FileName'] = file1['FileType'].apply(lambda x: df['Path'].str.extract('[^/]+$', expand=False) if x=='f' else '')
file1.to_csv('/root/Documents/temp1_file_{}.csv'.format(timestr),index = False)
</code>```

Below is my CSV file:

```<code>FileType,Path

d,/

f,/documents/csv/.zip

d,/documents/images

d,/hive/28374849

f,/hadoop/jdjdjd/dnejfn.img
</code>```

Required CSV file:

```<code>FileType,Path,FileName

d,/,

f,/documents/csv/.zip,.zip

d,/documents/images,

d,/hive/28374849,

f,/hadoop/jdjdjd/dnejfn.img,dnejfn.img
</code>```

I want to create a new column FileName where the data in that column should be extracted from Path column only when column Filetype=='f' else the data in that column should be a null value or no data

答:
Using numpy.where with pandas.Series.str.rsplit:

```<code>import numpy as np
import pandas as pd

df['FileName'] = np.where(df['FileType'].eq('f'),df['Path'].str.rsplit('/').str.get(-1), '')
</code>```

Output:

```<code>  FileType                       Path    FileName
0        d                          /
1        f        /documents/csv/.zip        .zip
2        d          /documents/images
3        d             /hive/28374849
4        f  /hadoop/jdjdjd/dnejfn.img  dnejfn.img
</code>```

Body:
I'm new to python coding and wanted to create a new column based on the condition statement on existing columns.

I use python 2.7 version and run the code on CentOs.

import pandas as pd
file1 = pd.read_csv("/root/Documents/temp_file_{}.csv".format(timestr))
file1['FileName'] = ''
file1['FileName'] = file1['FileType'].apply(lambda x: df['Path'].str.extract('[^/]+$', expand=False) if x=='f' else '')
file1.to_csv('/root/Documents/temp1_file_{}.csv'.format(timestr),index = False)

Below is my CSV file:

FileType,Path

d,/

f,/documents/csv/.zip

d,/documents/images

d,/hive/28374849

f,/hadoop/jdjdjd/dnejfn.img

Required CSV file:

FileType,Path,FileName

d,/,

f,/documents/csv/.zip,.zip

d,/documents/images,

d,/hive/28374849,

f,/hadoop/jdjdjd/dnejfn.img,dnejfn.img

I want to create a new column FileName where the data in that column should be extracted from Path column only when column Filetype=='f' else the data in that column should be a null value or no data

Body:
Using numpy.where with pandas.Series.str.rsplit:

import numpy as np
import pandas as pd

df['FileName'] = np.where(df['FileType'].eq('f'),df['Path'].str.rsplit('/').str.get(-1), '')

Output:

  FileType                       Path    FileName
0        d                          /
1        f        /documents/csv/.zip        .zip
2        d          /documents/images
3        d             /hive/28374849
4        f  /hadoop/jdjdjd/dnejfn.img  dnejfn.img


问:
Dynamically choose implementation of logger in Scala
I have a library in which I use log4j to log things. For some particular classes of my library (all classes extending Component) I want that the log statement contain the suffix [component_name] at the beginning.

I don't want to mutate how a log statement usually looks like. Therefore, within one of these special component named 'foo' the statement log.info("message") should output [foo] message in the logging system.

This is what I did so far and where I am stuck:

```<code>object Logging {
   val logger = Logger.getLogger("my_logger_name")
}
</code>```

This is the basic logger, which I call all over the code using Logging.logger.info("message")

I thought the best thing to do would be to build the enriched logger using a trait

```<code>trait WithEnrichedLogger {
   this: Component =>
   val logger = new EnrichedLogger(this.name)
}

class EnrichedLogger(name: String) {
   def info(msg: String): Unit = Logging.logger.info(s"[${name}] $msg")
}
</code>```

and my component simply looks like

```<code>abstract class Component with WithEnrichedLogger {
     def name: String
     ....

     def some_method: Unit = {
        logger.info("log statement") \\ it should print the '[name]' at the beginning
     }
 }
</code>```

The problem in this setup is that at the moment of Component creation, the WithEnrichedLogger trait gets initialised and the value of name is still null. For this reason, the statement is "null log statement"

This solution looked to me the most elegant one, but please propose me different ones if better

答:
You just need to make the logger value lazy:

```<code>trait WithEnrichedLogger {
  this: Component =>
  lazy val logger = new EnrichedLogger(this.name)
}
</code>```

Now logger will not be created until it is first used, by which time the name value will be valid.

Body:
I have a library in which I use log4j to log things. For some particular classes of my library (all classes extending Component) I want that the log statement contain the suffix [component_name] at the beginning.

I don't want to mutate how a log statement usually looks like. Therefore, within one of these special component named 'foo' the statement log.info("message") should output [foo] message in the logging system.

This is what I did so far and where I am stuck:

object Logging {
   val logger = Logger.getLogger("my_logger_name")
}

This is the basic logger, which I call all over the code using Logging.logger.info("message")

I thought the best thing to do would be to build the enriched logger using a trait

trait WithEnrichedLogger {
   this: Component =>
   val logger = new EnrichedLogger(this.name)
}

class EnrichedLogger(name: String) {
   def info(msg: String): Unit = Logging.logger.info(s"[${name}] $msg")
}

and my component simply looks like

abstract class Component with WithEnrichedLogger {
     def name: String
     ....

     def some_method: Unit = {
        logger.info("log statement") \\ it should print the '[name]' at the beginning
     }
 }

The problem in this setup is that at the moment of Component creation, the WithEnrichedLogger trait gets initialised and the value of name is still null. For this reason, the statement is "null log statement"

This solution looked to me the most elegant one, but please propose me different ones if better

Body:
You just need to make the logger value lazy:

trait WithEnrichedLogger {
  this: Component =>
  lazy val logger = new EnrichedLogger(this.name)
}

Now logger will not be created until it is first used, by which time the name value will be valid.


问:
I get a deprecated warning
I used the code from Android Hive. Now android studio shows this class uses deprecated api. But don't know which class.
I tried with some classes. My minimum SDK version is 11.

```<code>import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WelcomeScreen extends AppCompatActivity {

private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Checking for first time launch - before calling setContentView()
    prefManager = new PrefManager(this);

    if (!prefManager.isFirstTimeLaunch()) {
        launchHomeScreen();
        finish();
    }

    // Making notification bar transparent
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    setContentView(package_name.R.layout.activity_welcome_screen);

    viewPager = (ViewPager) findViewById(package_name.R.id.view_pager);
    dotsLayout = (LinearLayout) findViewById(package_name.R.id.layoutDots);
    btnSkip = (Button) findViewById(package_name.R.id.btn_skip);
    btnNext = (Button) findViewById(package_name.R.id.btn_next);

    // layouts of all welcome sliders
    // add few more layouts if you want
    layouts = new int[]{
            };

    // adding bottom dots
    addBottomDots(0);

    // making notification bar transparent
    changeStatusBarColor();

    myViewPagerAdapter = new MyViewPagerAdapter();
    viewPager.setAdapter(myViewPagerAdapter);
    viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

    btnSkip.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchHomeScreen();
        }
    });

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // checking for last page
            // if last page home screen will be launched
            int current = getItem(+1);
            if (current < layouts.length) {
                // move to next screen
                viewPager.setCurrentItem(current);
            } else {
                launchHomeScreen();
            }
        }
    });
}

private void addBottomDots(int currentPage) {
    dots = new TextView[layouts.length];

    int[] colorsActive = getResources().getIntArray(package_name.R.array.array_dot_active);
    int[] colorsInactive = getResources().getIntArray(package_name.R.array.array_dot_inactive);

    dotsLayout.removeAllViews();
    for (int i = 0; i < dots.length; i++) {
        dots[i] = new TextView(this);
        dots[i].setText(Html.fromHtml("•"));
        dots[i].setTextSize(35);
        dots[i].setTextColor(colorsInactive[currentPage]);
        dotsLayout.addView(dots[i]);
    }

    if (dots.length > 0)
        dots[currentPage].setTextColor(colorsActive[currentPage]);
}

private int getItem(int i) {
    return viewPager.getCurrentItem() + i;
}

private void launchHomeScreen() {
    prefManager.setFirstTimeLaunch(false);
    startActivity(new Intent(WelcomeScreen.this, class2.class));
    finish();
}

//  viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {
        addBottomDots(position);

        // changing the next button text 'NEXT' / 'GOT IT'
        if (position == layouts.length - 1) {
            // last page. make button text to GOT IT
            btnNext.setText(getString(package_name.R.string.start));
            btnSkip.setVisibility(View.GONE);
        } else {
            // still pages are left
            btnNext.setText(getString(package_name.R.string.next));
            btnSkip.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
};

/**
 * Making notification bar transparent
 */
private void changeStatusBarColor() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }
}

/**
 * View pager adapter
 */
public class MyViewPagerAdapter extends PagerAdapter {
    private LayoutInflater layoutInflater;

    public MyViewPagerAdapter() {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = layoutInflater.inflate(layouts[position], container, false);
        container.addView(view);

        return view;
    }

    @Override
    public int getCount() {
        return layouts.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
    }
}

}
</code>```

This is my WelcomeScreen.java
I am using latest Android Studio
these are in build.gradle
compileSdkVersion 27
buildToolsVersion '28.0.3'
minSdkVersion 16
targetSdkVersion 26

Anyone know how to find this? or is there any debug tool or something with Android Studio??

答:
private PrefManager prefManager;

PrefManager class has been deprecated. Android Documentation
If you did not get notified by android studio then just go check the android docs for the classes you used.

Title: I get a deprecated warning

Body:
I used the code from Android Hive. Now android studio shows this class uses deprecated api. But don't know which class.
I tried with some classes. My minimum SDK version is 11.

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WelcomeScreen extends AppCompatActivity {

private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Checking for first time launch - before calling setContentView()
    prefManager = new PrefManager(this);

    if (!prefManager.isFirstTimeLaunch()) {
        launchHomeScreen();
        finish();
    }

    // Making notification bar transparent
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    setContentView(package_name.R.layout.activity_welcome_screen);

    viewPager = (ViewPager) findViewById(package_name.R.id.view_pager);
    dotsLayout = (LinearLayout) findViewById(package_name.R.id.layoutDots);
    btnSkip = (Button) findViewById(package_name.R.id.btn_skip);
    btnNext = (Button) findViewById(package_name.R.id.btn_next);

    // layouts of all welcome sliders
    // add few more layouts if you want
    layouts = new int[]{
            };

    // adding bottom dots
    addBottomDots(0);

    // making notification bar transparent
    changeStatusBarColor();

    myViewPagerAdapter = new MyViewPagerAdapter();
    viewPager.setAdapter(myViewPagerAdapter);
    viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

    btnSkip.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchHomeScreen();
        }
    });

    btnNext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // checking for last page
            // if last page home screen will be launched
            int current = getItem(+1);
            if (current < layouts.length) {
                // move to next screen
                viewPager.setCurrentItem(current);
            } else {
                launchHomeScreen();
            }
        }
    });
}

private void addBottomDots(int currentPage) {
    dots = new TextView[layouts.length];

    int[] colorsActive = getResources().getIntArray(package_name.R.array.array_dot_active);
    int[] colorsInactive = getResources().getIntArray(package_name.R.array.array_dot_inactive);

    dotsLayout.removeAllViews();
    for (int i = 0; i < dots.length; i++) {
        dots[i] = new TextView(this);
        dots[i].setText(Html.fromHtml("•"));
        dots[i].setTextSize(35);
        dots[i].setTextColor(colorsInactive[currentPage]);
        dotsLayout.addView(dots[i]);
    }

    if (dots.length > 0)
        dots[currentPage].setTextColor(colorsActive[currentPage]);
}

private int getItem(int i) {
    return viewPager.getCurrentItem() + i;
}

private void launchHomeScreen() {
    prefManager.setFirstTimeLaunch(false);
    startActivity(new Intent(WelcomeScreen.this, class2.class));
    finish();
}

//  viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {
        addBottomDots(position);

        // changing the next button text 'NEXT' / 'GOT IT'
        if (position == layouts.length - 1) {
            // last page. make button text to GOT IT
            btnNext.setText(getString(package_name.R.string.start));
            btnSkip.setVisibility(View.GONE);
        } else {
            // still pages are left
            btnNext.setText(getString(package_name.R.string.next));
            btnSkip.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }
};

/**
 * Making notification bar transparent
 */
private void changeStatusBarColor() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
    }
}

/**
 * View pager adapter
 */
public class MyViewPagerAdapter extends PagerAdapter {
    private LayoutInflater layoutInflater;

    public MyViewPagerAdapter() {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = layoutInflater.inflate(layouts[position], container, false);
        container.addView(view);

        return view;
    }

    @Override
    public int getCount() {
        return layouts.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
    }
}

}

This is my WelcomeScreen.java
I am using latest Android Studio
these are in build.gradle
compileSdkVersion 27
buildToolsVersion '28.0.3'
minSdkVersion 16
targetSdkVersion 26

Anyone know how to find this? or is there any debug tool or something with Android Studio??


问:
Computing maximum of numpy ndarray in each bin
I am struggling to perform a conceptually simple algorithm using optimized numpy vectorized operations. In the code below I have data which is an array with a bunch of values, and coords of which entry i contains 3D spatial coordinates corresponding to data[i]. I want to populate the array max_data so that entry max_data[i,j,k] is the maximum of all entries of data such that the corresponding entries of coords fall in the range [ [i,i+1], [j,j+1], [k,k+1] ]. Example code that generates the data and implements the algorithm is below.

Is there any way to speed this up using numpy vectorized operations? I am running a version of this on arrays with ndata ~ 1e9 and it takes forever. I am not opposed to using other python libs.

```<code>import numpy as np
import time

shape = ( 20, 30, 40 )

ndata = int( 1e6 )

data = np.random.normal(  loc = 10, scale = 5, size = ndata )

coords = np.vstack( [ np.random.uniform( 0, shape[i], ndata )
                      for i in range( len( shape ) ) ] ).T

max_data = np.zeros( shape )

start = time.time()

for i in range( len( data ) ) :

    # shortcut to find bin indices when the bins are
    # [ range( shape[i] ) for i in range( len( shape ) ) ]

    bin_indices = tuple( coords[i].astype( int ) )

    max_data[ bin_indices ] = max( max_data[ bin_indices ], data[ i ] )

elapsed = time.time() - start

print( 'elapsed: %.3e' % elapsed )  # 2.98 seconds on my computer
</code>```

答:
Using the 2nd-fastest solution from https://stackoverflow.com/a/55226663/7207392 gives me a >30x speedup. If you are open to using pythran an even faster solution is available.

```<code>import numpy as np
from scipy import sparse
import time

shape = ( 20, 30, 40 )

ndata = int( 1e6 )

data = np.random.normal(  loc = 10, scale = 5, size = ndata )

coords = np.vstack( [ np.random.uniform( 0, shape[i], ndata )
                      for i in range( len( shape ) ) ] ).T

max_data = np.zeros( shape )

start = time.time()

for i in range( len( data ) ) :

    # shortcut to find bin indices when the bins are
    # [ range( shape[i] ) for i in range( len( shape ) ) ]

    bin_indices = tuple( coords[i].astype( int ) )

    max_data[ bin_indices ] = max( max_data[ bin_indices ], data[ i ] )

elapsed = time.time() - start

print( 'elapsed: %.3e' % elapsed )  # 2.98 seconds on my computer

start = time.time()

bin_indices = np.ravel_multi_index(coords.astype(int).T, shape)
aux = sparse.csr_matrix((data, bin_indices, np.arange(data.size+1)),
                        (data.size, np.prod(shape))).tocsc()
cut = aux.indptr.searchsorted(data.size)
max_data_pp = np.empty(shape)
max_data_pp.ravel()[:cut] = np.maximum.reduceat(aux.data, aux.indptr[:cut])

CLIPAT = 0

max_data_pp.ravel()[aux.indptr[:-1]==aux.indptr[1:]] = CLIPAT
max_data_pp[max_data_pp < CLIPAT] = CLIPAT

elapsed = time.time() - start

print( 'elapsed: %.3e' % elapsed )  # 2.98 seconds on my computer

assert np.all(max_data == max_data_pp)
</code>```

Sample run:

```<code>elapsed: 2.417e+00
elapsed: 6.387e-02
</code>```

Body:
I am struggling to perform a conceptually simple algorithm using optimized numpy vectorized operations. In the code below I have data which is an array with a bunch of values, and coords of which entry i contains 3D spatial coordinates corresponding to data[i]. I want to populate the array max_data so that entry max_data[i,j,k] is the maximum of all entries of data such that the corresponding entries of coords fall in the range [ [i,i+1], [j,j+1], [k,k+1] ]. Example code that generates the data and implements the algorithm is below.

Is there any way to speed this up using numpy vectorized operations? I am running a version of this on arrays with ndata ~ 1e9 and it takes forever. I am not opposed to using other python libs.

import numpy as np
import time

shape = ( 20, 30, 40 )

ndata = int( 1e6 )

data = np.random.normal(  loc = 10, scale = 5, size = ndata )

coords = np.vstack( [ np.random.uniform( 0, shape[i], ndata )
                      for i in range( len( shape ) ) ] ).T

max_data = np.zeros( shape )

start = time.time()

for i in range( len( data ) ) :

    # shortcut to find bin indices when the bins are
    # [ range( shape[i] ) for i in range( len( shape ) ) ]

    bin_indices = tuple( coords[i].astype( int ) )

    max_data[ bin_indices ] = max( max_data[ bin_indices ], data[ i ] )

elapsed = time.time() - start

print( 'elapsed: %.3e' % elapsed )  # 2.98 seconds on my computer

Body:
Using the 2nd-fastest solution from https://stackoverflow.com/a/55226663/7207392 gives me a >30x speedup. If you are open to using pythran an even faster solution is available.

import numpy as np
from scipy import sparse
import time

shape = ( 20, 30, 40 )

ndata = int( 1e6 )

data = np.random.normal(  loc = 10, scale = 5, size = ndata )

coords = np.vstack( [ np.random.uniform( 0, shape[i], ndata )
                      for i in range( len( shape ) ) ] ).T

max_data = np.zeros( shape )

start = time.time()

for i in range( len( data ) ) :

    # shortcut to find bin indices when the bins are
    # [ range( shape[i] ) for i in range( len( shape ) ) ]

    bin_indices = tuple( coords[i].astype( int ) )

    max_data[ bin_indices ] = max( max_data[ bin_indices ], data[ i ] )

elapsed = time.time() - start

print( 'elapsed: %.3e' % elapsed )  # 2.98 seconds on my computer

start = time.time()

bin_indices = np.ravel_multi_index(coords.astype(int).T, shape)
aux = sparse.csr_matrix((data, bin_indices, np.arange(data.size+1)),
                        (data.size, np.prod(shape))).tocsc()
cut = aux.indptr.searchsorted(data.size)
max_data_pp = np.empty(shape)
max_data_pp.ravel()[:cut] = np.maximum.reduceat(aux.data, aux.indptr[:cut])

CLIPAT = 0

max_data_pp.ravel()[aux.indptr[:-1]==aux.indptr[1:]] = CLIPAT
max_data_pp[max_data_pp < CLIPAT] = CLIPAT

elapsed = time.time() - start

print( 'elapsed: %.3e' % elapsed )  # 2.98 seconds on my computer

assert np.all(max_data == max_data_pp)

Sample run:

elapsed: 2.417e+00
elapsed: 6.387e-02


问:
Unable to install php7.1-bcmath on ubuntu 16.04
When I run the following command : composer require sonata-project/notification-bundle  I have this error:

```<code>- php-amqplib/php-amqplib v2.7.2 requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.
    - php-amqplib/php-amqplib v2.7.1 requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.
    - php-amqplib/php-amqplib v2.7.0 requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.
    - sonata-project/notification-bundle 3.4.0 requires enqueue/amqp-lib ^0.8 -> satisfiable by enqueue/amqp-lib[0.8.0, 0.8.10, 0.8.11, 0.8.12, 0.8.13, 0.8.15, 0.8.2, 0.8.21, 0.8.23, 0.8.4, 0.8.5, 0.8.9].
</code>```

Apparently bcmath is missing so I have run this:

```<code>sudo apt-get install php7.1-bcmath
</code>```

And I get the error below:

```<code>E: Unable to locate package php7.1-bcmath
E: Couldn't find any package by glob 'php7.1-bcmath'
E: Couldn't find any package by regex 'php7.1-bcmath'
</code>```

Any idea what causing the problem ?

Symfony 4
php 7.1
Ubuntu 16.04

答:
```<code>sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt install php7.1-bcmath
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I run the following command : composer require sonata-project/notification-bundle  I have this error:

- php-amqplib/php-amqplib v2.7.2 requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.
    - php-amqplib/php-amqplib v2.7.1 requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.
    - php-amqplib/php-amqplib v2.7.0 requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.
    - sonata-project/notification-bundle 3.4.0 requires enqueue/amqp-lib ^0.8 -> satisfiable by enqueue/amqp-lib[0.8.0, 0.8.10, 0.8.11, 0.8.12, 0.8.13, 0.8.15, 0.8.2, 0.8.21, 0.8.23, 0.8.4, 0.8.5, 0.8.9].

Apparently bcmath is missing so I have run this:

sudo apt-get install php7.1-bcmath

And I get the error below:

E: Unable to locate package php7.1-bcmath
E: Couldn't find any package by glob 'php7.1-bcmath'
E: Couldn't find any package by regex 'php7.1-bcmath'

Any idea what causing the problem ?

Symfony 4
php 7.1
Ubuntu 16.04


问:
How to navigate from a table view to a XIB file
I have loaded a XIB file(xyz) which is in the form of tableView
Now I have to load another XIB file(abc) on clicking any cell present in the xyz file . I have written this code in the didSelectRowAtIndexPath method

```<code>abc * vc = [[abc alloc] initWithNibName:@"abc" bundle:nil];
[self.navigationController pushViewController:vc animated:YES];
</code>```

It is throwing a SIGABRT error in main. Please help!!

答:
Like mentioned in the comment, check whether self.navigationController is nil.
If you're using storyboard, try embedding the ViewController in the NavigationController.You can do so by selecting your view controller in storyboard and then Go to Editor > Embed In > Navigation Controller

Further, check whether your xib file's name is indeed "abc"

Body:
I have loaded a XIB file(xyz) which is in the form of tableView
Now I have to load another XIB file(abc) on clicking any cell present in the xyz file . I have written this code in the didSelectRowAtIndexPath method

abc * vc = [[abc alloc] initWithNibName:@"abc" bundle:nil];
[self.navigationController pushViewController:vc animated:YES];

It is throwing a SIGABRT error in main. Please help!!


问:
How to keep alert of Contact Form 7 below its floated input field
I have made this Wordpress form with Contact Form 7 plugin: http://ipermx.buensaltolabs.com/test-contact-form/

However, if you click SEND without filling the fields, the span .wpcf7-not-valid-tip shows floated and this causes the remaining fields shift down.

Can you help me keep the error messages below each field?

Thanks in advance
Javier

答:
Add display: flex; to .wpcf7-form p

result


问:
Enable cURL on PHP7 windows10 64 bit Apache 2.4
I am using
Windows10 64 bit
Apache 2.4.25 (Win64)
PHP 7.1.0-Win32-VC14-x64

when i try calling curl_init() function, i get an error saying "Call to undefined function curl_init()"
tried following

copying ssleay32.dll & libeay32.dll & php7ts.dll to apache/bin folder

setting path properly to include above files "C:/PHP;"

Any help much appreciated.

答:
This save my life (from https://www.php.net/manual/en/curl.installation.php)

Upgrading to php 7.1.6 on Apache 2.4 32bit version Windows 7 x64

this curl  implementation works:

C:/(path to php folder)/php.ini  enable extension=php_curl.dll

libeay32.dll, ssleay32.dll, libssh2.dll find directly in php7 folder

add this to Apache/conf/httpd.conf
```<code># load curl and open ssl libraries
LoadFile "C:/(path to php folder)/libeay32.dll"
LoadFile "C:/(path to php folder)/ssleay32.dll"
LoadFile "C:/(path to php folder)/libssh2.dll"
</code>```

If you don't find some of this DLLs, try downloaidng non-TS version fo php and copy them from that folder.

Body:
This save my life (from https://www.php.net/manual/en/curl.installation.php)

Upgrading to php 7.1.6 on Apache 2.4 32bit version Windows 7 x64

this curl  implementation works:

C:/(path to php folder)/php.ini  enable extension=php_curl.dll

libeay32.dll, ssleay32.dll, libssh2.dll find directly in php7 folder

add this to Apache/conf/httpd.conf

# load curl and open ssl libraries
LoadFile "C:/(path to php folder)/libeay32.dll"
LoadFile "C:/(path to php folder)/ssleay32.dll"
LoadFile "C:/(path to php folder)/libssh2.dll"

If you don't find some of this DLLs, try downloaidng non-TS version fo php and copy them from that folder.


问:
Process large csv file and limit goroutines
I'm trying to find the best efficient way to read a csv file (~1M row).
Each row contain a HTTP link to an image which I need to download.

This is my current code using worker pools:

```<code>func worker(queue chan []string, worknumber int, done, ks chan bool) {
    for true {
        select {
        case url := <-queue:
            fmt.Println("doing work!", url, "worknumber", worknumber)
            processData(url) // HTTP download
            done <- true
        case <-ks:
            fmt.Println("worker halted, number", worknumber)
            return
        }
    }
}

func main() {
    start := time.Now()
    flag.Parse()
    fmt.Print(strings.Join(flag.Args(), "\n"))
    if *filename == "REQUIRED" {
        return
    }

    csvfile, err := os.Open(*filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    count, _ := lineCounter(csvfile)
    fmt.Printf("Total count: %d\n", count)
    csvfile.Seek(0, 0)

    defer csvfile.Close()

    //bar := pb.StartNew(count)
    bar := progressbar.NewOptions(count)
    bar.RenderBlank()

    reader := csv.NewReader(csvfile)

    //channel for terminating the workers
    killsignal := make(chan bool)

    //queue of jobs
    q := make(chan []string)
    // done channel takes the result of the job
    done := make(chan bool)

    numberOfWorkers := *numChannels
    for i := 0; i < numberOfWorkers; i++ {
        go worker(q, i, done, killsignal)
    }

    i := 0
    for {
        record, err := reader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            fmt.Println(err)
            return
        }
        i++

        go func(r []string, i int) {
            q <- r
            bar.Add(1)
        }(record, i)
    }

    // a deadlock occurs if c >= numberOfJobs
    for c := 0; c < count; c++ {
        <-done
    }

    fmt.Println("finished")

    // cleaning workers
    close(killsignal)
    time.Sleep(2 * time.Second)

    fmt.Printf("\n%2fs", time.Since(start).Seconds())
}
</code>```

My issue here is that it opens a lot of goroutines, use all the memory and crash.

What would be the best way to limit it?

答:
buffered channel can help you to limit goroutines

var taskPipe = make(chan interface{}, 5)

func main(){
    go func() {
        taskPipe <- nil
        sleep
    }()
}

func sleep() {
    time.Sleep(time.Second * 5)
    <- taskPipe
}
```

Body:
I'm trying to find the best efficient way to read a csv file (~1M row).
Each row contain a HTTP link to an image which I need to download.

This is my current code using worker pools:

func worker(queue chan []string, worknumber int, done, ks chan bool) {
    for true {
        select {
        case url := <-queue:
            fmt.Println("doing work!", url, "worknumber", worknumber)
            processData(url) // HTTP download
            done <- true
        case <-ks:
            fmt.Println("worker halted, number", worknumber)
            return
        }
    }
}

func main() {
    start := time.Now()
    flag.Parse()
    fmt.Print(strings.Join(flag.Args(), "\n"))
    if *filename == "REQUIRED" {
        return
    }

    csvfile, err := os.Open(*filename)
    if err != nil {
        fmt.Println(err)
        return
    }
    count, _ := lineCounter(csvfile)
    fmt.Printf("Total count: %d\n", count)
    csvfile.Seek(0, 0)

    defer csvfile.Close()

    //bar := pb.StartNew(count)
    bar := progressbar.NewOptions(count)
    bar.RenderBlank()

    reader := csv.NewReader(csvfile)

    //channel for terminating the workers
    killsignal := make(chan bool)

    //queue of jobs
    q := make(chan []string)
    // done channel takes the result of the job
    done := make(chan bool)

    numberOfWorkers := *numChannels
    for i := 0; i < numberOfWorkers; i++ {
        go worker(q, i, done, killsignal)
    }

    i := 0
    for {
        record, err := reader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            fmt.Println(err)
            return
        }
        i++

        go func(r []string, i int) {
            q <- r
            bar.Add(1)
        }(record, i)
    }

    // a deadlock occurs if c >= numberOfJobs
    for c := 0; c < count; c++ {
        <-done
    }

    fmt.Println("finished")

    // cleaning workers
    close(killsignal)
    time.Sleep(2 * time.Second)

    fmt.Printf("\n%2fs", time.Since(start).Seconds())
}

My issue here is that it opens a lot of goroutines, use all the memory and crash.

What would be the best way to limit it?


问:
Horizontal flyout menu using display:inline
is it possible to create a horizontal flyout menu without using float?
I tried it in this fiddle with display:inline.
My aim was to have a result like the second example.
Unfortunately I had to work with float ...

Do you have any idea what I am missing?
If you have a link, etc. post it, please.

Your help is much appreciated.

EDIT:
This is how far I got...
http://jsfiddle.net/gbMsq/2/

The second list-item should have another list under it. But it is set under the first list-item.

答:
You can try using absolute positioning like this:

```<code>li > ul { position: absolute; }
</code>```

Demo

The downside/advantage is that the inner ul is taken out of flow, as seen in my demo. It might be good if you want a dropdown menu, if not, you can add some height to the outer ul, or stick to floats.

Body:
You can try using absolute positioning like this:

li > ul { position: absolute; }

Demo

The downside/advantage is that the inner ul is taken out of flow, as seen in my demo. It might be good if you want a dropdown menu, if not, you can add some height to the outer ul, or stick to floats.


问:
Java 8 stream - merge collections of objects sharing the same Id
I have a collection of invoices :

```<code>class Invoice {
  int month;
  BigDecimal amount
}
</code>```

I'd like to merge these invoices, so I get one invoice per month, and the amount is the sum of the invoices amount for this month.

For example:

```<code>invoice 1 : {month:1,amount:1000}
invoice 2 : {month:1,amount:300}
invoice 3 : {month:2,amount:2000}
</code>```

Output:

```<code>invoice 1 : {month:1,amount:1300}
invoice 2 : {month:2,amount:2000}
</code>```

How can I do this with java 8 streams?

EDIT : as my Invoice class was mutable and it was not a problem to modify them, I choosed Eugene's solution

```<code>Collection<Invoice>  invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
                left.setAmount(left.getAmount().add(right.getAmount()));
                return left;
            })).values();
</code>```

答:
I think if your application do not support lambda than this might be a suitable answer eg (Android minSdkVersion=16 do not support lambda) </p>

```<code>public static List<Invoice> mergeAmount(List<Invoice> invoiceList) {
 List<Invoice> newInvoiceList = new ArrayList<>();
  for(Invoice inv: invoiceList) {
    boolean isThere = false;
     for (Invoice inv1: newInvoiceList) {
      if (inv1.getAmount() == inv.getAmount()) {
         inv1.setAmount(inv1.getAmoount()+inv.getAmount());
         isThere = true;
         break;
       }
     }
    if (!isThere) {
        newInvoiceList.add(inv);
    }
 }
  return newInvoiceList;
}
</code>```

Body:
I have a collection of invoices :

class Invoice {
  int month;
  BigDecimal amount
}

I'd like to merge these invoices, so I get one invoice per month, and the amount is the sum of the invoices amount for this month.

For example:

invoice 1 : {month:1,amount:1000}
invoice 2 : {month:1,amount:300}
invoice 3 : {month:2,amount:2000}

Output:

invoice 1 : {month:1,amount:1300}
invoice 2 : {month:2,amount:2000}

How can I do this with java 8 streams?

EDIT : as my Invoice class was mutable and it was not a problem to modify them, I choosed Eugene's solution

Collection<Invoice>  invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
                left.setAmount(left.getAmount().add(right.getAmount()));
                return left;
            })).values();

Body:
I think if your application do not support lambda than this might be a suitable answer eg (Android minSdkVersion=16 do not support lambda)

public static List<Invoice> mergeAmount(List<Invoice> invoiceList) {
 List<Invoice> newInvoiceList = new ArrayList<>();
  for(Invoice inv: invoiceList) {
    boolean isThere = false;
     for (Invoice inv1: newInvoiceList) {
      if (inv1.getAmount() == inv.getAmount()) {
         inv1.setAmount(inv1.getAmoount()+inv.getAmount());
         isThere = true;
         break;
       }
     }
    if (!isThere) {
        newInvoiceList.add(inv);
    }
 }
  return newInvoiceList;
}


问:
Disable ion-content top and bottom bounce
How do I disable top and bottom bounce in ion-content?  I've tried adding overflow-scroll and no such luck:

```<code><ion-content [scrollY]="!disableScroll" overflow-scroll="false">
</ion-content>
</code>```

答:
Use forceOverscroll for that

```<code><ion-content forceOverscroll="false">

</ion-content>
</code>```

Body:
How do I disable top and bottom bounce in ion-content?  I've tried adding overflow-scroll and no such luck:

<ion-content [scrollY]="!disableScroll" overflow-scroll="false">
</ion-content>

Body:
Use forceOverscroll for that

<ion-content forceOverscroll="false">

</ion-content>


问:
undefined method `model_name' for nil:NilClass problem with simple_form form
simple_form creates a problem:

I'll explain what I did: i've 2 scaffold:

questions/_form.html.erb

```<code><%= simple_form_for(@question ) do |f| %>
  <%= f.error_notification %>
  <div class="field">
    <div class="control">
      <%= render "info_users" %>

      <%= f.input :question, label: "Quelle est votre question ou votre suggestion ?", input_html: { class: "textarea "}, wrapper: false, label_html: {class: "label"}, placeholder: "Commencez vos Questions par << Comment >>, << Pourquoi>>, << Que >>, etc...", autofocus: true %>
    </div>
  </div>
  <%= f.button :submit,'Ajouter Une Question', class: "button is-info is-rounded " %>
<% end %>
</code>```

courses/_form.html.erb

```<code><%= simple_form_for(@course) do |f| %>
  <%= f.error_notification %>
  # here go all inputs
  <%= f.button :submit," Créer le Cours" ,class: "button is-info is-large is-rounded" %>
<% end %>
</code>```

Now I use these two forms in my home view and that's when simple_form becomes a problem. Here is the call code of the partials in home/_feed.html.erb

Note: I created a partial _feed.html.erb in home to render it in index.html.erb

home/_feed.html.erb

```<code><% if user_signed_in? %>
  <article class="media box">
    <div class="media-content">
      <%= render :partial => "questions/form" %>
    </div>
    <div class="media-content">
      <%= render :partial => "courses/form" %>
    </div>
  </article>
<% end %>
</code>```

答:
You have no defined @question and @course for forms, because now you render them from HomeController#index. Also, it is bad idea to use instance variables in partials, because it is hard to say, where from they come to the partial. Use only local variables and pass them to the partial

```<code># questions/_form.html.erb
<%= simple_form_for(question) do |f| %>
  # form code goes here
<% end %>

# the same for courses/_form.html.erb, change @course to course

# home/_feed.html.erb
<%= render partial: "questions/form", question: @question %>
<%= render partial: "courses/form", course: @course %>
</code>```

Define instance variables in home_controller.rb

```<code>def index
  @question = current_user.questions.new # I suppose you want to create associated records
  @course = current_user.courses.new
end
</code>```

Body:
simple_form creates a problem:

I'll explain what I did: i've 2 scaffold:

questions/_form.html.erb

<%= simple_form_for(@question ) do |f| %>
  <%= f.error_notification %>

      <%= render "info_users" %>

      <%= f.input :question, label: "Quelle est votre question ou votre suggestion ?", input_html: { class: "textarea "}, wrapper: false, label_html: {class: "label"}, placeholder: "Commencez vos Questions par << Comment >>, << Pourquoi>>, << Que >>, etc...", autofocus: true %>

  <%= f.button :submit,'Ajouter Une Question', class: "button is-info is-rounded " %>
<% end %>

courses/_form.html.erb

<%= simple_form_for(@course) do |f| %>
  <%= f.error_notification %>
  # here go all inputs
  <%= f.button :submit," Créer le Cours" ,class: "button is-info is-large is-rounded" %>
<% end %>

Now I use these two forms in my home view and that's when simple_form becomes a problem. Here is the call code of the partials in home/_feed.html.erb

Note: I created a partial _feed.html.erb in home to render it in index.html.erb

home/_feed.html.erb

<% if user_signed_in? %>

      <%= render :partial => "questions/form" %>

      <%= render :partial => "courses/form" %>

<% end %>

Body:
You have no defined @question and @course for forms, because now you render them from HomeController#index. Also, it is bad idea to use instance variables in partials, because it is hard to say, where from they come to the partial. Use only local variables and pass them to the partial

# questions/_form.html.erb
<%= simple_form_for(question) do |f| %>
  # form code goes here
<% end %>

# the same for courses/_form.html.erb, change @course to course

# home/_feed.html.erb
<%= render partial: "questions/form", question: @question %>
<%= render partial: "courses/form", course: @course %>

Define instance variables in home_controller.rb

def index
  @question = current_user.questions.new # I suppose you want to create associated records
  @course = current_user.courses.new
end


问:
How to insert an array to SQLite?
I need to insert an array loaded by JSON into an SQLite database. Any help is appreciated.</p>

```<code>JSONObject jsonObj = new JSONObject(jsonStr);

                    JSONArray sites = jsonObj.getJSONArray("Sites");

                    for (int i = 0; i < sites.length(); i++) {
                        JSONObject c = sites.getJSONObject(i);

                        String id = c.getString("id");
                        String nam = c.getString("names");
                        String loc = c.getString("location");

                        HashMap<String, String> sit = new HashMap<>();

                        sit.put("id", id);
                        sit.put("names", name);
                        sit.put("location", loc);

                        array_sites.add(sit);
</code>```

答:
Try this:

```<code>public void addData(ArrayList<String> list){

    int size = list.size();

    SQLiteDatabase db = getWritableDatabase();

    try{
       for (int i = 0; i < size ; i++){
           ContentValues cv = new ContentValues();
           cv.put(KEY_NAME, list.get(i));
           Log.d("Data Inserted ",""+ cv);
           db.insertOrThrow(TABLE_NAME, null, cv);
       }
       db.close();
    }catch (Exception e){
    Log.e("Exception>>>>", e + " ");
}
</code>```

Call from where you store your data

```<code>addData(array_sites);
</code>```

I suggested for ArrayList<String>, You can use your own ArrayList<YourDataType>.

Title: How to insert an array to SQLite?

Body:
I need to insert an array loaded by JSON into an SQLite database. Any help is appreciated.

JSONObject jsonObj = new JSONObject(jsonStr);

                    JSONArray sites = jsonObj.getJSONArray("Sites");

                    for (int i = 0; i < sites.length(); i++) {
                        JSONObject c = sites.getJSONObject(i);

                        String id = c.getString("id");
                        String nam = c.getString("names");
                        String loc = c.getString("location");

                        HashMap<String, String> sit = new HashMap<>();

                        sit.put("id", id);
                        sit.put("names", name);
                        sit.put("location", loc);

                        array_sites.add(sit);

Body:
Try this:

public void addData(ArrayList<String> list){

    int size = list.size();

    SQLiteDatabase db = getWritableDatabase();

    try{
       for (int i = 0; i < size ; i++){
           ContentValues cv = new ContentValues();
           cv.put(KEY_NAME, list.get(i));
           Log.d("Data Inserted ",""+ cv);
           db.insertOrThrow(TABLE_NAME, null, cv);
       }
       db.close();
    }catch (Exception e){
    Log.e("Exception>>>>", e + " ");
}

Call from where you store your data

addData(array_sites);

I suggested for ArrayList<String>, You can use your own ArrayList<YourDataType>.


问:
How to display the names of the sheets of xls file using PHPexcel?
How to display the names of the sheets of xls file using PHPexcel?</p>

```<code>$objWorksheet = $objPHPExcel->setActiveSheetIndex(0); ???
</code>```

答:
its return all sheet in an array</p>

```<code>    $this->load->library('PHPExcel/Classes/PHPExcel');
    $excelReader = PHPExcel_IOFactory::createReaderForFile($fileTempName);
    $excelObj = $excelReader->load($fileTempName);
    //$worksheet = $excelObj->getSheet(0);
    $worksheet = $excelObj->getSheetNames();

    echo "```";
    print_r($worksheet);
    die;
</code>```

Body:
How to display the names of the sheets of xls file using PHPexcel?

$objWorksheet = $objPHPExcel->setActiveSheetIndex(0); ???

Body:
its return all sheet in an array

    $this->load->library('PHPExcel/Classes/PHPExcel');
    $excelReader = PHPExcel_IOFactory::createReaderForFile($fileTempName);
    $excelObj = $excelReader->load($fileTempName);
    //$worksheet = $excelObj->getSheet(0);
    $worksheet = $excelObj->getSheetNames();

    echo "<pre>";
    print_r($worksheet);
    die;


问:
jQuery convert element ids into comma seperated string
I have a simple html and jquery script like below, I am trying to get a comma seperated list of data-item-id so would look like...

```<code>1,2,3,4,5
</code>```

var items = $('.container').children();
console.log(items);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div></code>```

I have grabbed the items but how can I convert this into the comma seperated string?

答:
You can also apply some features of ES5 and ES6 for a shorter solution. And without jQuery.

let itemsIds = [...document.getElementsByClassName("item")]
    .map(elem => elem.getAttribute("data-item-id"))
    .join(',');
console.log(itemsIds);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div></code>```

Body:
I have a simple html and jquery script like below, I am trying to get a comma seperated list of data-item-id so would look like...

1,2,3,4,5

var items = $('.container').children();
console.log(items);

Item 1

Item 2

Item 3

Item 4

Item 5

I have grabbed the items but how can I convert this into the comma seperated string?

Body:
You can also apply some features of ES5 and ES6 for a shorter solution. And without jQuery.

let itemsIds = [...document.getElementsByClassName("item")]
    .map(elem => elem.getAttribute("data-item-id"))
    .join(',');
console.log(itemsIds);

<div class="container">
  <div class="item" data-item-id="1">Item 1</div>
  <div class="item" data-item-id="2">Item 2</div>
  <div class="item" data-item-id="3">Item 3</div>
  <div class="item" data-item-id="4">Item 4</div>
  <div class="item" data-item-id="5">Item 5</div>
</div>


问:
"error": "InvalidRegistration" while sending push notifications
I am implementing FCM push notifications using  FirebasePushNotificationPlugin in Xamarin.Forms. In iOS project, in AppDelegate when RegisteredForRemoteNotifications method calling deviceToken generating but when I am sending notification for generated token by Postman I am getting error.

{ "multicast_id": 8631208504861228784, "success": 0, "failure": 1,
  "canonical_ids": 0, "results": [ { "error": "InvalidRegistration" } ]
  }

This is the code I have on AppDelegate got from here:

```<code>public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();
    LoadApplication(new App());

    FirebasePushNotificationManager.Initialize(options, new NotificationUserCategory[]
    {
        new NotificationUserCategory("message",new List<NotificationUserAction> {
            new NotificationUserAction("Reply","Reply",NotificationActionType.Foreground)
        }),
        new NotificationUserCategory("request",new List<NotificationUserAction> {
            new NotificationUserAction("Accept","Accept"),
            new NotificationUserAction("Reject","Reject",NotificationActionType.Destructive)
        })
    });

    return base.FinishedLaunching(app, options);
}

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
    Console.WriteLine("Token- - - :  "+deviceToken);
}

public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
    FirebasePushNotificationManager.RemoteNotificationRegistrationFailed(error);
}

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
    FirebasePushNotificationManager.DidReceiveMessage(userInfo);
    System.Console.WriteLine(userInfo);
    completionHandler(UIBackgroundFetchResult.NewData);
}
</code>```

data object in Postman when sending sample notification

```<code>{
 "to":"79f64b43339859a329a935f7a3e417ecc1599fbb5d6935afbooa3b4291c07fa7",
 "notification" : {
 "body" : "New task",
 "content_available" : true,
 "priority" : "high",
 "color":"Page1",
 "title":"Announcement"
 },
 "data" : {
 "color":"Page1",
 "title":"title",
 "content_available" : true,
 "body" : "New Announcement ad"

}
}
</code>```

Body of Postman

These are the Provisioning profiles setting from Visual Studio

How can I solve this issue?

答:
I'm not familiar with Xamarin. But I worked with FCM a lot.

I think you are getting wrong token. Using deviceToken won't work with push notification from FCM. I did a search and maybe you have to get it from

var fcmToken = FirebaseInstanceId.Instance.Token;

More detail:
https://learn.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=macos

Body:
I am implementing FCM push notifications using  FirebasePushNotificationPlugin in Xamarin.Forms. In iOS project, in AppDelegate when RegisteredForRemoteNotifications method calling deviceToken generating but when I am sending notification for generated token by Postman I am getting error.

{ "multicast_id": 8631208504861228784, "success": 0, "failure": 1,
  "canonical_ids": 0, "results": [ { "error": "InvalidRegistration" } ]
  }

This is the code I have on AppDelegate got from here:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();
    LoadApplication(new App());

    FirebasePushNotificationManager.Initialize(options, new NotificationUserCategory[]
    {
        new NotificationUserCategory("message",new List<NotificationUserAction> {
            new NotificationUserAction("Reply","Reply",NotificationActionType.Foreground)
        }),
        new NotificationUserCategory("request",new List<NotificationUserAction> {
            new NotificationUserAction("Accept","Accept"),
            new NotificationUserAction("Reject","Reject",NotificationActionType.Destructive)
        })
    });

    return base.FinishedLaunching(app, options);
}

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    FirebasePushNotificationManager.DidRegisterRemoteNotifications(deviceToken);
    Console.WriteLine("Token- - - :  "+deviceToken);
}

public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
    FirebasePushNotificationManager.RemoteNotificationRegistrationFailed(error);
}

public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
    FirebasePushNotificationManager.DidReceiveMessage(userInfo);
    System.Console.WriteLine(userInfo);
    completionHandler(UIBackgroundFetchResult.NewData);
}

data object in Postman when sending sample notification

{
 "to":"79f64b43339859a329a935f7a3e417ecc1599fbb5d6935afbooa3b4291c07fa7",
 "notification" : {
 "body" : "New task",
 "content_available" : true,
 "priority" : "high",
 "color":"Page1",
 "title":"Announcement"
 },
 "data" : {
 "color":"Page1",
 "title":"title",
 "content_available" : true,
 "body" : "New Announcement ad"

}
}

Body of Postman

These are the Provisioning profiles setting from Visual Studio

How can I solve this issue?


问:
npm install -g react-native-cli - showing error
heckPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!</p>

答: This is due to permission related issue, use sudo npm i -d react-native-cli


问:
How To Set Ajax Url with Variable
i want to add some string to the url in ajax process, but fail every time i access the function.
when i submit the form it only access this url 'Master_data/' </p>

```<code>var jenis_submit = document.getElementById('jenis_submit');
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

$.ajax({
    url: '<?php echo base_url();?>Master_data/' + submit_url,
    method: 'POST',
    data: dataKirim,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        // console.log(data);
        $('#notif').html(data);
    }
});
</code>```

答:
Try this:</p>

```<code>var jenis_submit = document.getElementById('jenis_submit');
var submit_url   = '';

if (jenis_submit == '1') {
    submit_url = "func_save_instansi";
} else if(jenis_submit == '2') {
    submit_url = "func_update_instansi";
}

var post_url = '<?php echo base_url('Master_data'); ?>' + '/' + submit_url;

$.ajax({
     type: "POST",
     url: post_url,
     data: dataKirim,
     beforeSend: function() {
       // you can show a preloader here
     }
 }).done(function(data) {
     // hide the preloader
     // console.log(data);
     $('#notif').html(data);
 }).fail(function() {
   // hide the preloader
   // show an error message
 });
</code>```

Title: How To Set Ajax Url with Variable

Body:
i want to add some string to the url in ajax process, but fail every time i access the function.
when i submit the form it only access this url 'Master_data/'

var jenis_submit = document.getElementById('jenis_submit');
var submit_url = '';
if (jenis_submit == '1') {

    submit_url = "func_save_instansi";
} else if (jenis_submit == '2') {

    submit_url = "func_update_instansi";
}

$.ajax({
    url: '<?php echo base_url();?>Master_data/' + submit_url,
    method: 'POST',
    data: dataKirim,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
        // console.log(data);
        $('#notif').html(data);
    }
});

Body:
Try this:

var jenis_submit = document.getElementById('jenis_submit');
var submit_url   = '';

if (jenis_submit == '1') {
    submit_url = "func_save_instansi";
} else if(jenis_submit == '2') {
    submit_url = "func_update_instansi";
}

var post_url = '<?php echo base_url('Master_data'); ?>' + '/' + submit_url;

$.ajax({
     type: "POST",
     url: post_url,
     data: dataKirim,
     beforeSend: function() {
       // you can show a preloader here
     }
 }).done(function(data) {
     // hide the preloader
     // console.log(data);
     $('#notif').html(data);
 }).fail(function() {
   // hide the preloader
   // show an error message
 });


问:
Getting incorrect text when extracting text from image using Python (Dot Matrix OCR)
I am trying to extracting the text from image using the OpenCV via python but getting the incorrect result and mostly getting special characters,please correct what's wrong here

```<code>import cv2
import numpy as np
import pytesseract
from PIL import Image
import os

def get_string(img_path):
    # Read image with opencv
    img = cv2.imread(img_path)

    # Convert to gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply dilation and erosion to remove some noise
    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)

    # Write image after removed noise
    cv2.imwrite(src_path + "removed_noise.png", img)

    # Write the image after apply opencv to do some ...
    cv2.imwrite(src_path + "thres.png", img)

    # Recognize text with tesseract for python
    result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))

    return result

print('--- Start recognize text from image ---')
print(get_string("image_full_path.png"))
</code>```

Tried Googling but none of things helped. can some one point to right code
output:

```<code>i } i er Oe a Pee pe be a

i j rye Se) PEE eet et ae ec?

j } a « o cy ” a @

: i : } Cand RET RE Petr eet PI ret

nif wad

fs | : : } wert
| ; a] |
wee | a
— th | cE i
ae | i
“ oe i j EYE }
en ct
. a f ae " i
- — ; - i! }
</code>```

答:
The image is too bright and the contrast is not ideal.

You need to improve the contrast and brightness.

After that apply some morphological operations to remove noise.

Then follow this tips on how to improve dot matrix printer fonts for OCR:

Find the Edges

Threshold the Greyscale Image

Blur the Black & White Image

Body:
I am trying to extracting the text from image using the OpenCV via python but getting the incorrect result and mostly getting special characters,please correct what's wrong here

import cv2
import numpy as np
import pytesseract
from PIL import Image
import os

def get_string(img_path):
    # Read image with opencv
    img = cv2.imread(img_path)

    # Convert to gray
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply dilation and erosion to remove some noise
    kernel = np.ones((1, 1), np.uint8)
    img = cv2.dilate(img, kernel, iterations=1)
    img = cv2.erode(img, kernel, iterations=1)

    # Write image after removed noise
    cv2.imwrite(src_path + "removed_noise.png", img)

    # Write the image after apply opencv to do some ...
    cv2.imwrite(src_path + "thres.png", img)

    # Recognize text with tesseract for python
    result = pytesseract.image_to_string(Image.open(src_path + "thres.png"))

    return result

print('--- Start recognize text from image ---')
print(get_string("image_full_path.png"))

Tried Googling but none of things helped. can some one point to right code
output:

i } i er Oe a Pee pe be a

i j rye Se) PEE eet et ae ec?

j } a « o cy ” a @

: i : } Cand RET RE Petr eet PI ret

nif wad

fs | : : } wert
| ; a] |
wee | a
— th | cE i
ae | i
“ oe i j EYE }
en ct
. a f ae " i
- — ; - i! }


答:
Like this?

Working Example: here

example 3 uses display: inline-block instead of float, and vertically aligns the blocks to the top

Updated

fiddle updated to show the first example and the latest one in the OP.. both use the same CSS

Title: Horizontal flyout menu using display:inline

Body:
is it possible to create a horizontal flyout menu without using float?
I tried it in this fiddle with display:inline.
My aim was to have a result like the second example.
Unfortunately I had to work with float ...

Do you have any idea what I am missing?
If you have a link, etc. post it, please.

Your help is much appreciated.

EDIT:
This is how far I got...
http://jsfiddle.net/gbMsq/2/

The second list-item should have another list under it. But it is set under the first list-item.


问:
How to sort strings in java , order shoud display Capital Strings first
Need to sort strings in java in a case sensitive, but Capital letters should display first.

What I tried:

```<code>List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
l.stream().sorted(String.CASE_INSENSITIVE_ORDER);
System.out.println(l);`
</code>```

Output:

```<code>[aaa, AAA, AAA, aaa, BBB, ccc, CCC]
</code>```

Expecting Output:

```<code>[AAA,AAA,aaa,aaa,BBB,CCC,ccc]
</code>```

答:
Following code help you to sorting string in CASE_INSENSITIVE_ORDER. Here you need two time sorting for list.</p>

```<code>public static void main(String[] args) {
  List<String> l = Arrays.asList("a", "A", "A", "a", "B", "c", "C");
  Collections.sort(l);
  Collections.sort(l, String.CASE_INSENSITIVE_ORDER);
  System.out.println(l);
}
</code>```

Body:
Need to sort strings in java in a case sensitive, but Capital letters should display first.

What I tried:

List<String> l = Arrays.asList("aaa","AAA","AAA","aaa","BBB","ccc","CCC");
l.stream().sorted(String.CASE_INSENSITIVE_ORDER);
System.out.println(l);`

Output:

[aaa, AAA, AAA, aaa, BBB, ccc, CCC]

Expecting Output:

[AAA,AAA,aaa,aaa,BBB,CCC,ccc]

Body:
Following code help you to sorting string in CASE_INSENSITIVE_ORDER. Here you need two time sorting for list.

public static void main(String[] args) {
  List<String> l = Arrays.asList("a", "A", "A", "a", "B", "c", "C");
  Collections.sort(l);
  Collections.sort(l, String.CASE_INSENSITIVE_ORDER);
  System.out.println(l);
}


问:
Copying files from a series of directories based off a list in a text file
I am attempting to use either rsync or cp in a for loop to copy files matching a list of 200 of names stored on new lines in a .txt file that match filenames with the .pdbqt extension that are in a series of subdirectories with one parent folder. The .txt file looks as follows:

```<code>file01
file02
file08
file75
file45
...
</code>```

I have attempted to use rsync with the following command:

```<code>rsync -a /home/ubuntu/Project/files/pdbqt/*/*.pdbqt \
--files-from=/home/ubuntu/Project/working/output.txt \
/home/ubuntu/Project/files/top/
</code>```

When I run the rsync command I receive:

```<code>rsync error: syntax or usage error (code 1) at options.c(2346) [client=3.1.2]
</code>```

I have written a bash script as follows in an attempt to get that to work:

```<code>#!/bin/bash
for i in "$(cat /home/ubuntu/Project/working/output.txt | tr '\n' '')"; do
    cp /home/ubuntu/Project/files/pdbqt/*/"$i".pdbqt /home/ubuntu/Project/files/top/;
done
</code>```

I understand cat isn't a great command to use but I could not figure out an alternate solution to it, as I am still new to using bash. Running that I get the following error:

```<code>tr: when not truncating set1, string2 must be non-empty
cp: cannot stat '/home/ubuntu/Project/files/pdbqt/*/.pdbqt': No such file or directory
</code>```

I assume that the cp error is thrown as a result of the tr error but I am not sure how else to get rid of the \n that is read from the new line separated list.

The expected results are that from the subdirectories in /pdbqt/ with the 12000 .pdbqt files the 200 files from the output.txt list would be copied from those subdirectories into the /top/ directory.

答:
for loops are good when your data is already in shell variables.  When reading in data from a file, while ... read loops work better.  In your case, try:

```<code>while IFS= read -r file; do  cp -i -- /home/ubuntu/Project/files/pdbqt/*/"$file".pdbqt  /home/ubuntu/Project/files/top/; done </home/ubuntu/Project/working/output.txt
</code>```

or, if you find the multiline version more readable:

```<code>while IFS= read -r file
do
    cp -i -- /home/ubuntu/Project/files/pdbqt/*/"$file".pdbqt /home/ubuntu/Project/files/top/
done </home/ubuntu/Project/working/output.txt
</code>```

How it works

while IFS= read -r file; do

This starts a while loop reading one line at a time.  IFS= tells bash not to truncate white space from the line and -r tells read not to mangle backslashes.  The line is stored in the shell variable called file.

cp -i -- /home/ubuntu/Project/files/pdbqt/*/"$file".pdbqt /home/ubuntu/Project/files/top/

This copies the file.  -i tells cp to ask before overwriting an existing file.

done </home/ubuntu/Project/working/output.txt

This marks the end of the while loop and tells the shell to get the input for the loop from /home/ubuntu/Project/working/output.txt

Body:
I am attempting to use either rsync or cp in a for loop to copy files matching a list of 200 of names stored on new lines in a .txt file that match filenames with the .pdbqt extension that are in a series of subdirectories with one parent folder. The .txt file looks as follows:

file01
file02
file08
file75
file45
...

I have attempted to use rsync with the following command:

rsync -a /home/ubuntu/Project/files/pdbqt/*/*.pdbqt \
--files-from=/home/ubuntu/Project/working/output.txt \
/home/ubuntu/Project/files/top/

When I run the rsync command I receive:

rsync error: syntax or usage error (code 1) at options.c(2346) [client=3.1.2]

I have written a bash script as follows in an attempt to get that to work:

#!/bin/bash
for i in "$(cat /home/ubuntu/Project/working/output.txt | tr '\n' '')"; do
    cp /home/ubuntu/Project/files/pdbqt/*/"$i".pdbqt /home/ubuntu/Project/files/top/;
done

I understand cat isn't a great command to use but I could not figure out an alternate solution to it, as I am still new to using bash. Running that I get the following error:

tr: when not truncating set1, string2 must be non-empty
cp: cannot stat '/home/ubuntu/Project/files/pdbqt/*/.pdbqt': No such file or directory

I assume that the cp error is thrown as a result of the tr error but I am not sure how else to get rid of the \n that is read from the new line separated list.

The expected results are that from the subdirectories in /pdbqt/ with the 12000 .pdbqt files the 200 files from the output.txt list would be copied from those subdirectories into the /top/ directory.

Body:
for loops are good when your data is already in shell variables.  When reading in data from a file, while ... read loops work better.  In your case, try:

while IFS= read -r file; do  cp -i -- /home/ubuntu/Project/files/pdbqt/*/"$file".pdbqt  /home/ubuntu/Project/files/top/; done </home/ubuntu/Project/working/output.txt

or, if you find the multiline version more readable:

while IFS= read -r file
do
    cp -i -- /home/ubuntu/Project/files/pdbqt/*/"$file".pdbqt /home/ubuntu/Project/files/top/
done </home/ubuntu/Project/working/output.txt

How it works

while IFS= read -r file; do

This starts a while loop reading one line at a time.  IFS= tells bash not to truncate white space from the line and -r tells read not to mangle backslashes.  The line is stored in the shell variable called file.

cp -i -- /home/ubuntu/Project/files/pdbqt/*/"$file".pdbqt /home/ubuntu/Project/files/top/

This copies the file.  -i tells cp to ask before overwriting an existing file.

done </home/ubuntu/Project/working/output.txt

This marks the end of the while loop and tells the shell to get the input for the loop from /home/ubuntu/Project/working/output.txt


问:
Error saving a string longer than 1500 bytes in Datastore from Dataflow api
Dataflow job is throwing this error message when I try to save a very long string: The value of property "myProperty" is longer than 1500 bytes., code=INVALID_ARGUMENT.

There is an error when following Google's DatastoreWordCount sample and saving a string longuer then 1500 bytes.

I know that when using Datastore API, I am able to save strings that are longer than 1500 bytes by saving the property as com.google.appengine.api.datastore.Text. However, There is no alternative in DatastoreWordCount sample or in DatastoreHelper class documentation that could indicate that Text type is supported.

Could be a way to save such long strings using that api so that it could be read as com.google.appengine.api.datastore.Text?

The full error message is as follow:

```<code>java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: com.google.datastore.v1.client.DatastoreException: The value of property "dalekTestExecutions" is longer than 1500 bytes., code=INVALID_ARGUMENT
    at com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn$1.output(SimpleParDoFn.java:162)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnContext.outputWindowedValue(DoFnRunnerBase.java:288)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnContext.outputWindowedValue(DoFnRunnerBase.java:284)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnProcessContext$1.outputWindowedValue(DoFnRunnerBase.java:508)
    at com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsAndCombineDoFn.closeWindow(GroupAlsoByWindowsAndCombineDoFn.java:205)
    at com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsAndCombineDoFn.processElement(GroupAlsoByWindowsAndCombineDoFn.java:192)
    at com.google.cloud.dataflow.sdk.util.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:49)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.processElement(DoFnRunnerBase.java:139)
    at com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:190)
    at com.google.cloud.dataflow.sdk.runners.worker.ForwardingParDoFn.processElement(ForwardingParDoFn.java:42)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerLoggingParDoFn.processElement(DataflowWorkerLoggingParDoFn.java:47)
    at com.google.cloud.dataflow.sdk.util.common.worker.ParDoOperation.process(ParDoOperation.java:55)
    at com.google.cloud.dataflow.sdk.util.common.worker.OutputReceiver.process(OutputReceiver.java:52)
    at com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:224)
    at com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation.start(ReadOperation.java:185)
    at com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:72)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.executeWork(DataflowWorker.java:287)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.doWork(DataflowWorker.java:223)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.getAndPerformWork(DataflowWorker.java:173)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.doWork(DataflowWorkerHarness.java:193)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:173)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:160)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
DataStore create index for each property so there is a default limit of 1500 bytes on properties. Now if you need to store data something like big JSON then you can specify that index is not needed for this property in following way:

```<code>Entity newEntity =
                Entity.newBuilder(key)
                        .set("time", Timestamp.parseTimestamp("1970-01-01T00:00:00Z"))
                        .set("message", StringValue.newBuilder(JSON).setExcludeFromIndexes(true).build())
                        .build();
</code>```

This way you will be able to save data of bigger size rather than default limit of 1500 bytes.

Body:
Dataflow job is throwing this error message when I try to save a very long string: The value of property "myProperty" is longer than 1500 bytes., code=INVALID_ARGUMENT.

There is an error when following Google's DatastoreWordCount sample and saving a string longuer then 1500 bytes.

I know that when using Datastore API, I am able to save strings that are longer than 1500 bytes by saving the property as com.google.appengine.api.datastore.Text. However, There is no alternative in DatastoreWordCount sample or in DatastoreHelper class documentation that could indicate that Text type is supported.

Could be a way to save such long strings using that api so that it could be read as com.google.appengine.api.datastore.Text?

The full error message is as follow:

java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: java.lang.RuntimeException: com.google.cloud.dataflow.sdk.util.UserCodeException: com.google.datastore.v1.client.DatastoreException: The value of property "dalekTestExecutions" is longer than 1500 bytes., code=INVALID_ARGUMENT
    at com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn$1.output(SimpleParDoFn.java:162)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnContext.outputWindowedValue(DoFnRunnerBase.java:288)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnContext.outputWindowedValue(DoFnRunnerBase.java:284)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase$DoFnProcessContext$1.outputWindowedValue(DoFnRunnerBase.java:508)
    at com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsAndCombineDoFn.closeWindow(GroupAlsoByWindowsAndCombineDoFn.java:205)
    at com.google.cloud.dataflow.sdk.util.GroupAlsoByWindowsAndCombineDoFn.processElement(GroupAlsoByWindowsAndCombineDoFn.java:192)
    at com.google.cloud.dataflow.sdk.util.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:49)
    at com.google.cloud.dataflow.sdk.util.DoFnRunnerBase.processElement(DoFnRunnerBase.java:139)
    at com.google.cloud.dataflow.sdk.runners.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:190)
    at com.google.cloud.dataflow.sdk.runners.worker.ForwardingParDoFn.processElement(ForwardingParDoFn.java:42)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerLoggingParDoFn.processElement(DataflowWorkerLoggingParDoFn.java:47)
    at com.google.cloud.dataflow.sdk.util.common.worker.ParDoOperation.process(ParDoOperation.java:55)
    at com.google.cloud.dataflow.sdk.util.common.worker.OutputReceiver.process(OutputReceiver.java:52)
    at com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:224)
    at com.google.cloud.dataflow.sdk.util.common.worker.ReadOperation.start(ReadOperation.java:185)
    at com.google.cloud.dataflow.sdk.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:72)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.executeWork(DataflowWorker.java:287)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.doWork(DataflowWorker.java:223)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorker.getAndPerformWork(DataflowWorker.java:173)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.doWork(DataflowWorkerHarness.java:193)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:173)
    at com.google.cloud.dataflow.sdk.runners.worker.DataflowWorkerHarness$WorkerThread.call(DataflowWorkerHarness.java:160)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Body:
DataStore create index for each property so there is a default limit of 1500 bytes on properties. Now if you need to store data something like big JSON then you can specify that index is not needed for this property in following way:

Entity newEntity =
                Entity.newBuilder(key)
                        .set("time", Timestamp.parseTimestamp("1970-01-01T00:00:00Z"))
                        .set("message", StringValue.newBuilder(JSON).setExcludeFromIndexes(true).build())
                        .build();

This way you will be able to save data of bigger size rather than default limit of 1500 bytes.


问:
Is it an eclipse or maven-compiler-plugin bug, the generics Class cast issue?
I have a code like this:

```<code>protected <T> T doSomething(String someParam, Class<T> clazz) {
...
}
</code>```

which I use in a TestCase class:

```<code>Class clazz = MyClass.class;
MyClass MyClass = someObject.doSomething(someString, clazz);
</code>```

This code gives a warning in eclipse:

Class is a raw type. References to generic type Class should be parameterized

and

Multiple markers at this line

      - Type safety: Unchecked invocation doSomething(String, Class) of the generic method doSomething(String, Class) of type MyClass

      - Type safety: The expression of type Class needs unchecked conversion to conform to Class

When I run this code (test) in eclipse - everything works perfectly. When I do it through "mvn clean install" through command prompt, I get:

C:\pathToProject\src\test\java\packagesPath\MyTestCase.java:[xx,xxx] incompatible types found   :

  java.lang.Object

  required: com.somePackagePath.MyClass

But when providing:

```<code>Class<MyClass> clazz = MyClass.class;
MyClass MyClass = someObject.doSomething(someString, clazz);
</code>```

I don't get any errors nor warnings. .

I understand that java compiler erases type info, so:

Shouldn't eclipse provide a compiler error instead of warning, or is it the maven-plugin-compiler that creates the problem?

The maven plugin is:

```<code>        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <showDeprecation>false</showDeprecation>
                <debug>true</debug>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
</code>```

Kind Regards,

Despot

答:
This is a known bug in Eclipse: 333011: [compiler][1.5] Eclipse compiles codes which javac rejects: incompatible types . Feel free to vote for the bug and add your use case to it.

There are situations when javac and Eclipse disagree, and you should report them as bugs. It is preferred to have a standalone test case of as few Java files as possible which can be copy/pasted in Eclipse and compiled using javac from the command line without any dependencies.

Body:
I have a code like this:

protected <T> T doSomething(String someParam, Class<T> clazz) {
...
}

which I use in a TestCase class:

Class clazz = MyClass.class;
MyClass MyClass = someObject.doSomething(someString, clazz);

This code gives a warning in eclipse:

Class is a raw type. References to generic type Class should be parameterized

and

Multiple markers at this line

      - Type safety: Unchecked invocation doSomething(String, Class) of the generic method doSomething(String, Class) of type MyClass

      - Type safety: The expression of type Class needs unchecked conversion to conform to Class

When I run this code (test) in eclipse - everything works perfectly. When I do it through "mvn clean install" through command prompt, I get:

C:\pathToProject\src\test\java\packagesPath\MyTestCase.java:[xx,xxx] incompatible types found   :

  java.lang.Object

  required: com.somePackagePath.MyClass

But when providing:

Class<MyClass> clazz = MyClass.class;
MyClass MyClass = someObject.doSomething(someString, clazz);

I don't get any errors nor warnings. .

I understand that java compiler erases type info, so:

Shouldn't eclipse provide a compiler error instead of warning, or is it the maven-plugin-compiler that creates the problem?

The maven plugin is:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <showDeprecation>false</showDeprecation>
                <debug>true</debug>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

Kind Regards,

Despot


问:
Title on other Activities
I need that the sentence in the mainActivity "datos tarjeta credito" appears also in the top of the second activity. The xml layouts are the same, I don't understand where can I change this. This is what is now:

I tried to attach the xml layouts, but its not working.

答:
If you are using Activity with Actionbar enabled theme, then you can use below code to change the title of actionbar in all activity programatically.

```<code>ActionBar actionBar = getSupportActionBar();
 if (actionBar != null) {
      actionBar.setTitle("Your Title here");
   }
</code>```

Or you can set the title in manifest itself by:

```<code> <activity
     android:name="your activity name"
     android:label="Your Title Here"/>
</code>```

Title: Title on other Activities

Body:
If you are using Activity with Actionbar enabled theme, then you can use below code to change the title of actionbar in all activity programatically.

ActionBar actionBar = getSupportActionBar();
 if (actionBar != null) {
      actionBar.setTitle("Your Title here");
   }

Or you can set the title in manifest itself by:

 <activity
     android:name="your activity name"
     android:label="Your Title Here"/>


问:
how foldr works on this data tree?
I know how foldr works on Leaf, but I don't know how foldr work on Node. What is the parameter \x z' if we already have f and z as parameter. assume we have

```<code>tree = Node [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]
</code>```

how this code works

```<code>foldr (+) 0 tree
</code>```

```<code>data RoseTree a =  Leaf a | Node [RoseTree a]
instance Foldable RoseTree where
    foldr f z (Leaf x) = f x z
    foldr f z (Node ns) =
        foldr (\x z' -> foldr f z' x) z ns
</code>```

答:
The definition of foldr for Node calls foldr on the list of RoseTrees. Then, inside of that foldr, it calls foldr on each subtree, using the current accumulator as the initial parameter.

Basically, even though it looks like the function calls foldr twice, it is calling it for different types each time, and so only one is recursive. The other is the foldr defined for [a].

Title: how foldr works on this data tree?

Body:
I know how foldr works on Leaf, but I don't know how foldr work on Node. What is the parameter \x z' if we already have f and z as parameter. assume we have

tree = Node [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]

how this code works

foldr (+) 0 tree

data RoseTree a =  Leaf a | Node [RoseTree a]
instance Foldable RoseTree where
    foldr f z (Leaf x) = f x z
    foldr f z (Node ns) =
        foldr (\x z' -> foldr f z' x) z ns