问:
how override spring framework beans?
I want to customize some of the codes of OAuth authorization server provided by spring security. the code responsible for generating /oauth/authorize is a bean named AuthorizationEndpoint. in AuthorizationServerEndpointsConfiguration class the following code creates a bean of AuthorizationEndpoint class:

```<code>@Bean
public AuthorizationEndpoint authorizationEndpoint() throws Exception {
    AuthorizationEndpoint authorizationEndpoint = new AuthorizationEndpoint();
    FrameworkEndpointHandlerMapping mapping = getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
    authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
    authorizationEndpoint.setProviderExceptionHandler(exceptionTranslator());
    authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
    authorizationEndpoint.setTokenGranter(tokenGranter());
    authorizationEndpoint.setClientDetailsService(clientDetailsService);
    authorizationEndpoint.setAuthorizationCodeServices(authorizationCodeServices());
    authorizationEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
    authorizationEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
    authorizationEndpoint.setUserApprovalHandler(userApprovalHandler());
    return authorizationEndpoint;
}
</code>```

I want to override it by a new custom bean. I have created a class which extends AuthorizationEndpoint. for now I have pasted the same code inside this new class.

```<code>public class AuthorizationEndpointCustom extends AuthorizationEndpoint {
</code>```

creating the bean:

```<code>    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    AuthorizationServerEndpointsConfiguration asec;

    @Bean
//  @Order(value = Ordered.LOWEST_PRECEDENCE)
    @Primary
    public AuthorizationEndpoint authorizationEndpoint () {

        AuthorizationEndpointCustom authorizationEndpoint = new AuthorizationEndpointCustom();
        FrameworkEndpointHandlerMapping mapping = asec.getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
        authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
        authorizationEndpoint.setProviderExceptionHandler(asec.getEndpointsConfigurer().getExceptionTranslator());
        authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
        authorizationEndpoint.setTokenGranter(asec.getEndpointsConfigurer().getTokenGranter());
        authorizationEndpoint.setClientDetailsService(clientDetailsService);
        authorizationEndpoint.setAuthorizationCodeServices(asec.getEndpointsConfigurer().getAuthorizationCodeServices());
        authorizationEndpoint.setOAuth2RequestFactory(asec.getEndpointsConfigurer().getOAuth2RequestFactory());
        authorizationEndpoint.setOAuth2RequestValidator(asec.getEndpointsConfigurer().getOAuth2RequestValidator());
        authorizationEndpoint.setUserApprovalHandler(asec.getEndpointsConfigurer().getUserApprovalHandler());

        return authorizationEndpoint;
    }

    private String extractPath(FrameworkEndpointHandlerMapping mapping, String page) {
        String path = mapping.getPath(page);
        if (path.contains(":")) {
            return path;
        }
        return "forward:" + path;
    }
</code>```

when I try to create a bean of this new class I encounter the following error:

APPLICATION FAILED TO START

Description:

The bean 'authorizationEndpoint', defined in
  org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration,
  could not be registered. A bean with that name has already been
  defined in class path resource
  [com/example/demo/AuthorizationServerConfig.class] and overriding is
  disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
  spring.main.allow-bean-definition-overriding=true

the error goes away by adding the suggested config to application.properties. but the new bean does not replace the framework bean. in another part of my code I accessed the AuthorizationEndpoint from applicationContext. I called the .getClass() of this object and it is the same bean from the framework:

"org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint"

how can I force spring to use my bean?

答:
I red an article about overriding beans and it seems so messy and unpredictable. read here
it's best to avoid doing so. The solution to disable framework bean lies in excluding the configuration class which creates it. but this means we have to implement the hole thing ourselves.

```<code>@SpringBootApplication(exclude=<AuthorizationServerEndpointsConfiguration>.class)
</code>```

but the solution to overriding the framework endpoints is much easier.all we have to do is create a controller with mapping for /oauth/authorize

Customizing the UI Most of the Authorization Server endpoints are used
  primarily by machines, but there are a couple of resource that need a
  UI and those are the GET for /oauth/confirm_access and the HTML
  response from /oauth/error. They are provided using whitelabel
  implementations in the framework, so most real-world instances of the
  Authorization Server will want to provide their own so they can
  control the styling and content. All you need to do is provide a
  Spring MVC controller with @RequestMappings for those endpoints, and
  the framework defaults will take a lower priority in the dispatcher.
  In the /oauth/confirm_access endpoint you can expect an
  AuthorizationRequest bound to the session carrying all the data needed
  to seek approval from the user (the default implementation is
  WhitelabelApprovalEndpoint so look there for a starting point to
  copy). You can grab all the data from that request and render it
  however you like, and then all the user needs to do is POST back to
  /oauth/authorize with information about approving or denying the
  grant. The request parameters are passed directly to a
  UserApprovalHandler in the AuthorizationEndpoint so you can interpret
  the data more or less as you please. The default UserApprovalHandler
  depends on whether or not you have supplied an ApprovalStore in your
  AuthorizationServerEndpointsConfigurer (in which case it is an
  ApprovalStoreUserApprovalHandler) or not (in which case it is a
  TokenStoreUserApprovalHandler). The standard approval handlers accept
  the following:

read more here.

there is another question related to this subject: read here

Title: how override spring framework beans?

Body:
I want to customize some of the codes of OAuth authorization server provided by spring security. the code responsible for generating /oauth/authorize is a bean named AuthorizationEndpoint. in AuthorizationServerEndpointsConfiguration class the following code creates a bean of AuthorizationEndpoint class:

@Bean
public AuthorizationEndpoint authorizationEndpoint() throws Exception {
    AuthorizationEndpoint authorizationEndpoint = new AuthorizationEndpoint();
    FrameworkEndpointHandlerMapping mapping = getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
    authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
    authorizationEndpoint.setProviderExceptionHandler(exceptionTranslator());
    authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
    authorizationEndpoint.setTokenGranter(tokenGranter());
    authorizationEndpoint.setClientDetailsService(clientDetailsService);
    authorizationEndpoint.setAuthorizationCodeServices(authorizationCodeServices());
    authorizationEndpoint.setOAuth2RequestFactory(oauth2RequestFactory());
    authorizationEndpoint.setOAuth2RequestValidator(oauth2RequestValidator());
    authorizationEndpoint.setUserApprovalHandler(userApprovalHandler());
    return authorizationEndpoint;
}

I want to override it by a new custom bean. I have created a class which extends AuthorizationEndpoint. for now I have pasted the same code inside this new class.

public class AuthorizationEndpointCustom extends AuthorizationEndpoint {

creating the bean:

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    AuthorizationServerEndpointsConfiguration asec;

    @Bean
//  @Order(value = Ordered.LOWEST_PRECEDENCE)
    @Primary
    public AuthorizationEndpoint authorizationEndpoint () {

        AuthorizationEndpointCustom authorizationEndpoint = new AuthorizationEndpointCustom();
        FrameworkEndpointHandlerMapping mapping = asec.getEndpointsConfigurer().getFrameworkEndpointHandlerMapping();
        authorizationEndpoint.setUserApprovalPage(extractPath(mapping, "/oauth/confirm_access"));
        authorizationEndpoint.setProviderExceptionHandler(asec.getEndpointsConfigurer().getExceptionTranslator());
        authorizationEndpoint.setErrorPage(extractPath(mapping, "/oauth/error"));
        authorizationEndpoint.setTokenGranter(asec.getEndpointsConfigurer().getTokenGranter());
        authorizationEndpoint.setClientDetailsService(clientDetailsService);
        authorizationEndpoint.setAuthorizationCodeServices(asec.getEndpointsConfigurer().getAuthorizationCodeServices());
        authorizationEndpoint.setOAuth2RequestFactory(asec.getEndpointsConfigurer().getOAuth2RequestFactory());
        authorizationEndpoint.setOAuth2RequestValidator(asec.getEndpointsConfigurer().getOAuth2RequestValidator());
        authorizationEndpoint.setUserApprovalHandler(asec.getEndpointsConfigurer().getUserApprovalHandler());

        return authorizationEndpoint;
    }

    private String extractPath(FrameworkEndpointHandlerMapping mapping, String page) {
        String path = mapping.getPath(page);
        if (path.contains(":")) {
            return path;
        }
        return "forward:" + path;
    }

when I try to create a bean of this new class I encounter the following error:

APPLICATION FAILED TO START

Description:

The bean 'authorizationEndpoint', defined in
  org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration,
  could not be registered. A bean with that name has already been
  defined in class path resource
  [com/example/demo/AuthorizationServerConfig.class] and overriding is
  disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting
  spring.main.allow-bean-definition-overriding=true

the error goes away by adding the suggested config to application.properties. but the new bean does not replace the framework bean. in another part of my code I accessed the AuthorizationEndpoint from applicationContext. I called the .getClass() of this object and it is the same bean from the framework:

"org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint"

how can I force spring to use my bean?

Body:
I red an article about overriding beans and it seems so messy and unpredictable. read here
it's best to avoid doing so. The solution to disable framework bean lies in excluding the configuration class which creates it. but this means we have to implement the hole thing ourselves.

@SpringBootApplication(exclude=<AuthorizationServerEndpointsConfiguration>.class)

but the solution to overriding the framework endpoints is much easier.all we have to do is create a controller with mapping for /oauth/authorize

Customizing the UI Most of the Authorization Server endpoints are used
  primarily by machines, but there are a couple of resource that need a
  UI and those are the GET for /oauth/confirm_access and the HTML
  response from /oauth/error. They are provided using whitelabel
  implementations in the framework, so most real-world instances of the
  Authorization Server will want to provide their own so they can
  control the styling and content. All you need to do is provide a
  Spring MVC controller with @RequestMappings for those endpoints, and
  the framework defaults will take a lower priority in the dispatcher.
  In the /oauth/confirm_access endpoint you can expect an
  AuthorizationRequest bound to the session carrying all the data needed
  to seek approval from the user (the default implementation is
  WhitelabelApprovalEndpoint so look there for a starting point to
  copy). You can grab all the data from that request and render it
  however you like, and then all the user needs to do is POST back to
  /oauth/authorize with information about approving or denying the
  grant. The request parameters are passed directly to a
  UserApprovalHandler in the AuthorizationEndpoint so you can interpret
  the data more or less as you please. The default UserApprovalHandler
  depends on whether or not you have supplied an ApprovalStore in your
  AuthorizationServerEndpointsConfigurer (in which case it is an
  ApprovalStoreUserApprovalHandler) or not (in which case it is a
  TokenStoreUserApprovalHandler). The standard approval handlers accept
  the following:

read more here.

there is another question related to this subject: read here


来源: stackexchange

问:
Firebase Notifications not being delivered if sent other than firebase console
I am facing a really strange issue, the notifications sent from the Firebase Console are being delivered properly so it means the project is configured and certificates are correct, but when I send notification from the app it doesn't work. I am using the following method to send notifications.

```<code>func sendPushNotification(to token: String, title: String, body: String, Type: String) {

        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] =
            [
                "message" :[
                    "to" : token,
                    "notification" : ["title" : title, "body" : body],
                    "data" : ["notification_type": Type]
                ],
                "to" : token
            ]

        print(paramString)
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAApQ9EAjg:XXXX", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()

    }
</code>```

I have also tried sending through curl with the following method

```<code><?php
/**
 * Created by PhpStorm.
 * User: ussaidiqbal
 * Date: 2020-02-17
 * Time: 19:45
 */

$url = "https://fcm.googleapis.com/fcm/send";
$token = "eMIK6wGOTUUutqp62vEIr-:XXXXXX";
$serverKey = 'AIzaSyCJFUydXXXXXXXXXX';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,

    "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
</code>```

I also have tried to send through PostMan using the following payload

```<code>{
    "notification":{
        "title": "XXXXX",
        "body": "XXXXX"
    },
  "to": "XXXXXXX"
}
</code>```

This is the response of the request

```<code>{
    "multicast_id": 36126XXXXXXXX,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1581960379105057~~~~~~~~~~"
        }
    ]
}
</code>```

None of the above method seems to be working, What am I doing wrong?
I have tried both the Legacy server key and Server key but no luck. Has anyone ever faced such an issue?

答:
So after spending a lot of time I figured it out and it's all working normally. So if anyone else facing this issue they can solve by opening your AppDelegate.swift file, find a function didRegisterForRemoteNotificationsWithDeviceToken and replace with the following

```<code> func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
        // With swizzling disabled you must set the APNs token here.
         Messaging.messaging().apnsToken = deviceToken
    }
</code>```

After doing this all seems to be working fine.

ContentLicense: CC BY-SA 4.0

Body:
I am facing a really strange issue, the notifications sent from the Firebase Console are being delivered properly so it means the project is configured and certificates are correct, but when I send notification from the app it doesn't work. I am using the following method to send notifications.

func sendPushNotification(to token: String, title: String, body: String, Type: String) {

        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] =
            [
                "message" :[
                    "to" : token,
                    "notification" : ["title" : title, "body" : body],
                    "data" : ["notification_type": Type]
                ],
                "to" : token
            ]

        print(paramString)
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAApQ9EAjg:XXXX", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()

    }

I have also tried sending through curl with the following method

<?php
/**
 * Created by PhpStorm.
 * User: ussaidiqbal
 * Date: 2020-02-17
 * Time: 19:45
 */

$url = "https://fcm.googleapis.com/fcm/send";
$token = "eMIK6wGOTUUutqp62vEIr-:XXXXXX";
$serverKey = 'AIzaSyCJFUydXXXXXXXXXX';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,

    "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

I also have tried to send through PostMan using the following payload

{
    "notification":{
        "title": "XXXXX",
        "body": "XXXXX"
    },
  "to": "XXXXXXX"
}

This is the response of the request

{
    "multicast_id": 36126XXXXXXXX,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1581960379105057~~~~~~~~~~"
        }
    ]
}

None of the above method seems to be working, What am I doing wrong?
I have tried both the Legacy server key and Server key but no luck. Has anyone ever faced such an issue?

Body:
So after spending a lot of time I figured it out and it's all working normally. So if anyone else facing this issue they can solve by opening your AppDelegate.swift file, find a function didRegisterForRemoteNotificationsWithDeviceToken and replace with the following

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs token retrieved: \(deviceToken)")
        // With swizzling disabled you must set the APNs token here.
         Messaging.messaging().apnsToken = deviceToken
    }

After doing this all seems to be working fine.


问:
How to conditionally add a child component to a parent component in React?
Consider an array like this:

```<code>const myArray = [1,2,3]
</code>```

Depending on the length of this array (which keeps changing only between 2 and 3), I want to add or remove a react-native-svg component which display this value.

This is how I have approached it so far (I know this code will not work):

```<code>const myComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);

    const mySVGComponents = useEffect(() => {
        //It is ensured that the array has at least two values
        let GroupWrapper = (() => {
            return (
                <G>
                    <SVGText>{myArray[0]}</SVGText>
                    <SVGText>{myArray[1]}</SVGText>
                </G>
            )
        })

        if (myArray.length === 3) {
            GroupWrapper = (() => {
                return (
                    <GroupWrapper>
                        <SVGText>{myArray[2]}</SVGText>
                    </GroupWrapper>
                )
            })
        }

        return GroupWrapper;

    }, [myArray]);

    return (
        <G>
            {mySVGComponents}
        </G>
    )
}
</code>```

How can I inject SVGText components into the <G> component conditionally based on the length of myArray?

答:
Rendering an array of items in React is not as complicated as you are trying to do it here. You can read mode about that here: https://reactjs.org/docs/lists-and-keys.html

Specifically for your case, you first have to remove the useEffect, you are not supposed to use it like that (https://reactjs.org/docs/hooks-effect.html). All you have to do is just map the array in the return statement, take a look at this:

```<code>export const MyComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);
    return <G>{myArray.map(item => <SVGText key={item}>{item}</SVGText>)}</G>;
}
</code>```

This way you are rendering each item in the array, and it will be automatically rerendered when you update you array using setMyArray.

Body:
Consider an array like this:

const myArray = [1,2,3]

Depending on the length of this array (which keeps changing only between 2 and 3), I want to add or remove a react-native-svg component which display this value.

This is how I have approached it so far (I know this code will not work):

const myComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);

    const mySVGComponents = useEffect(() => {
        //It is ensured that the array has at least two values
        let GroupWrapper = (() => {
            return (
                <G>
                    <SVGText>{myArray[0]}</SVGText>
                    <SVGText>{myArray[1]}</SVGText>
                </G>
            )
        })

        if (myArray.length === 3) {
            GroupWrapper = (() => {
                return (
                    <GroupWrapper>
                        <SVGText>{myArray[2]}</SVGText>
                    </GroupWrapper>
                )
            })
        }

        return GroupWrapper;

    }, [myArray]);

    return (
        <G>
            {mySVGComponents}
        </G>
    )
}

How can I inject SVGText components into the <G> component conditionally based on the length of myArray?

Body:
Rendering an array of items in React is not as complicated as you are trying to do it here. You can read mode about that here: https://reactjs.org/docs/lists-and-keys.html

Specifically for your case, you first have to remove the useEffect, you are not supposed to use it like that (https://reactjs.org/docs/hooks-effect.html). All you have to do is just map the array in the return statement, take a look at this:

export const MyComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);
    return <G>{myArray.map(item => <SVGText key={item}>{item}</SVGText>)}</G>;
}

This way you are rendering each item in the array, and it will be automatically rerendered when you update you array using setMyArray.


问:
How to set image in grid view?
I want to know how to put tick mark on image which we click in grid layout.I have image of tickmark pls tell me how to put tick mark over image?

here is my code

```<code>    public class HeadshotAllPhoto extends Activity implements OnItemClickListener
{
    ImageView bg,tickmark;
    int ht,wt;
    GridView imagegrid;
    static boolean flag = false;
    String path,filemanagerstring;
    String[] ImageNameArr;
    String filePath = null;
    String ImageName ;
    Bitmap bitmap;
    DataHelperHeadshot dbHeadshot;
    String uplaodedHeadshot;
    Cursor cursor;
    String sub_list ;
    String[] pathArr;
    Bitmap[] bmp;
    ArrayList<String> items = new ArrayList<String>();
    ImageView i;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.headshotallphoto);
        dbHeadshot = new DataHelperHeadshot(this);

        bg = (ImageView)findViewById(R.id.selectHeadshotView);

        List<String> names = this.dbHeadshot.fetchAllHeadshot();
        StringBuilder sb = new StringBuilder();
        for (String name : names)
        {
           name.trim();
           sb.append(",");
           sb.append(name);
        }
        bmp = new Bitmap[SelectionHeadshot.icount+1];
        for(int p=0;p<names.size();p++)
        {
            if(names.get(p) !=null)
            {
                bitmap = decodeFile(names.get(p));
                if(bitmap!=null)
                {
                    items.add(names.get(p));
                    bmp[p] = bitmap;
                }
            }
        }
        imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
        imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
        imagegrid.setOnItemClickListener(this);
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context mContext;
        Bitmap[] mImageArray;

        public ImageAdapter(Context c, Bitmap[] imgArray)
        {
              mContext = c;
              mImageArray = imgArray;
        }

        public int getCount()
        {
              return mImageArray.length;
        }

        public Object getItem(int position)
        {
              return position;
        }
        public long getItemId(int position)
        {
              return position;
        }

        public View getView(int position,View convertView,ViewGroup parent)
        {
            System.gc();
            if (convertView == null)
            {
                i = new ImageView(mContext);
                i.setLayoutParams(new GridView.LayoutParams(92,92));
                i.setScaleType(ImageView.ScaleType.CENTER_CROP);
                i.setImageBitmap(mImageArray[position]);
            }
            else
                 i = (ImageView) convertView;
            return i;
        }

    }

    public Bitmap decodeFile(String filePath)
    {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 100;
        final int H = 50;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < H)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }
        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);
        return bitmap;
    }

    public void onItemClick(AdapterView<?> a, View v, final int position, long id)
    {
        imagegrid.getChildAt(position).setBackgroundResource(R.drawable.imgredselectmark);
    }
}
</code>```

Thanks

答:
Try this code :

```<code>        private int Splash_Time_Limit = 3000;

        gridview.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
                long arg3) {
            // TODO Auto-generated method stub

            gridview.getChildAt(arg2).setBackgroundResource(R.drawable.wrong);

            //  new Handler().postDelayed(new Runnable() {
            //  @Override
            //  public void run() {
            //       gridview.getChildAt(arg2).setBackgroundResource(R.drawable.tick1);
            //  }
            //  }, Splash_Time_Limit);
        }
    });
</code>```

If you click the Image in Grid View the images tick image will be set as Background image.

If you want to disappear that Tick image after some times use Handler code that is commented.

ContentLicense: CC BY-SA 3.0

Title: How to set image in grid view?

Body:
I want to know how to put tick mark on image which we click in grid layout.I have image of tickmark pls tell me how to put tick mark over image?

here is my code

    public class HeadshotAllPhoto extends Activity implements OnItemClickListener
{
    ImageView bg,tickmark;
    int ht,wt;
    GridView imagegrid;
    static boolean flag = false;
    String path,filemanagerstring;
    String[] ImageNameArr;
    String filePath = null;
    String ImageName ;
    Bitmap bitmap;
    DataHelperHeadshot dbHeadshot;
    String uplaodedHeadshot;
    Cursor cursor;
    String sub_list ;
    String[] pathArr;
    Bitmap[] bmp;
    ArrayList<String> items = new ArrayList<String>();
    ImageView i;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.headshotallphoto);
        dbHeadshot = new DataHelperHeadshot(this);

        bg = (ImageView)findViewById(R.id.selectHeadshotView);

        List<String> names = this.dbHeadshot.fetchAllHeadshot();
        StringBuilder sb = new StringBuilder();
        for (String name : names)
        {
           name.trim();
           sb.append(",");
           sb.append(name);
        }
        bmp = new Bitmap[SelectionHeadshot.icount+1];
        for(int p=0;p<names.size();p++)
        {
            if(names.get(p) !=null)
            {
                bitmap = decodeFile(names.get(p));
                if(bitmap!=null)
                {
                    items.add(names.get(p));
                    bmp[p] = bitmap;
                }
            }
        }
        imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
        imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
        imagegrid.setOnItemClickListener(this);
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context mContext;
        Bitmap[] mImageArray;

        public ImageAdapter(Context c, Bitmap[] imgArray)
        {
              mContext = c;
              mImageArray = imgArray;
        }

        public int getCount()
        {
              return mImageArray.length;
        }

        public Object getItem(int position)
        {
              return position;
        }
        public long getItemId(int position)
        {
              return position;
        }

        public View getView(int position,View convertView,ViewGroup parent)
        {
            System.gc();
            if (convertView == null)
            {
                i = new ImageView(mContext);
                i.setLayoutParams(new GridView.LayoutParams(92,92));
                i.setScaleType(ImageView.ScaleType.CENTER_CROP);
                i.setImageBitmap(mImageArray[position]);
            }
            else
                 i = (ImageView) convertView;
            return i;
        }

    }

    public Bitmap decodeFile(String filePath)
    {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 100;
        final int H = 50;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < H)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }
        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);
        return bitmap;
    }

    public void onItemClick(AdapterView<?> a, View v, final int position, long id)
    {
        imagegrid.getChildAt(position).setBackgroundResource(R.drawable.imgredselectmark);
    }
}

Thanks

Body:
Try this code :

        private int Splash_Time_Limit = 3000;

        gridview.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
                long arg3) {
            // TODO Auto-generated method stub

            gridview.getChildAt(arg2).setBackgroundResource(R.drawable.wrong);

            //  new Handler().postDelayed(new Runnable() {
            //  @Override
            //  public void run() {
            //       gridview.getChildAt(arg2).setBackgroundResource(R.drawable.tick1);
            //  }
            //  }, Splash_Time_Limit);
        }
    });

If you click the Image in Grid View the images tick image will be set as Background image.

If you want to disappear that Tick image after some times use Handler code that is commented.


问:
Full-text Index stop list for Persian language
I need to customize Full-text search for Persian language. And customize Stop/Noise words and synonyms for this language.

My SQL Server version is 2016 and full-text search is installed.

答:
Finally I found the solution.

By default when you create a full text index it is associated with a system stoplist. The default stoplist has more than 150 words for the English language.

configure-and-manage-stopwords-and-stoplists-for-full-text-search

full-text-search-stoplist-and-stopword

Just open this file and then add your words

[SQL Server Path]\MSSQL13.MSSQLSERVER\MSSQL\FTData\tsglobal.xml

```<code><XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
<diacritics_sensitive>0</diacritics_sensitive>
    <expansion>
        <sub>Internet Explorer</sub>
        <sub>IE</sub>
        <sub>IE5</sub>
    </expansion>
    <expansion>
        <sub>سازگار سیستم خاورمیانه</sub>
        <sub>ستیران</sub>
    </expansion>
        <expansion>
        <sub>آبجی</sub>
        <sub>خواهر</sub>
    </expansion>
    <replacement>
        <pat>NT5</pat>
        <pat>W2K</pat>
        <sub>Windows 2000</sub>
    </replacement>
    <expansion>
        <sub>run</sub>
        <sub>jog</sub>
    </expansion>
</thesaurus>
</code>```

And then execute this SQL command.

```<code>EXEC sys.sp_fulltext_load_thesaurus_file 0;
</code>```

And for creating a custom stop list just flow these code:

```<code>CREATE FULLTEXT STOPLIST [PersianStopList]
</code>```

And then add your stop list

```<code>    ALTER FULLTEXT STOPLIST [PersianStopList] ADD 'از' LANGUAGE 'Neutral';
</code>```

Complete information in the Persian language:
https://www.dotnettips.info/courses/topics/13#/page/1/date/desc

Body:
Finally I found the solution.

By default when you create a full text index it is associated with a system stoplist. The default stoplist has more than 150 words for the English language.

configure-and-manage-stopwords-and-stoplists-for-full-text-search

full-text-search-stoplist-and-stopword

Just open this file and then add your words

[SQL Server Path]\MSSQL13.MSSQLSERVER\MSSQL\FTData\tsglobal.xml

<XML ID="Microsoft Search Thesaurus">
<thesaurus xmlns="x-schema:tsSchema.xml">
<diacritics_sensitive>0</diacritics_sensitive>
    <expansion>
        <sub>Internet Explorer</sub>
        <sub>IE</sub>
        <sub>IE5</sub>
    </expansion>
    <expansion>
        <sub>سازگار سیستم خاورمیانه</sub>
        <sub>ستیران</sub>
    </expansion>
        <expansion>
        <sub>آبجی</sub>
        <sub>خواهر</sub>
    </expansion>
    <replacement>
        <pat>NT5</pat>
        <pat>W2K</pat>
        <sub>Windows 2000</sub>
    </replacement>
    <expansion>
        <sub>run</sub>
        <sub>jog</sub>
    </expansion>
</thesaurus>

And then execute this SQL command.

EXEC sys.sp_fulltext_load_thesaurus_file 0;

And for creating a custom stop list just flow these code:

CREATE FULLTEXT STOPLIST [PersianStopList]

And then add your stop list

    ALTER FULLTEXT STOPLIST [PersianStopList] ADD 'از' LANGUAGE 'Neutral';

Complete information in the Persian language:
https://www.dotnettips.info/courses/topics/13#/page/1/date/desc


问:
I cant seem to add the category field automatically from an api
Well, here is a signup form, and in an input area i want the categories to be fetched automatically from the server api....... everything is ready but i can't seems to fetch it
api: https://stuaas.herokuapp.com/api/v1/organizations/categories

code:

```<code><form class="form-signin" method="GET" action="https://stuaas.herokuapp.com/api/v1/organizations/categories">
   <div class="form-label-group">
      <select name="" class="form-control">
        <option value="">Select your Account Type</option>
        <option>Student</option>
        <option>Organisation</option>
      </select>
  </div>

  <div class="form-label-group">
    <input type="name" id="inputName" class="form-control" placeholder="Organisational Name" required>
    <label for="inputName">Organisation Name</label>
  </div>

  <div class="form-label-group">
    <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    <label for="inputEmail">Email address</label>
  </div>

  <div class="form-label-group">
    <input type="tel" id="inputPhone" class="form-control" placeholder="Phone Number" required autofocus>
    <label for="inputPhone">Phone Number</label>
  </div>

  <div class="form-label-group">
    <input type="text" id="inputAddress" class="form-control" placeholder="Address" required autofocus>
    <label for="inputAddress">Address</label>
  </div>

  <div class="form-label-group">
    <input type="text" id="inputDescription" class="form-control" placeholder="Description" required autofocus>
    <label for="inputDescription">Description</label>
  </div>

  <div class="form-label-group">
    <select name="" class="form-control">
        <option value="">Categories</option>

  </div>

<div class="form-label-group">
  <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
  <label for="inputPassword">Password</label>
</div>

<div class="form-label-group">
  <input type="password" id="inputPassword" class="form-control" placeholder="Retype Password" required>
  <label for="inputPassword">Retype Password</label>
</div>

<button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign Up</button>
<hr class="my-4">
<button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"><i class="fab fa-google mr-2"></i> Sign Up with Google</button>
</form>
    <div class="form-label-group">
        <select name="" class="form-control">
            <option value="">Select your Account Type</option>
            <option>Student</option>
            <option>Organisation</option>
          </select>
    </div>

    <div class="form-label-group">
        <input type="name" id="inputName" class="form-control" placeholder="Organisational Name" required>
        <label for="inputName">Organisation Name</label>
      </div>

      <div class="form-label-group">
        <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputEmail">Email address</label>
      </div>

      <div class="form-label-group">
        <input type="tel" id="inputPhone" class="form-control" placeholder="Phone Number" required autofocus>
        <label for="inputPhone">Phone Number</label>
      </div>

      <div class="form-label-group">
        <input type="text" id="inputAddress" class="form-control" placeholder="Address" required autofocus>
        <label for="inputAddress">Address</label>
      </div>

      <div class="form-label-group">
        <input type="text" id="inputDescription" class="form-control" placeholder="Description" required autofocus>
        <label for="inputDescription">Description</label>
      </div>

      <div class="form-label-group">
        <select name="" class="form-control">
            <option value="">Categories</option>

      </div>

    <div class="form-label-group">
      <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
      <label for="inputPassword">Password</label>
    </div>

    <div class="form-label-group">
      <input type="password" id="inputPassword" class="form-control" placeholder="Retype Password" required>
      <label for="inputPassword">Retype Password</label>
    </div>

    <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign Up</button>
    <hr class="my-4">
    <button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"><i class="fab fa-google mr-2"></i> Sign Up with Google</button>
</form>

</code>```

答:
i don't know if you want to ask on how to fetch the data or how to use AJAX to fetch the data because you just provide the html only and not with the js.
If you ask on how to use AJAX to fetch the data from URL, here's some example :

function getCategories(){
  const xhr = new XMLHttpRequest();
  xhr.open('GET','https://stuaas.herokuapp.com/api/v1/organizations/categories',true);
  xhr.send();

  xhr.onload = function(){
    if(this.status === 200){
      const response = JSON.parse(this.responseText);

      let output = '';
      if (response.success) {
        response.payload.data.forEach(function(cat){
          output += `<option value = "${cat.id}">${cat.name}</option>`
        });
        document.querySelector('.categories-opt').innerHTML = output;
      } else {
        console.log('something went wrong!');
      }
    }
  }
}
(getCategories)();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form class="form-signin" method="GET" action="https://stuaas.herokuapp.com/api/v1/organizations/categories">
    <div class="form-label-group">
       <select name="" class="form-control">
         <option value="">Select your Account Type</option>
         <option>Student</option>
         <option>Organisation</option>
       </select>
   </div>

   <div class="form-label-group">
     <input type="name" id="inputName" class="form-control" placeholder="Organisational Name" required>
     <label for="inputName">Organisation Name</label>
   </div>

   <div class="form-label-group">
     <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
     <label for="inputEmail">Email address</label>
   </div>

   <div class="form-label-group">
     <input type="tel" id="inputPhone" class="form-control" placeholder="Phone Number" required autofocus>
     <label for="inputPhone">Phone Number</label>
   </div>

   <div class="form-label-group">
     <input type="text" id="inputAddress" class="form-control" placeholder="Address" required autofocus>
     <label for="inputAddress">Address</label>
   </div>

   <div class="form-label-group">
     <input type="text" id="inputDescription" class="form-control" placeholder="Description" required autofocus>
     <label for="inputDescription">Description</label>
   </div>

   <div class="form-label-group">
     <select name="categories" class="categories-opt form-control">
   </div>

 <div class="form-label-group">
   <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
   <label for="inputPassword">Password</label>
 </div>

 <div class="form-label-group">
   <input type="password" id="inputPassword" class="form-control" placeholder="Retype Password" required>
   <label for="inputPassword">Retype Password</label>
 </div>

 <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign Up</button>
 <hr class="my-4">
 <button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"><i class="fab fa-google mr-2"></i> Sign Up with Google</button>
 </form>
<script src="app.js"></script>
</body>
</html></code>```

Body:
Well, here is a signup form, and in an input area i want the categories to be fetched automatically from the server api....... everything is ready but i can't seems to fetch it
api: https://stuaas.herokuapp.com/api/v1/organizations/categories

code:

<form class="form-signin" method="GET" action="https://stuaas.herokuapp.com/api/v1/organizations/categories">

      <select name="" class="form-control">
        <option value="">Select your Account Type</option>
        <option>Student</option>
        <option>Organisation</option>
      </select>

    <input type="name" id="inputName" class="form-control" placeholder="Organisational Name" required>
    Organisation Name

    <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    Email address

    <input type="tel" id="inputPhone" class="form-control" placeholder="Phone Number" required autofocus>
    Phone Number

    <input type="text" id="inputAddress" class="form-control" placeholder="Address" required autofocus>
    Address

    <input type="text" id="inputDescription" class="form-control" placeholder="Description" required autofocus>
    Description

    <select name="" class="form-control">
        <option value="">Categories</option>

  <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
  Password

  <input type="password" id="inputPassword" class="form-control" placeholder="Retype Password" required>
  Retype Password

<button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign Up</button>

<button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"> Sign Up with Google</button>
</form>

        <select name="" class="form-control">
            <option value="">Select your Account Type</option>
            <option>Student</option>
            <option>Organisation</option>
          </select>

        <input type="name" id="inputName" class="form-control" placeholder="Organisational Name" required>
        Organisation Name

        <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        Email address

        <input type="tel" id="inputPhone" class="form-control" placeholder="Phone Number" required autofocus>
        Phone Number

        <input type="text" id="inputAddress" class="form-control" placeholder="Address" required autofocus>
        Address

        <input type="text" id="inputDescription" class="form-control" placeholder="Description" required autofocus>
        Description

        <select name="" class="form-control">
            <option value="">Categories</option>

      <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
      Password

      <input type="password" id="inputPassword" class="form-control" placeholder="Retype Password" required>
      Retype Password

    <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign Up</button>

    <button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"> Sign Up with Google</button>
</form>

Body:
i don't know if you want to ask on how to fetch the data or how to use AJAX to fetch the data because you just provide the html only and not with the js.
If you ask on how to use AJAX to fetch the data from URL, here's some example :

function getCategories(){
  const xhr = new XMLHttpRequest();
  xhr.open('GET','https://stuaas.herokuapp.com/api/v1/organizations/categories',true);
  xhr.send();

  xhr.onload = function(){
    if(this.status === 200){
      const response = JSON.parse(this.responseText);

      let output = '';
      if (response.success) {
        response.payload.data.forEach(function(cat){
          output += `<option value = "${cat.id}">${cat.name}</option>`
        });
        document.querySelector('.categories-opt').innerHTML = output;
      } else {
        console.log('something went wrong!');
      }
    }
  }
}
(getCategories)();

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <form class="form-signin" method="GET" action="https://stuaas.herokuapp.com/api/v1/organizations/categories">
    <div class="form-label-group">
       <select name="" class="form-control">
         <option value="">Select your Account Type</option>
         <option>Student</option>
         <option>Organisation</option>
       </select>
   </div>

   <div class="form-label-group">
     <input type="name" id="inputName" class="form-control" placeholder="Organisational Name" required>
     <label for="inputName">Organisation Name</label>
   </div>

   <div class="form-label-group">
     <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
     <label for="inputEmail">Email address</label>
   </div>

   <div class="form-label-group">
     <input type="tel" id="inputPhone" class="form-control" placeholder="Phone Number" required autofocus>
     <label for="inputPhone">Phone Number</label>
   </div>

   <div class="form-label-group">
     <input type="text" id="inputAddress" class="form-control" placeholder="Address" required autofocus>
     <label for="inputAddress">Address</label>
   </div>

   <div class="form-label-group">
     <input type="text" id="inputDescription" class="form-control" placeholder="Description" required autofocus>
     <label for="inputDescription">Description</label>
   </div>

   <div class="form-label-group">
     <select name="categories" class="categories-opt form-control">
   </div>

 <div class="form-label-group">
   <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
   <label for="inputPassword">Password</label>
 </div>

 <div class="form-label-group">
   <input type="password" id="inputPassword" class="form-control" placeholder="Retype Password" required>
   <label for="inputPassword">Retype Password</label>
 </div>

 <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign Up</button>
 <hr class="my-4">
 <button class="btn btn-lg btn-google btn-block text-uppercase" type="submit"><i class="fab fa-google mr-2"></i> Sign Up with Google</button>
 </form>
<script src="app.js"></script>
</body>
</html>


问:
How to permanently delete an abandoned pull request in Azure DevOps?
We have an abandoned pull request which we would like to permanently remove. How can this be done? There doesn't seem to be a 'delete' or 'remove' option. Thanks.</p>

答:
How to permanently delete an abandoned pull request in Azure DevOps?

Sorry for any inconvenience.

I'm afraid there is no such way to permanently delete an abandoned pull request in Azure DevOps at this moment.

Microsoft thinks that data retention and traceability is important to a lot of our customers - it's not as simple as always providing CRUD operations for every artifact. But more and more customers are requesting delete pull requests, or at least the ability to delete abandoned pull requests.

Just like Spevacus comment, this feature is under Review, and Microsoft replied:

Your suggestion has been queued up for prioritization. Feature
  suggestions are prioritized based on the value to our broader
  developer community and the product roadmap. We may not be able to
  pursue this one immediately, but we will continue to monitor it up to
  90 days for community input

You could vote and add your comments for this feedback. When there are enough community votes and comments with reliable feedback, the product team members will take this feature request seriously.

Hope this helps.


答:
You can simply modify the old table to add the column.. If you cant do that, then just use a join on the two tables like this</p>

```<code>UPDATE newTable N INNER JOIN
oldTable O
ON N.datenum = O.datenum
SET N.newcolumn = <whatever you want to set>
WHERE <any conditions on either tables>
</code>```

Title: Mysql update data

Body:
UPDATE

+-----+------------------+-------------+
| id  | datenum          | F1_baro_20_ |
+-----+------------------+-------------+
|   1 | 734152.000000000 |     1005.21 |
|   2 | 734152.006944445 |     1005.26 |
+-----+------------------+-------------+

this is my table

And this is my new table

+-----+------------------+-------------+------------+
| id  | datenum          | F1_baro_20_ |new column  |
+-----+------------------+-------------+------------+
|   1 | 734152.000000000 |     1005.21 |            |
|   2 | 734152.006944445 |     1005.26 |            |
+-----+------------------+-------------+------------+

I want to insert data to the 'new_colum' where old_datenum=new_datenum but I don't wan to modify the existing data!

Body:
You can simply modify the old table to add the column.. If you cant do that, then just use a join on the two tables like this

UPDATE newTable N INNER JOIN
oldTable O
ON N.datenum = O.datenum
SET N.newcolumn = <whatever you want to set>
WHERE <any conditions on either tables>


问:
Kibana not mobile friendly
I am looking for a frontend to query Elasticsearch, I know that Kibana is the best option for this (Besides grafana).

Unfortunately Kibana is totally not mobile friendly on android. Search is a real headache...

Tried searching on google but not able to find a worthy alternative.
Someone has experience on other tools/making kibana perform better on mobile devices.

If this turns out to be nothing I am seriously considering writing an angular app to perform base searches myself. Delivering in the dynamicniss of Kibana itself :(

答:
It is painful to use web version of kibana on ipad, although they claim it is mobile friendly.

I see a recent post on elastic forum, that a native iphone/ipad kibana go is now available, a very nice start.

https://discuss.elastic.co/t/ios-mobile-app/218463

You can download the app and check out the demo dashboard, to connect to your own ELK, you will need to install a kibana plugin then pointing to your own kibana.

Title: Kibana not mobile friendly


问:
Web App Script - How to pull value from question to be used in search to populate another question?
Here is my current script and attached sheet.

I have been able to successfully find the index value with function getColumnIndex(label) and then return that function into function getColumnValues(index) to pull all the rows in that specific column. I can't seem to use the input field from the autocomplete question id="courseCode" Enter Course Code as the search string to be used in the function getExpectations(); to populate the HTML page question id="expectations" as a multi selection question.

It works if I manually add the search string text to return the column rows. I would like to take the first 4 characters of the input field id="courseCode" Enter Course Code (3 letter followed by a number) as the search string to determine what selection options will populate the  id="expectations" question.

I am a bit confused with calling back functions within another function and when and how to use a parameter/condition to pass through the function.

I hope this is enough information to solve my script error. Thanks in advance for this concern. Take care.

Added the following lines of code to get all options selected in the multi-selection Course Expectations question.

```<code>function collectForm(){
    var submission = {};
    // gets you the values for all id="specific_names"

    submission.grade = document.getElementById("grade").value;
    submission.courseCode = document.getElementById("courseCode").value;

    var list = document.getElementsByClassName('selectedExpectations');
    var selection = ' ';
      for (i = 0; i < list.length; i++){
        if (list[i].checked === true) {
        selection += list[i].value + ", ";
        }
      }

    submission.expectations = selection;

    google.script.run.userClicked(submission);
 }
</code>```

答:
In short

You need something like this

```<code>/**
 *
 * @param {string} code
 */
function getExpectations2(code) {
  var patt = new RegExp(code.slice(0, 5), 'i');
  var data = SpreadsheetApp.openById(
    '1evNXXgFITrdNwsSdGXmprgzti74AQy03dg0igP5nT0I'
  )
    .getSheetByName('expectations')
    .getDataRange()
    .getValues();
  var colIndex = data[0].reduce(function(p, c, i) {
    return patt.test(c) ? i : p;
  }, -1);
  return colIndex === -1
    ? []
    : data
        .slice(1)
        .filter(function(row) {
          return row[colIndex] !== '';
        })
        .map(function(row) {
          return row[colIndex];
        });
}
</code>```

getExpectations2 - returns a column by code as a list.

Also you have to update your listExpectations

```<code>  function listExpectations(listLabels) {
    console.log(listLabels);
    const elm = document.getElementById('expectations');
    const label = listLabels
      .map(row => `<option value="${row}">${row}</option>`)
      .join('');

    elm.innerHTML =
      '<option disabled selected>Select expectations not met</option>' + label;
    setTimeout(() => M.FormSelect.init(elm), 0);
  }
</code>```

Of course you need bind all of them

```<code>  function populateCodes(codes) {
    var autocomplete = document.getElementById('courseCode');
    var instances = M.Autocomplete.init(autocomplete, {
      data: codes,
      onAutocomplete: onAutocompleteCourseCode,
    });
  }
</code>```

Where onAutocompleteCourseCode is

```<code>  const onAutocompleteCourseCode = courseCode => {
    google.script.run
      .withSuccessHandler(listExpectations)
      .getExpectations2(courseCode);
  };
</code>```

Body:
Here is my current script and attached sheet.

I have been able to successfully find the index value with function getColumnIndex(label) and then return that function into function getColumnValues(index) to pull all the rows in that specific column. I can't seem to use the input field from the autocomplete question id="courseCode" Enter Course Code as the search string to be used in the function getExpectations(); to populate the HTML page question id="expectations" as a multi selection question.

It works if I manually add the search string text to return the column rows. I would like to take the first 4 characters of the input field id="courseCode" Enter Course Code (3 letter followed by a number) as the search string to determine what selection options will populate the  id="expectations" question.

I am a bit confused with calling back functions within another function and when and how to use a parameter/condition to pass through the function.

I hope this is enough information to solve my script error. Thanks in advance for this concern. Take care.

Added the following lines of code to get all options selected in the multi-selection Course Expectations question.

function collectForm(){
    var submission = {};
    // gets you the values for all id="specific_names"

    submission.grade = document.getElementById("grade").value;
    submission.courseCode = document.getElementById("courseCode").value;

    var list = document.getElementsByClassName('selectedExpectations');
    var selection = ' ';
      for (i = 0; i < list.length; i++){
        if (list[i].checked === true) {
        selection += list[i].value + ", ";
        }
      }

    submission.expectations = selection;

    google.script.run.userClicked(submission);
 }

Body:
In short

You need something like this

/**
 *
 * @param {string} code
 */
function getExpectations2(code) {
  var patt = new RegExp(code.slice(0, 5), 'i');
  var data = SpreadsheetApp.openById(
    '1evNXXgFITrdNwsSdGXmprgzti74AQy03dg0igP5nT0I'
  )
    .getSheetByName('expectations')
    .getDataRange()
    .getValues();
  var colIndex = data[0].reduce(function(p, c, i) {
    return patt.test(c) ? i : p;
  }, -1);
  return colIndex === -1
    ? []
    : data
        .slice(1)
        .filter(function(row) {
          return row[colIndex] !== '';
        })
        .map(function(row) {
          return row[colIndex];
        });
}

getExpectations2 - returns a column by code as a list.

Also you have to update your listExpectations

  function listExpectations(listLabels) {
    console.log(listLabels);
    const elm = document.getElementById('expectations');
    const label = listLabels
      .map(row => `<option value="${row}">${row}</option>`)
      .join('');

    elm.innerHTML =
      '<option disabled selected>Select expectations not met</option>' + label;
    setTimeout(() => M.FormSelect.init(elm), 0);
  }

Of course you need bind all of them

  function populateCodes(codes) {
    var autocomplete = document.getElementById('courseCode');
    var instances = M.Autocomplete.init(autocomplete, {
      data: codes,
      onAutocomplete: onAutocompleteCourseCode,
    });
  }

Where onAutocompleteCourseCode is

  const onAutocompleteCourseCode = courseCode => {
    google.script.run
      .withSuccessHandler(listExpectations)
      .getExpectations2(courseCode);
  };


问:
How to adjust UIToolBar left and right padding
I create one UIToolbar with code and another with interface builder. But, found out the two toolbar having different left and right padding which shown below:

From Interface Builder:

From Code:

```<code>UIImage *buttonImage = [[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTest setBackgroundImage:buttonImage forState:UIControlStateNormal];
[btnTest setTitle:@"Back" forState:UIControlStateNormal];
[btnTest.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
[btnTest setBackgroundImage:[imgToolbarButton stretchableImageWithLeftCapWidth:5 topCapHeight:0]  forState:UIControlStateNormal];
[btnTest addTarget:self action:@selector(clearDateEdit:) forControlEvents:UIControlEventTouchUpInside];
btnTest.frame = CGRectMake(0.0, 0.0, 50, 30);
UIBarButtonItem *btnTestItem = [[UIBarButtonItem alloc] initWithCustomView:btnTest];
[self.toolbar setItems:[NSArray arrayWithObjects:btnTestItem,nil]];
[btnTestItem release];
</code>```

My question is how can I adjust the left and right padding of UIToolbar by code?

Update

I discovered this alignment issue only happen to UIBarButtonItem with customView of UIButton, the alignment is fine with UIBarButtonItem. Any idea what cause this or to resolve this.

The only solution I can think of right now is to manually set the frame.

答:
use this button</p>

```<code>UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                           target:nil
                                                                           action:nil];
</code>```

Body:
I create one UIToolbar with code and another with interface builder. But, found out the two toolbar having different left and right padding which shown below:

From Interface Builder:

From Code:

UIImage *buttonImage = [[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTest setBackgroundImage:buttonImage forState:UIControlStateNormal];
[btnTest setTitle:@"Back" forState:UIControlStateNormal];
[btnTest.titleLabel setFont:[UIFont boldSystemFontOfSize:13]];
[btnTest setBackgroundImage:[imgToolbarButton stretchableImageWithLeftCapWidth:5 topCapHeight:0]  forState:UIControlStateNormal];
[btnTest addTarget:self action:@selector(clearDateEdit:) forControlEvents:UIControlEventTouchUpInside];
btnTest.frame = CGRectMake(0.0, 0.0, 50, 30);
UIBarButtonItem *btnTestItem = [[UIBarButtonItem alloc] initWithCustomView:btnTest];
[self.toolbar setItems:[NSArray arrayWithObjects:btnTestItem,nil]];
[btnTestItem release];

My question is how can I adjust the left and right padding of UIToolbar by code?

Update

I discovered this alignment issue only happen to UIBarButtonItem with customView of UIButton, the alignment is fine with UIBarButtonItem. Any idea what cause this or to resolve this.

The only solution I can think of right now is to manually set the frame.

Body:
use this button

UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                           target:nil
                                                                           action:nil];


问:
How to delete CartEntries from hybris?
I need to create a CronJob that deletes Cart Entries of a specific type. I have allready found all entries with the needed PK, but I still cant delete them.

I found on the web that I cant use the FlexibleSearchQuery for that. Also I did not found any method for that in the CartEntryService. Where is the delete logic?

答:
You have to use modelService to remove any model from the database. In your case, all you need to do is pass list of cartEntryModel to getModelService().removeAll(list)

Look at the DefaultCartService updateQuantities method, basically this method is invoked with 0 quantity for the cart entry which the user tries to remove from the cart.

```<code>    final Collection<CartEntryModel> toRemove = new LinkedList<CartEntryModel>();
    final Collection<CartEntryModel> toSave = new LinkedList<CartEntryModel>();
    for (final Map.Entry<CartEntryModel, Long> e : getEntryQuantityMap(cart, quantities).entrySet())
    {
        final CartEntryModel cartEntry = e.getKey();
        final Long quantity = e.getValue();
        if (quantity == null || quantity.longValue() < 1)
        {
            toRemove.add(cartEntry);
        }
        else
        {
            cartEntry.setQuantity(quantity);
            toSave.add(cartEntry);
        }
    }
    getModelService().removeAll(toRemove);
</code>```

You can achieve the same form using a groovy script. Refer create a Cronjob using Groovy script in SAP Hybris

Groovy Script example:

```<code>import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.core.model.user.CartEntryModel;
import de.hybris.platform.servicelayer.search.SearchResult;
import org.apache.commons.collections.CollectionUtils;

def removeCartEntries()

 {
  final SearchResult<CartEntryModel> searchResults = flexibleSearchService.search("query to get the list of cartentries")
  if (searchResults != null && CollectionUtils.isNotEmpty(searchResults.getResult())) {
      modelService.removeAll(searchResults.getResult());
   }
 }
removeCartEntries();

println "done";
</code>```

Title: How to delete CartEntries from hybris?

Body:
You have to use modelService to remove any model from the database. In your case, all you need to do is pass list of cartEntryModel to getModelService().removeAll(list)

Look at the DefaultCartService updateQuantities method, basically this method is invoked with 0 quantity for the cart entry which the user tries to remove from the cart.

    final Collection<CartEntryModel> toRemove = new LinkedList<CartEntryModel>();
    final Collection<CartEntryModel> toSave = new LinkedList<CartEntryModel>();
    for (final Map.Entry<CartEntryModel, Long> e : getEntryQuantityMap(cart, quantities).entrySet())
    {
        final CartEntryModel cartEntry = e.getKey();
        final Long quantity = e.getValue();
        if (quantity == null || quantity.longValue() < 1)
        {
            toRemove.add(cartEntry);
        }
        else
        {
            cartEntry.setQuantity(quantity);
            toSave.add(cartEntry);
        }
    }
    getModelService().removeAll(toRemove);

You can achieve the same form using a groovy script. Refer create a Cronjob using Groovy script in SAP Hybris

Groovy Script example:

import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.core.model.user.CartEntryModel;
import de.hybris.platform.servicelayer.search.SearchResult;
import org.apache.commons.collections.CollectionUtils;

def removeCartEntries()

 {
  final SearchResult<CartEntryModel> searchResults = flexibleSearchService.search("query to get the list of cartentries")
  if (searchResults != null && CollectionUtils.isNotEmpty(searchResults.getResult())) {
      modelService.removeAll(searchResults.getResult());
   }
 }
removeCartEntries();

println "done";


问:
Laravel Swagger - Uncaught SyntaxError: Unexpected end of input
I am getting this error "Uncaught SyntaxError: Unexpected end of input" in console when trying to generate the Swagger documentation. Page is black and "Uncaught SyntaxError: Unexpected end of input" in console.

I am using

Laravel 5.7
darkaonline/l5-swagger": "5.7.*
zircote/swagger-php": "2.*

答:
A bit strange

just removing extra spaced from the code fixed the issue.

resources/views/vendor/l5-swagger/index.blade.php

```<code><script>
window.onload = function() {
  const ui = SwaggerUIBundle({
    dom_id: '#swagger-ui',

    url: "{!! $urlToDocs !!}",
    operationsSorter: {!! isset($operationsSorter) ? '"' . $operationsSorter . '"' : 'null' !!},
    configUrl: {!! isset($configUrl) ? '"' . $configUrl . '"' : 'null' !!},
    validatorUrl: {!! isset($validatorUrl) ? '"' . $validatorUrl . '"' : 'null' !!},
    oauth2RedirectUrl: "{{ route('l5-swagger.oauth2_callback') }}",
    requestInterceptor: function() {
      this.headers['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
      return this;
    },
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  });
  window.ui = ui;
}
</script>
</code>```

Body:
A bit strange

just removing extra spaced from the code fixed the issue.

resources/views/vendor/l5-swagger/index.blade.php

<script>
window.onload = function() {
  const ui = SwaggerUIBundle({
    dom_id: '#swagger-ui',

    url: "{!! $urlToDocs !!}",
    operationsSorter: {!! isset($operationsSorter) ? '"' . $operationsSorter . '"' : 'null' !!},
    configUrl: {!! isset($configUrl) ? '"' . $configUrl . '"' : 'null' !!},
    validatorUrl: {!! isset($validatorUrl) ? '"' . $validatorUrl . '"' : 'null' !!},
    oauth2RedirectUrl: "{{ route('l5-swagger.oauth2_callback') }}",
    requestInterceptor: function() {
      this.headers['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
      return this;
    },
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  });
  window.ui = ui;
}
</script>


问:
IsDigit() in c reading char as digit in C
I am trying to check if a char is upper case, lower case or a digit without using the library functions. I wrote my own functions but when I enter a character, my IsDigit() returns true and says that it is a digit rather than saying it is not. </p>

<p>I can't seem to find out where the bug is in my code. </p>

```<code>#include<stdio.h>
#include <stdbool.h>

int isLower(char ch)
{
   if (ch >= 'a' && ch <= 'z')
   {
       return true;
   }
   else
   {
       return false;
   }
}
int isUpper(char ch)
{
    if(ch>='A' && ch<='Z')
    {
       return true;
    }
    else
    {
        return false;
    }
}
int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)
    {
        return true;
    }
    else{
        return false;
    }
}

int main() {
   char ch='L';

   if(isLower(ch))
   {
       printf("%c is lower case.\n", ch);
   }
   else
   {
        printf("%c is not lower case.\n",ch);
   }

   if(isUpper(ch))
   {
       printf("%c is upper case.\n",ch);
   }
   else{
        printf("%c is not upper case.\n", ch);
   }

   if(isDigit(ch))
   {
       printf("%c is a digit.\n",ch);
   }
   else{
       printf("%c is not a digit.\n",ch);
   }

   return (0);
  }
Output:
d is lower case.
d is not upper case.
d is a digit.
</code>```

答:
Return the result of the test directly and use the same style as you did with the letters.

int isDigit(char ch)
{
    return (ch >= '0') && (ch <= '9');
}
```

Body:
I am trying to check if a char is upper case, lower case or a digit without using the library functions. I wrote my own functions but when I enter a character, my IsDigit() returns true and says that it is a digit rather than saying it is not.

I can't seem to find out where the bug is in my code.

#include<stdio.h>
#include <stdbool.h>

int isLower(char ch)
{
   if (ch >= 'a' && ch <= 'z')
   {
       return true;
   }
   else
   {
       return false;
   }
}
int isUpper(char ch)
{
    if(ch>='A' && ch<='Z')
    {
       return true;
    }
    else
    {
        return false;
    }
}
int isDigit(char ch)
{
    if(ch>=0 && ch <=47876)
    {
        return true;
    }
    else{
        return false;
    }
}

int main() {
   char ch='L';

   if(isLower(ch))
   {
       printf("%c is lower case.\n", ch);
   }
   else
   {
        printf("%c is not lower case.\n",ch);
   }

   if(isUpper(ch))
   {
       printf("%c is upper case.\n",ch);
   }
   else{
        printf("%c is not upper case.\n", ch);
   }

   if(isDigit(ch))
   {
       printf("%c is a digit.\n",ch);
   }
   else{
       printf("%c is not a digit.\n",ch);
   }

   return (0);
  }
Output:
d is lower case.
d is not upper case.
d is a digit.


问:
Issue in SQL query full scanning twice?
Table A

```<code>ID    EmpNo   Grade
--------------------
1      100    HIGH
2      105    LOW
3      100    MEDIUM
4      100    LOW
5      105    LOW
</code>```

Query:

```<code>select *
from A
where EMPNO = 100
  and rownum <= 2
order by ID desc
</code>```

I tried this query to retrieve max and max-1 value; I need to compare the grade from max and max-1, if equals I need to set the flag as 'Y' or 'N' without using a cursor. Also I don't want to scan the entire record twice.

Please help me.

答:
```<code>select *
from (
select id, emp_no, grade
       , case
          when lag(grade) over (order by emp_no desc) = grade
          then 'Y'
          else 'N'
          end
          as flag
      , dense_rank() over( order by emp_no desc)  as rank
from t
)
where rank <=2
;
</code>```

Title: Issue in SQL query full scanning twice?

Body:
Table A

ID    EmpNo   Grade
--------------------
1      100    HIGH
2      105    LOW
3      100    MEDIUM
4      100    LOW
5      105    LOW

Query:

select *
from A
where EMPNO = 100
  and rownum <= 2
order by ID desc

I tried this query to retrieve max and max-1 value; I need to compare the grade from max and max-1, if equals I need to set the flag as 'Y' or 'N' without using a cursor. Also I don't want to scan the entire record twice.

Please help me.


问:
gradle fails when ionic cordova build android on Mac 10.x
When trying to build an Ionic project ionic cordova build android on Mac  v10.x I get this error:

```<code>Subproject Path: CordovaLib

Configuration 'compile' in project ':' is deprecated. Use 'implementation' instead.
null

The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.

at build_1v81ywijexel39ggzi5morld0.run(<Userspath>/platforms/android/build.gradle:143)
org.xwalk:xwalk_core_library:23+
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.

>

All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com/r/tools/flavorDimensions-missing-error-message.html
</code>```

The error suggests it is a Gradle issue.  Anyone run into this and been able to solve the issue?  What should I do?

```<code>------------------------------------------------------------
Gradle 4.4.1
------------------------------------------------------------

Build time:   2017-12-20 15:45:23 UTC
Revision:     10ed9dc355dc39f6307cc98fbd8cea314bdd381c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_161 (Oracle Corporation 25.161-b12)
OS:           Mac OS X 10.13.2 x86_64
</code>```

Using Ionic v3.19.x and Cordova v7.1.0, and updating Cordova v8.0 definitely doesn't resolve the issue, also using cordova-android v6.2.3

答:
I was getting a very similar error and eventually resolved it running this:
brew install gradle
I also had to download version 8 of the java runtime for developers.

Body:
When trying to build an Ionic project ionic cordova build android on Mac  v10.x I get this error:

Subproject Path: CordovaLib

Configuration 'compile' in project ':' is deprecated. Use 'implementation' instead.
null

The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.

at build_1v81ywijexel39ggzi5morld0.run(<Userspath>/platforms/android/build.gradle:143)
org.xwalk:xwalk_core_library:23+
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.

>

All flavors must now belong to a named flavor dimension. Learn more at https://d.android.com/r/tools/flavorDimensions-missing-error-message.html

The error suggests it is a Gradle issue.  Anyone run into this and been able to solve the issue?  What should I do?

------------------------------------------------------------
Gradle 4.4.1
------------------------------------------------------------

Build time:   2017-12-20 15:45:23 UTC
Revision:     10ed9dc355dc39f6307cc98fbd8cea314bdd381c

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_161 (Oracle Corporation 25.161-b12)
OS:           Mac OS X 10.13.2 x86_64

Using Ionic v3.19.x and Cordova v7.1.0, and updating Cordova v8.0 definitely doesn't resolve the issue, also using cordova-android v6.2.3


问:
How to use pandas UDF in pyspark and return result in StructType
How can I drive a column based on panda-udf in pyspark. I've written udf as below:

```<code>from pyspark.sql.functions import pandas_udf, PandasUDFType

@pandas_udf("in_type string, in_var string, in_numer int", PandasUDFType.GROUPED_MAP)

def getSplitOP(in_data):
    if in_data is None or len(in_data) < 1:
        return None
    #Input/variable.12-2017
    splt=in_data.split("/",1)
    in_type=splt[0]

    splt_1=splt[1].split(".",1)
    in_var = splt_1[0]

    splt_2=splt_1[1].split("-",1)
    in_numer=int(splt_2[0])

    return (in_type, in_var, in_numer)
    #Expected output: ("input", "variable", 12)

df = df.withColumn("splt_col", getSplitOP(df.In_data))
</code>```

Can someone help me out to identify, what's wrong with above code, and why it's not working.

答:
This will work:

```<code>df = spark.createDataFrame([("input/variable.12-2017",), ("output/invariable.11-2018",)], ("in_data",))
df.show()

from pyspark.sql.functions import pandas_udf, PandasUDFType

@pandas_udf("in_type string, in_var string, in_numer int", PandasUDFType.GROUPED_MAP)
def getSplitOP(pdf):
    in_data = pdf.in_data

    #Input/variable.12-2017
    splt = in_data.apply(lambda x: x.split("/",1))
    in_type = splt.apply(lambda x: x[0])

    splt_1 = splt.apply(lambda x: x[1].split(".",1))
    in_var = splt_1.apply(lambda x: x[0])

    splt_2 = splt_1.apply(lambda x: x[1].split("-",1))
    in_numer = splt_2.apply(lambda x: int(x[0]))

    return pd.DataFrame({"in_type": in_type, "in_var": in_var, "in_numer": in_numer})
    #Expected output: ("input", "variable", 12)

df = df.groupBy().apply(getSplitOP)
df.show()
</code>```

There must not be a blank line after @pandas_udf.

pandas Series objects don't directly support string functions such as split.  Use apply to operate elementwise on each Series.

You used a GROUPED_MAP in order to return multiple columns, but your code isn't inherently grouped by anything.  Note that groupBy is used without any arguments here.  This requires all the data to fit on a single processor.

Body:
How can I drive a column based on panda-udf in pyspark. I've written udf as below:

from pyspark.sql.functions import pandas_udf, PandasUDFType

@pandas_udf("in_type string, in_var string, in_numer int", PandasUDFType.GROUPED_MAP)

def getSplitOP(in_data):
    if in_data is None or len(in_data) < 1:
        return None
    #Input/variable.12-2017
    splt=in_data.split("/",1)
    in_type=splt[0]

    splt_1=splt[1].split(".",1)
    in_var = splt_1[0]

    splt_2=splt_1[1].split("-",1)
    in_numer=int(splt_2[0])

    return (in_type, in_var, in_numer)
    #Expected output: ("input", "variable", 12)

df = df.withColumn("splt_col", getSplitOP(df.In_data))

Can someone help me out to identify, what's wrong with above code, and why it's not working.

Body:
This will work:

df = spark.createDataFrame([("input/variable.12-2017",), ("output/invariable.11-2018",)], ("in_data",))
df.show()

from pyspark.sql.functions import pandas_udf, PandasUDFType

@pandas_udf("in_type string, in_var string, in_numer int", PandasUDFType.GROUPED_MAP)
def getSplitOP(pdf):
    in_data = pdf.in_data

    #Input/variable.12-2017
    splt = in_data.apply(lambda x: x.split("/",1))
    in_type = splt.apply(lambda x: x[0])

    splt_1 = splt.apply(lambda x: x[1].split(".",1))
    in_var = splt_1.apply(lambda x: x[0])

    splt_2 = splt_1.apply(lambda x: x[1].split("-",1))
    in_numer = splt_2.apply(lambda x: int(x[0]))

    return pd.DataFrame({"in_type": in_type, "in_var": in_var, "in_numer": in_numer})
    #Expected output: ("input", "variable", 12)

df = df.groupBy().apply(getSplitOP)
df.show()

There must not be a blank line after @pandas_udf.

pandas Series objects don't directly support string functions such as split.  Use apply to operate elementwise on each Series.

You used a GROUPED_MAP in order to return multiple columns, but your code isn't inherently grouped by anything.  Note that groupBy is used without any arguments here.  This requires all the data to fit on a single processor.


问:
MYSQL remove duplicates from table with two columns
Have table contents_tags

```<code>+------------+--------+
| content_id | tag_id |
+------------+--------+
|          1 |      1 |
|          1 |      2 |
|          1 |      2 |
|          2 |      3 |
|          2 |      4 |
|          2 |      4 |
</code>```

I want create unique index with two columns

```<code>alter table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);
</code>```

But I already have duplicate entries and get error:

ERROR 1062 (23000): Duplicate entry '1-2' for key 'contents_tags'

```<code>alter IGNORE table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);
</code>```

IGNORE - don't work in Mysql 8

How can I remove duplicates?

答:
If you're going to make a UNIQUE key on two columns that is the entire table it might as well be the primary key:

```<code>CREATE TABLE contents_tags2 (
  `content_id` INTEGER,
  `tag_id` INTEGER,
  PRIMARY KEY (`content_id`,  `tag_id`)
  );

INSERT INTO  contents_tags2 SELECT DISTINCT content_id, tag_id FROM contents_tags;

RENAME TABLE contents_tags TO contents_tags_del, contents_tags2 TO contents_tags;

DROP TABLE contents_tags_del;
</code>```

fiddle

Body:
Have table contents_tags

+------------+--------+
| content_id | tag_id |
+------------+--------+
|          1 |      1 |
|          1 |      2 |
|          1 |      2 |
|          2 |      3 |
|          2 |      4 |
|          2 |      4 |

I want create unique index with two columns

alter table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);

But I already have duplicate entries and get error:

ERROR 1062 (23000): Duplicate entry '1-2' for key 'contents_tags'

alter IGNORE table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);

IGNORE - don't work in Mysql 8

How can I remove duplicates?

Body:
If you're going to make a UNIQUE key on two columns that is the entire table it might as well be the primary key:

CREATE TABLE contents_tags2 (
  `content_id` INTEGER,
  `tag_id` INTEGER,
  PRIMARY KEY (`content_id`,  `tag_id`)
  );

INSERT INTO  contents_tags2 SELECT DISTINCT content_id, tag_id FROM contents_tags;

RENAME TABLE contents_tags TO contents_tags_del, contents_tags2 TO contents_tags;

DROP TABLE contents_tags_del;

fiddle


问:
I am trying to download data from REST API to azure data lake via azure data factory. How can I pass query parameters for API in azure data factory?
I am doing this using ‘Copy Activity’. Is there any other activity that can better perform this operation?
Example REST API URL:https://xzy.com/servicename?name=tom&age=50&city=boston&......
I am putting 'https://xzy.com/servicename/' as the base URL for the linked service.
How to pass the query parameters 'name=tom' and 'age=50' and 'city=boston' to the base url in the azure data factory to get the response?
Will the parameters be passed at linked service, dataset or pipeline level?</p>

答:
It seems that your request method is Get. You could only set the query parameters behind base url directly.

For example,i test rest api from this sample website:

```<code>https://jsonplaceholder.typicode.com/comments?postId=1
</code>```

Test result:

If your request method is Post,i suppose you have to define the parameters in the Body part.

Body:
It seems that your request method is Get. You could only set the query parameters behind base url directly.

For example,i test rest api from this sample website:

https://jsonplaceholder.typicode.com/comments?postId=1

Test result:

If your request method is Post,i suppose you have to define the parameters in the Body part.


问:
Can Git hook scripts be managed along with the repository?
We'd like to make a few basic hook scripts that we can all share -- for things like pre-formatting commit messages.  Git has hook scripts for that that are normally stored under <project>/.git/hooks/.  However, those scripts are not propagated when people do a clone and they are not version controlled.

Is there a good way to help everyone get the right hook scripts?  Can I just make those hook scripts point to version controlled scripts in my repo?

答:
For Gradle users

I found these scripts very useful for Gradle projects.

build.gradle

apply from: rootProject.file('gradle/install-git-hooks.gradle')

gradle/install-git-hooks.gradle

```<code>tasks.create(name: 'gitExecutableHooks') {
    doLast {
        Runtime.getRuntime().exec("chmod -R +x .git/hooks/");
    }
}
task installGitHooks(type: Copy) {
    from new File(rootProject.rootDir, 'pre-commit')
    into { new File(rootProject.rootDir, '.git/hooks') }
}
gitExecutableHooks.dependsOn installGitHooks
clean.dependsOn gitExecutableHooks
</code>```

pre-commit

```<code>.... your pre commit scripts goes here
</code>```

OwnerDisplayName: Pat Notz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Pat Notz

Body:
For Gradle users

I found these scripts very useful for Gradle projects.

build.gradle

apply from: rootProject.file('gradle/install-git-hooks.gradle')

gradle/install-git-hooks.gradle

tasks.create(name: 'gitExecutableHooks') {
    doLast {
        Runtime.getRuntime().exec("chmod -R +x .git/hooks/");
    }
}
task installGitHooks(type: Copy) {
    from new File(rootProject.rootDir, 'pre-commit')
    into { new File(rootProject.rootDir, '.git/hooks') }
}
gitExecutableHooks.dependsOn installGitHooks
clean.dependsOn gitExecutableHooks

pre-commit

.... your pre commit scripts goes here


答:
The problem is in your implementation of isDigit() function. There are only 10 digits 0-9 (0 and 9 inclusive). See the ascii table http://www.asciitable.com/ to understand why your code was behaving incorrectly. So I think the implementation should be like (I am correcting you example):

int isDigit(char ch)
{
    if(ch >= '0' && ch <= '9')
    {
        return true;
    }

    return false;
}
```

Now, since you were trying to compare specifically with 47876 then I would like to know your thoughts on that. Thanks. Happy programming.

Title: IsDigit() in c reading char as digit in C

Body:
The problem is in your implementation of isDigit() function. There are only 10 digits 0-9 (0 and 9 inclusive). See the ascii table http://www.asciitable.com/ to understand why your code was behaving incorrectly. So I think the implementation should be like (I am correcting you example):

int isDigit(char ch)
{
    if(ch >= '0' && ch <= '9')
    {
        return true;
    }

    return false;
}

Now, since you were trying to compare specifically with 47876 then I would like to know your thoughts on that. Thanks. Happy programming.


问:
React ref undefined
so I'm having a little trouble using ref's with React.

All I'm trying to do is print the text content of an element using ref's like this:

```<code>export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}
</code>```

However, this always prints null or undefined instead of "Hi" which is what I want.

答:
You should use current with ref, like this.ref.current.textContent

Check the stackblitz demo Here

```<code>export default class App extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
  }

 componentDidMount(){
      console.log( this.intro.current.textContent);
    }

 render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}
</code>```

Title: React ref undefined

Body:
so I'm having a little trouble using ref's with React.

All I'm trying to do is print the text content of an element using ref's like this:

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (

Hi

    )
  }
}

However, this always prints null or undefined instead of "Hi" which is what I want.

Body:
You should use current with ref, like this.ref.current.textContent

Check the stackblitz demo Here

export default class App extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
  }

 componentDidMount(){
      console.log( this.intro.current.textContent);
    }

 render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}


问:
DOM manipulation does not work in User Agent String function
I am working on a website and a part of it involves interpreting whether the website is opened on a mobile or a desktop. I am using client side User agent string for this purpose. I update the inner HTML of one of my elements based on whether the website is opened on mobile or a desktop. I have taken the function from http://detectmobilebrowsers.com/

JavaScript code

```<code>window.onload =
    (function (a) {
        (jQuery.browser = jQuery.browser || {}).mobile = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))
        if (jQuery.browser.mobile === true) {
            $("#head").html("Mohawk Mobile")
            console.log("Mobile")
        } else {
            $("#head").html("Desktop")
            console.log("Desktop")
        }
    })(navigator.userAgent || navigator.vendor || window.opera)
</code>```

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Desktop

```

The console.log does work fine which means there is no problem in code functionality but I think there is some issue with the loading of the DOM elements. I tried to change the html outside the function and it does work.

答:
This could be happening since, #head might NOT be unique in your DOM. Therefore, it could help if you get more selective for your .html('<selector...>') substitution.

Also, I think it would be better if you think of another way to scale your mobile browser check. Because, this regex match, shown above, could get very hard to maintain for new mobile browser versions (IMHO).

Body:
I am working on a website and a part of it involves interpreting whether the website is opened on a mobile or a desktop. I am using client side User agent string for this purpose. I update the inner HTML of one of my elements based on whether the website is opened on mobile or a desktop. I have taken the function from http://detectmobilebrowsers.com/

JavaScript code

window.onload =
    (function (a) {
        (jQuery.browser = jQuery.browser || {}).mobile = /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))
        if (jQuery.browser.mobile === true) {
            $("#head").html("Mohawk Mobile")
            console.log("Mobile")
        } else {
            $("#head").html("Desktop")
            console.log("Desktop")
        }
    })(navigator.userAgent || navigator.vendor || window.opera)

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Desktop

The console.log does work fine which means there is no problem in code functionality but I think there is some issue with the loading of the DOM elements. I tried to change the html outside the function and it does work.