问:
Count the consecutive zero bits (trailing) on the right in parallel: an explanation?
Consider this link from the Bit Twiddling Hacks website.
In order to count the trailing bits, the following algorithm is used:

```<code>unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v); /* THIS LINE */
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
</code>```

Can someone explain me the role of the line marked as /* THIS LINE */ and more importantly is it possible to use only bitwise operations to avoid the use of signed() ?

EDIT: How to replace signed() by arithmetic/logical/bitwise operations?

答:
signed in this code is an error which causes undefined behavior.

It can be safely removed.  The code requires the behavior of unsigned negation... which signed negation may or may not deliver.  Without the keyword the behavior is always as expected.

Now, the code still is not portable.  But at least it will be safe, and it will work if int is 32 bits.

Body:
Consider this link from the Bit Twiddling Hacks website.
In order to count the trailing bits, the following algorithm is used:

unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v); /* THIS LINE */
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;

Can someone explain me the role of the line marked as /* THIS LINE */ and more importantly is it possible to use only bitwise operations to avoid the use of signed() ?

EDIT: How to replace signed() by arithmetic/logical/bitwise operations?


来源: stackexchange

问:
DROP FUNCTION without knowing the number/type of parameters?
I keep all my functions in a text file with 'CREATE OR REPLACE FUNCTION somefunction'.

So if I add or change some function I just feed the file to psql.

Now if I add or remove parameters to an existing function, it creates an overload with the same name and to delete the original I need type in all the parameter types in the exact order which is kind of tedious.

Is there some kind of wildcard I can use to DROP all functions with a given name so I can just add DROP FUNCTION lines to the top of my file?

答:
pgsql generates an error if there exists more than one procedure with the same name but different arguments when the procedure is deleted according to its name. Thus if you want to delete a single procedure without affecting others then simply use the following query.

SELECT 'DROP FUNCTION ' || oid::regprocedure
FROM   pg_proc
WHERE  oid = {$proc_oid}
```

ContentLicense: CC BY-SA 4.0


问:
Translating to english using word lists
Say I have a list of item-colour pairs:

Item1 red

Item2 red_in_finnish

Item3 red_in_polish

Item4 blue_in_russian

Item5 blue_in_estonian

Item6 blue_in_polish

I need to translate all the colours in foreign languages to English:

Item1 red

Item2 red

Item3 red

Item4 blue

Item5 blue

Item6 blue

In my actual code, I have many more than two colours, and about a dozen different arrays containing all the foreign words for each colour. This is the current way I am performing the replacement:

```<code>red_words = ['red_in_finnish', 'red_in_polish']
blue_words = ['blue_in_russian', 'blue_in_estonian', 'blue_in_polish']

for word in red_words:
   if word in item_name:
      item_name = item_name.replace(word, "red")
</code>```

The problem is that I do not know beforehand if each name contains any specific colour, so I need to check for all of them to make sure I replace everything.

Is there a smart way to do this? It would be perfect if it was possible to somehow map colours' foreign names to their English names.

答:
You could also try using a dict</p>

```<code>item_name = "hello my color is red_in_estonian"
dic = {
    "red_in_estonian"  :  "red",
    "red_in_german"    :  "red",
    "blue_in_estonian" :  "blue",
    "blue_in_german"   :  "blue",
}
for word in item_name.split(" "):
    try:
        translation = dic[word]
        item_name = item_name.replace(word, translation)

    except:
        pass
</code>```

Title: Translating to english using word lists

Body:
Say I have a list of item-colour pairs:

Item1 red

Item2 red_in_finnish

Item3 red_in_polish

Item4 blue_in_russian

Item5 blue_in_estonian

Item6 blue_in_polish

I need to translate all the colours in foreign languages to English:

Item1 red

Item2 red

Item3 red

Item4 blue

Item5 blue

Item6 blue

In my actual code, I have many more than two colours, and about a dozen different arrays containing all the foreign words for each colour. This is the current way I am performing the replacement:

red_words = ['red_in_finnish', 'red_in_polish']
blue_words = ['blue_in_russian', 'blue_in_estonian', 'blue_in_polish']

for word in red_words:
   if word in item_name:
      item_name = item_name.replace(word, "red")

The problem is that I do not know beforehand if each name contains any specific colour, so I need to check for all of them to make sure I replace everything.

Is there a smart way to do this? It would be perfect if it was possible to somehow map colours' foreign names to their English names.

Body:
You could also try using a dict

item_name = "hello my color is red_in_estonian"
dic = {
    "red_in_estonian"  :  "red",
    "red_in_german"    :  "red",
    "blue_in_estonian" :  "blue",
    "blue_in_german"   :  "blue",
}
for word in item_name.split(" "):
    try:
        translation = dic[word]
        item_name = item_name.replace(word, translation)

    except:
        pass


问:
Exclude urls from service-worker using webpack offline-plugin
i’m currently setting up 2 apps on the same domain using AWS Cloudfront to manage routes between the apps. One of the 2 apps is a React app, based on React-Boilerplate and using offline-plugin to setup service workers. By default,  routes of the react app are whitelisted in Cloudfront and the fallback routes are the routes of the other app (/blog for example).

The problem comes from the service workers of the React app which return the default 404 when calling a route of the other app.

I guess my url that should redirect to the other app, based on Cloudfront redirect, (for instance /blog which is a wordpress) is intercepted by the service worker and then return a 404 from the main app.

I've tried some options provided by webpack offline-plugin but my understanding of service-workers is not optimal...
I've tried playing with responseStrategy, excludes, ServiceWorkers cacheName but no success.

```<code>new OfflinePlugin({
      publicPath: '/',
      appShell: '/',
      excludes: ['.htaccess'],
      caches: {
        main: [':rest:'],
        additional: ['*.chunk.js'],
      },
      safeToUseOptionalCaches: true,
    }),
</code>```

答:
Use it in your

app.js

```<code>import * as serviceWorker from 'utils/serviceWorker';

serviceWorker.unregister();
</code>```

utils/serviceWorker.js

```<code>// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
    ),
);

export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit ',
          );
        });
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');

              // Execute callback
              if (config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');

              // Execute callback
              if (config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      if (
        response.status === 404 ||
        response.headers.get('content-type').indexOf('javascript') === -1
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.',
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}
</code>```

Body:
i’m currently setting up 2 apps on the same domain using AWS Cloudfront to manage routes between the apps. One of the 2 apps is a React app, based on React-Boilerplate and using offline-plugin to setup service workers. By default,  routes of the react app are whitelisted in Cloudfront and the fallback routes are the routes of the other app (/blog for example).

The problem comes from the service workers of the React app which return the default 404 when calling a route of the other app.

I guess my url that should redirect to the other app, based on Cloudfront redirect, (for instance /blog which is a wordpress) is intercepted by the service worker and then return a 404 from the main app.

I've tried some options provided by webpack offline-plugin but my understanding of service-workers is not optimal...
I've tried playing with responseStrategy, excludes, ServiceWorkers cacheName but no success.

new OfflinePlugin({
      publicPath: '/',
      appShell: '/',
      excludes: ['.htaccess'],
      caches: {
        main: [':rest:'],
        additional: ['*.chunk.js'],
      },
      safeToUseOptionalCaches: true,
    }),

Body:
Use it in your

app.js

import * as serviceWorker from 'utils/serviceWorker';

serviceWorker.unregister();

utils/serviceWorker.js

// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
    ),
);

export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit ',
          );
        });
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}

function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');

              // Execute callback
              if (config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');

              // Execute callback
              if (config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      if (
        response.status === 404 ||
        response.headers.get('content-type').indexOf('javascript') === -1
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.',
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}


问:
Sort array of days in ascending order
I have an array that contains unique strings of day names. The day names will be in random order. - eg:

```<code>["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"]
</code>```

I want to use javascript to sort that array so that it will be in ascending order.

```<code>["Wed 3pm", "Sat 10am", "Sat 4pm", "Sun 10am", "Sun 4pm"]
</code>```

Can anybody suggest the best way to do that?

Thank you

答:
You can create a object with days names as keys and values increasing from 1 to 7.

Create a helper function which takes second part of string i.e 3pm,10am.. as input and add 12 to result if its pm

Also divide the result by 24 so first sort should happen on days.

Use the sort() function and for each value add the time index(which will be always less than 1) to the day index(1,2,3...) and subtract it for both value.

const arr = ["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"];

function getTime(str){
  let time = str.slice(0,-2);
  let isAm = str.includes('am');
  return (isAm ? +time : +time + 12)/24
}

function sortTime(arr){
  let days = {
    Mon:1,
    Tue:2,
    Wed:3,
    Thur:4,
    Fri:5,
    Sat:6,
    Sun:7
  }
  return arr.slice().sort((a,b) => {
    let [day1,time1] = a.split(' ');
    let [day2,time2] = b.split(' ');
    return (days[day1] + getTime(time1)) - (days[day2] + getTime(time2))
  })

}

console.log(sortTime(arr))```

Title: Sort array of days in ascending order

Body:
I have an array that contains unique strings of day names. The day names will be in random order. - eg:

["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"]

I want to use javascript to sort that array so that it will be in ascending order.

["Wed 3pm", "Sat 10am", "Sat 4pm", "Sun 10am", "Sun 4pm"]

Can anybody suggest the best way to do that?

Thank you


问:
iOS swift How to create .p8 file?
I am working with Pushy Notification where I need to register with the p8 file. So how can I create that p8 file from developer account?

答:
First login Apple developer a/c. Go to Keys option, click + button

Than on next page, enter valid Name, check Push notification option and click, click continue, click download button, It will download .p8 file.

ContentLicense: CC BY-SA 3.0

Title: iOS swift How to create .p8 file?


问:
Flask WTForms SelectField Create choices from api data
I am pulling information from an api that is delivered like this:

```<code>{
  "Location": {
    "Units": [
     {
       "id": 1,
       "Item": [
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         }
       ]
     },
     {
       "id": 2,
       "Item": [
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         }
       ]
     }
    ]
  }
}
</code>```

I am providing a wtform with a select field:

forms.py

```<code>class ReserveForm(Form):
  item = SelectField(
    'Item',
    choices=[],
    coerce=int
  )
</code>```

I am passing the id of the "Unit.id" to my route as a url variable:

app.py

```<code>@app.route('/reserve/<id>')
def reserve(id):
  data = *my api data in json format*
  form = ReserveForm()
  return render_template('reserve.html', data=data, form=form)
</code>```

and in my view I am printing the form:

```<code><form action="" method="POST">
  {{ form.hidden_tag() }}
  {{ form.item.label() }}
  {{ form.item() }}
</form>
</code>```

What I need to do is use the 'Item's, from the 'Unit' with the ID that matches the id from the url variable, as the choices for the select field.

I cannot seam to find a way to add choices to the field at the template level, which would be my preferred method. Something like:

```<code><form action="" method="POST">
  {{ form.hidden_tag() }}
  {{ form.item.label() }}
  {{ form.item(choices=[data.Location.Unit[specific-ID].item]) }}
</form>
</code>```

I was banking on finding a solution like this, because I am most familiar with Jinja2.

Since I cannot find a way to make that work, I have been trying to figure out how to create the selectfield choices in the route. This posts was helpful: Dynamic choices WTForms Flask SelectField

however my data is structured differently because there is an extra nested layer.

I think I am getting it right, by looping through the 'Units' to find the one with an id matching my variable, and assigning that 'Unit' to a variable. Then I can do like on the post linked above, using a key value for loop (I do not know what this is called or how it works so I am not able to search for how it works):

```<code>@app.route('/reserve/<id>')
def reserve(id):
  data = *my api data in json format*
  for item in data['Location']['Unit']:
    if item['ID'] == id:
      unit = item
  items = [(item['ID'], item['Description']) for item in unit['Item']]
  form = ReserveForm()
  form.item.choices = items

  return render_template('reserve.html', data=data, form=form)
</code>```

I am pretty sure this is going to work, but I am receiving an error 'alueError: invalid literal for int() with base 10:'

obviously the key needs to be an integer, not a string. The problem is that both the description and ID from the api data are strings, and the id is a letter/number combo that can't be converted to an integer.

I need the description to be the display text for the select field option, and I need the value to be the ID string.

what can I use as the key if I don't have an integer ID? how do the name and value apply to the select field options if I can't use the ID string as the key? I am assuming the key will be the select field value.

**UPDATE: I replaced item['ID'] with the number '1':

```<code>items = [(1, item['Description']) for item in unit['Item']]
</code>```

and now the page is rendering, and the select field is working, but all of the select field values are set to '1':

```<code><option value="1">item name from api data</option>
</code>```

The value needs to be the ID of the item form the api data, and that looks like:

```<code>'ID': 'babb87d5-323f-4d56-9ed0-e2b643a78936'
</code>```

but it doesn't seam to be possible to use a string as the value. any advice would be appreciated.

答: I was forcing an int value by setting coerce to int in my field settings. The default for coerce is unicode. Once I changed that the field populated as it is supposed.</p>

Body:
I am pulling information from an api that is delivered like this:

{
  "Location": {
    "Units": [
     {
       "id": 1,
       "Item": [
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         }
       ]
     },
     {
       "id": 2,
       "Item": [
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         },
         {
           "Description": "some string value",
           "ID": "some string value"
         }
       ]
     }
    ]
  }
}

I am providing a wtform with a select field:

forms.py

class ReserveForm(Form):
  item = SelectField(
    'Item',
    choices=[],
    coerce=int
  )

I am passing the id of the "Unit.id" to my route as a url variable:

app.py

@app.route('/reserve/<id>')
def reserve(id):
  data = *my api data in json format*
  form = ReserveForm()
  return render_template('reserve.html', data=data, form=form)

and in my view I am printing the form:

<form action="" method="POST">
  {{ form.hidden_tag() }}
  {{ form.item.label() }}
  {{ form.item() }}
</form>

What I need to do is use the 'Item's, from the 'Unit' with the ID that matches the id from the url variable, as the choices for the select field.

I cannot seam to find a way to add choices to the field at the template level, which would be my preferred method. Something like:

<form action="" method="POST">
  {{ form.hidden_tag() }}
  {{ form.item.label() }}
  {{ form.item(choices=[data.Location.Unit[specific-ID].item]) }}
</form>

I was banking on finding a solution like this, because I am most familiar with Jinja2.

Since I cannot find a way to make that work, I have been trying to figure out how to create the selectfield choices in the route. This posts was helpful: Dynamic choices WTForms Flask SelectField

however my data is structured differently because there is an extra nested layer.

I think I am getting it right, by looping through the 'Units' to find the one with an id matching my variable, and assigning that 'Unit' to a variable. Then I can do like on the post linked above, using a key value for loop (I do not know what this is called or how it works so I am not able to search for how it works):

@app.route('/reserve/<id>')
def reserve(id):
  data = *my api data in json format*
  for item in data['Location']['Unit']:
    if item['ID'] == id:
      unit = item
  items = [(item['ID'], item['Description']) for item in unit['Item']]
  form = ReserveForm()
  form.item.choices = items

  return render_template('reserve.html', data=data, form=form)

I am pretty sure this is going to work, but I am receiving an error 'alueError: invalid literal for int() with base 10:'

obviously the key needs to be an integer, not a string. The problem is that both the description and ID from the api data are strings, and the id is a letter/number combo that can't be converted to an integer.

I need the description to be the display text for the select field option, and I need the value to be the ID string.

what can I use as the key if I don't have an integer ID? how do the name and value apply to the select field options if I can't use the ID string as the key? I am assuming the key will be the select field value.

**UPDATE: I replaced item['ID'] with the number '1':

items = [(1, item['Description']) for item in unit['Item']]

and now the page is rendering, and the select field is working, but all of the select field values are set to '1':

<option value="1">item name from api data</option>

The value needs to be the ID of the item form the api data, and that looks like:

'ID': 'babb87d5-323f-4d56-9ed0-e2b643a78936'

but it doesn't seam to be possible to use a string as the value. any advice would be appreciated.


问:
Align Widget inside Expanded in row in flutter
I'm trying to align widget inside the row but the widget automatically aligns to the center. I want to align both the widget to the top of the row.

```<code> Widget PlayerConnectWidget(double width,double height){
      return SingleChildScrollView(
          child: Container(

            margin: EdgeInsets.only(left: width*0.03,right: width*0.03,top: width*0.05),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Flexible(flex:1,fit:FlexFit.loose,child:MyFeedTile(),),
                    Flexible(flex:1,fit:FlexFit.loose,child:_logoContainer(width),),

                ],),
                SizedBox(height: width*0.02),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                   Expanded(flex: 7,child: Container(
                     margin: EdgeInsets.only(right: width*0.03),
                     padding: EdgeInsets.all(width*0.03),
                     decoration: BoxDecoration(color: Colors.white70,borderRadius: new BorderRadius.circular(12.0),),
                     child: Column(
                       crossAxisAlignment: CrossAxisAlignment.stretch,
                       children: <Widget>[
                       Text('Venue'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Location'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Sports'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Opening Times'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Notes'),
                         new Divider(
                           color: Colors.black87,
                         ),
                     ],),

                   ),),
                    Expanded(flex: 3, child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                    //  mainAxisAlignment: MainAxisAlignment.start,
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[

                      //  SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Message',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),),
                        SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Continue',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),)
                      ],),)
                  ],)
              ],
            ),
          )
      );
    }

Widget _logoContainer(double width){
  return Container(
    margin: EdgeInsets.only(left:width*0.05),
    height: 110.0,
    width: 120.0,
    decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/cmp_click.png"),
          fit: BoxFit.fill,
        )
    ),
  );
}
Widget MyFeedTile(){
  return GestureDetector(
    onTap: (){
      Navigator.push(context, MaterialPageRoute(builder: (context) => FeedView()),);
    },
    child: Container(
      padding: EdgeInsets.only(top:width*0.02,bottom: width*0.02),
      decoration: BoxDecoration(
        color: MyColors.colorPrimaryDark,
        borderRadius: new BorderRadius.circular(12.0),

      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Expanded(flex: 3,
            child: Container(
              //decoration: BoxDecoration(color: Colors.green[100]),
              height: 50,
              width: 50,
              margin: EdgeInsets.all(width*0.01),
              child: CircleAvatar(
                radius: 50.0,
                backgroundImage:
                NetworkImage('https://via.placeholder.com/150'),
                backgroundColor: Colors.transparent,),),

          ),
          Expanded(flex: 7,child: Container(
            //decoration: BoxDecoration(color: Colors.green[100]),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Text('User name',style: TextStyle(color: Colors.white,fontFamily: 'bold'),),
                SizedBox(height: width*0.01),
                Text('Time',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Location',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Date',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
              ],),),)
        ],),

    ),);
}
</code>```

I'm getting this

and I'm trying to achieve this

and this

答:
There is a property name cross-axis alignment for both Row and Column
As I see you have used main axis alignment.

Main Axis for Column is to align children Vertically.

Main Axis for Row is to align children Horizontally.

Cross Axis for Column is to align children Horizontally.

Cross Axis for Row is to align children Vertically.

So you can try with this for your row

```<code>crossAxisAlignment: CrossAxisAlignment.start,
</code>```

Body:
I'm trying to align widget inside the row but the widget automatically aligns to the center. I want to align both the widget to the top of the row.

 Widget PlayerConnectWidget(double width,double height){
      return SingleChildScrollView(
          child: Container(

            margin: EdgeInsets.only(left: width*0.03,right: width*0.03,top: width*0.05),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[

                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Flexible(flex:1,fit:FlexFit.loose,child:MyFeedTile(),),
                    Flexible(flex:1,fit:FlexFit.loose,child:_logoContainer(width),),

                ],),
                SizedBox(height: width*0.02),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                   Expanded(flex: 7,child: Container(
                     margin: EdgeInsets.only(right: width*0.03),
                     padding: EdgeInsets.all(width*0.03),
                     decoration: BoxDecoration(color: Colors.white70,borderRadius: new BorderRadius.circular(12.0),),
                     child: Column(
                       crossAxisAlignment: CrossAxisAlignment.stretch,
                       children: <Widget>[
                       Text('Venue'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Location'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Sports'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Opening Times'),
                         new Divider(
                           color: Colors.black87,
                         ),
                       Text('Notes'),
                         new Divider(
                           color: Colors.black87,
                         ),
                     ],),

                   ),),
                    Expanded(flex: 3, child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                    //  mainAxisAlignment: MainAxisAlignment.start,
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[

                      //  SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Message',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),),
                        SizedBox(height: width*0.02),
                        Container(
                          decoration: BoxDecoration(
                            color: MyColors.yellowBg,
                            borderRadius: new BorderRadius.circular(8.0),
                          ),
                          child:  FlatButton(
                              onPressed: (){
                              },
                              child: Text(
                                  'Continue',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16.0,

                                  )
                              )
                          ),)
                      ],),)
                  ],)
              ],
            ),
          )
      );
    }

Widget _logoContainer(double width){
  return Container(
    margin: EdgeInsets.only(left:width*0.05),
    height: 110.0,
    width: 120.0,
    decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/images/cmp_click.png"),
          fit: BoxFit.fill,
        )
    ),
  );
}
Widget MyFeedTile(){
  return GestureDetector(
    onTap: (){
      Navigator.push(context, MaterialPageRoute(builder: (context) => FeedView()),);
    },
    child: Container(
      padding: EdgeInsets.only(top:width*0.02,bottom: width*0.02),
      decoration: BoxDecoration(
        color: MyColors.colorPrimaryDark,
        borderRadius: new BorderRadius.circular(12.0),

      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Expanded(flex: 3,
            child: Container(
              //decoration: BoxDecoration(color: Colors.green[100]),
              height: 50,
              width: 50,
              margin: EdgeInsets.all(width*0.01),
              child: CircleAvatar(
                radius: 50.0,
                backgroundImage:
                NetworkImage('https://via.placeholder.com/150'),
                backgroundColor: Colors.transparent,),),

          ),
          Expanded(flex: 7,child: Container(
            //decoration: BoxDecoration(color: Colors.green[100]),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Text('User name',style: TextStyle(color: Colors.white,fontFamily: 'bold'),),
                SizedBox(height: width*0.01),
                Text('Time',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Location',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
                SizedBox(height: width*0.01),
                Text('Date',style: TextStyle(color: Colors.white,fontFamily: 'light'),),
              ],),),)
        ],),

    ),);
}

I'm getting this

and I'm trying to achieve this

and this

Body:
There is a property name cross-axis alignment for both Row and Column
As I see you have used main axis alignment.

Main Axis for Column is to align children Vertically.

Main Axis for Row is to align children Horizontally.

Cross Axis for Column is to align children Horizontally.

Cross Axis for Row is to align children Vertically.

So you can try with this for your row

crossAxisAlignment: CrossAxisAlignment.start,


问:
UNDERSTANDING how to count trailing zeros for a number using bitwise operators in C
Note - This is NOT a duplicate of this question - Count the consecutive zero bits (trailing) on the right in parallel: an explanation? . The linked question has a different context, it only asks the purpose of signed() being use. DO NOT mark this question as duplicate.

I've been finding a way to acquire the number of trailing zeros in a number. I found a bit twiddling Stanford University Write up HERE here that gives the following explanation.

```<code>unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
</code>```

Why does this end up working ? I have an understanding of how Hex numbers are represented as binary and bitwise operators, but I am unable to figure out the intuition behind this working ? What is the working mechanism ?

答:
This code (from the net) is mostly C, although v &= -signed(v); isn't correct C.  The intent is for it to behave as v &= ~v + 1;

First, if v is zero, then it remains zero after the & operation, and all of the if statements are skipped, so you get 32.

Otherwise, the & operation (when corrected) clears all bits to the left of the rightmost 1, so at that point v contains a single 1 bit. Then c is decremented to 31, i.e. all 1 bits within the possible result range.

The if statements then determine its numeric position one bit at a time (one bit of the position number, not of v), clearing the bits that should be 0.

Body:
Note - This is NOT a duplicate of this question - Count the consecutive zero bits (trailing) on the right in parallel: an explanation? . The linked question has a different context, it only asks the purpose of signed() being use. DO NOT mark this question as duplicate.

I've been finding a way to acquire the number of trailing zeros in a number. I found a bit twiddling Stanford University Write up HERE here that gives the following explanation.

unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;

Why does this end up working ? I have an understanding of how Hex numbers are represented as binary and bitwise operators, but I am unable to figure out the intuition behind this working ? What is the working mechanism ?


问:
Java Spring Boot + Mysql - Return a Json (key-value) response when the mysql query result does not match any model corresponding to any database table
I'm a beginner with Spring Boot and need some assistance for an issue.

In Spring Boot repository, I am fetching data from mysql database.

I have two types of return values from the repository.

a) The return value is a List of model that I have defined with @Entity tag and this model corresponds to a table in mysql. Ex: ZoneModel in the below code.

```<code>@Query(value = "select c from ZoneModel c where c.cityId = ?1")
public List<ZoneModel> getZonesInCity(String cityId);
</code>```

In this case, my response is:

```<code>[
  {
    "id": "1",
    "cityId": "1",
    "name": "Phoenix Marketcity",
    "type": "Mall",
    "locationLat": "12.9970372",
    "locationLong": "77.6944303"
  }
]
</code>```

The response is a key-value pair json.

b) The return value does not directly correspond to any model or list of any model. It has additional columns.

```<code>@Query(value = "select id, cityId, name, type, locationLat, locationLong," +
        " (6371 * acos (\n" +
        "cos ( radians(?2) )\n" +
        "* cos( radians( locationLat ) )\n" +
        "* cos( radians( locationLong ) - radians(?3) )\n" +
        "+ sin ( radians(?2) )\n" +
        "* sin( radians( locationLat ) )\n" +
        ")) as distanceInKms\n" +
        "from zone where cityId = ?1\n" +
        "group by id\n" +
        "having distanceInKms < 150\n" +
        "order by distanceInKms\n", nativeQuery = true)

public List<Object[]> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);
</code>```

In this case, the response is:

```<code>[
  [
    "1",
    "1",
    "Phoenix Marketcity",
    "Mall",
    "12.9970372",
    "77.6944303",
    0.19478083559705964
  ]
]
</code>```

The response does not have keys corresponding to the column names.

How can I return key-value pair responses with keys as column names even in the cases where the return value from the repository does not exactly match with any model?

答:
```<code>public List<Object[]> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);
</code>```

You are trying to map the result to a List of Object arrays. So spring did what you told it to do and mapped it to a list of object arrays.

Try this instead:

```<code>public List<Map<String, Object>> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);
</code>```

Body:
I'm a beginner with Spring Boot and need some assistance for an issue.

In Spring Boot repository, I am fetching data from mysql database.

I have two types of return values from the repository.

a) The return value is a List of model that I have defined with @Entity tag and this model corresponds to a table in mysql. Ex: ZoneModel in the below code.

@Query(value = "select c from ZoneModel c where c.cityId = ?1")
public List<ZoneModel> getZonesInCity(String cityId);

In this case, my response is:

[
  {
    "id": "1",
    "cityId": "1",
    "name": "Phoenix Marketcity",
    "type": "Mall",
    "locationLat": "12.9970372",
    "locationLong": "77.6944303"
  }
]

The response is a key-value pair json.

b) The return value does not directly correspond to any model or list of any model. It has additional columns.

@Query(value = "select id, cityId, name, type, locationLat, locationLong," +
        " (6371 * acos (\n" +
        "cos ( radians(?2) )\n" +
        "* cos( radians( locationLat ) )\n" +
        "* cos( radians( locationLong ) - radians(?3) )\n" +
        "+ sin ( radians(?2) )\n" +
        "* sin( radians( locationLat ) )\n" +
        ")) as distanceInKms\n" +
        "from zone where cityId = ?1\n" +
        "group by id\n" +
        "having distanceInKms < 150\n" +
        "order by distanceInKms\n", nativeQuery = true)

public List<Object[]> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);

In this case, the response is:

[
  [
    "1",
    "1",
    "Phoenix Marketcity",
    "Mall",
    "12.9970372",
    "77.6944303",
    0.19478083559705964
  ]
]

The response does not have keys corresponding to the column names.

How can I return key-value pair responses with keys as column names even in the cases where the return value from the repository does not exactly match with any model?

Body:
public List<Object[]> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);

You are trying to map the result to a List of Object arrays. So spring did what you told it to do and mapped it to a list of object arrays.

Try this instead:

public List<Map<String, Object>> getZoneSuggestions(String cityId, String latitude, String longitude, Pageable pageable);


问:
POST an item to JSON server db- Angular
I'm trying to POST an Item to my db in my json server. I'm sending the POST request from Angular. When I do so, I get the following error:

Note: when I do the get in a the GET end point it works fine. I'm very new on the server side

POST ERROR 404:
  Http failure response for http://localhost:3000/addMember: 404 Not Found

SERVER.JS

```<code>const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
....

app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(
  helmet({
    noCache: true
  })
);
app.use(
  hsts({
    maxAge: 15552000 // 180 days in seconds
  })
);

app.use(
  express.static(path.join(__dirname, 'dist/softrams-racing'), {
    etag: false
  })
);

app.get('/api/members', (req, res) => {
  request('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

// TODO: Dropdown!
app.get('/api/teams', (req, res) => {
  request('http://localhost:3000/teams', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

    // Submit Form!
    app.post('/api/members', function(request, response) {
  request.post('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      req.send(body);
    }
  });
});

  app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'dist/softrams-racing/index.html'));
    });

    app.listen('8000', () => {
      console.log('Vrrrum Vrrrum! Server starting!');
    });
</code>```

ANGULAR

```<code>addMember(memberForm: Member) {
    this.http.post(`${this.api}/addMember`, memberForm).subscribe(
      data => {
        console.log('POST Request is successful ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }
</code>```

UPDATE:
in my console i see this POST /addMember 404 12.105 ms - 2 and If i go to http://localhost:3000/addMember directly in the browser I see an empty object {} and if I go here http://localhost:3000/ I see this message To access and modify resources, you can use any HTTP method GET POST PUT PATCH DELETE OPTIONS

答:
Try to change your code like this:

```<code>addMember(memberForm: Member) {
    this.http.post(`${this.api}/api/addMember`, memberForm).subscribe(
      data => {
        console.log('POST Request is successful ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }
</code>```

From the error it is shown that your service is expecting the request at http://localhost:3000/api/addMember but your console.log shows that you are sending post request at http://locatlhost:3000/addMember

Title: POST an item to JSON server db- Angular

Body:
I'm trying to POST an Item to my db in my json server. I'm sending the POST request from Angular. When I do so, I get the following error:

Note: when I do the get in a the GET end point it works fine. I'm very new on the server side

POST ERROR 404:
  Http failure response for http://localhost:3000/addMember: 404 Not Found

SERVER.JS

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
....

app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(
  helmet({
    noCache: true
  })
);
app.use(
  hsts({
    maxAge: 15552000 // 180 days in seconds
  })
);

app.use(
  express.static(path.join(__dirname, 'dist/softrams-racing'), {
    etag: false
  })
);

app.get('/api/members', (req, res) => {
  request('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

// TODO: Dropdown!
app.get('/api/teams', (req, res) => {
  request('http://localhost:3000/teams', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

    // Submit Form!
    app.post('/api/members', function(request, response) {
  request.post('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      req.send(body);
    }
  });
});

  app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'dist/softrams-racing/index.html'));
    });

    app.listen('8000', () => {
      console.log('Vrrrum Vrrrum! Server starting!');
    });

ANGULAR

addMember(memberForm: Member) {
    this.http.post(`${this.api}/addMember`, memberForm).subscribe(
      data => {
        console.log('POST Request is successful ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }

UPDATE:
in my console i see this POST /addMember 404 12.105 ms - 2 and If i go to http://localhost:3000/addMember directly in the browser I see an empty object {} and if I go here http://localhost:3000/ I see this message To access and modify resources, you can use any HTTP method GET POST PUT PATCH DELETE OPTIONS

Body:
Try to change your code like this:

addMember(memberForm: Member) {
    this.http.post(`${this.api}/api/addMember`, memberForm).subscribe(
      data => {
        console.log('POST Request is successful ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }

From the error it is shown that your service is expecting the request at http://localhost:3000/api/addMember but your console.log shows that you are sending post request at http://locatlhost:3000/addMember


问:
How to play video in HTML page
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

```<code><video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>
</code>```

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

```<code><video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>
</code>```

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

答:
I can give you some pieces of advice.First,you can use the absolute path about video,place the video file on the server,then you can get a path such as www.xxx.com/movie.mp4,and you can write the code on your HTML page,like this:

```<code><video width="320" height="240" autoplay>
  <source src="www.xxx.com/movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>
</code>```

Second,you can place your video file on the directory as same as the HTML page location.For example,if your HTML page in the directory which called test.you can create a directory which called src,and you can write the code on your HTML page,like this:

```<code><video width="320" height="240" autoplay>
  <source src="./src/movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>
</code>```

Third,you can use the input tag to upload the local video file,the HTML code as below:

```<code>  <input type="file" id="myInput"/>
  <video controls autoplay></video>

</code>```

the js code as below:

```<code>     var input = document.getElementById('myInput'),
         video = document.getElementById('myVideo');
        input.onchange = function () {
            var file = this.files[0];
            var url = URL.createObjectURL(file);
            video.innerHTML = '<source src="' + url + '" type="video/mp4">';
        }
</code>```

Fourth,use the object tag.you can write the code,like this:

```<code>//the HTML code
<div id="playhere"></div>
</code>```

```<code>//js code
function play(fn){
  var str='<object id="MediaPlayer" height="300" classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" style="width:70%"><param name="URL" value=\''+fn+'\'\/><param name="autoStart" value="1"\/><param name="balance" value="0"\/><param name="baseURL" value=""\/><param name="currentPosition" value="0"\/><param name="currentMarker" value="0"\/><param name="defaultFrame" value=""\/><param name="enabled" value="1"\/><param name="enableErrorDialogs" value="0"\/><param name="enableContextMenu" value="0"\/><param name="fullScreen" value="0"\/><param name="invokeURLs" value="1"\/><param name="mute" value="0"\/><param name="playCount" value="1"\/><param name="rate" value="1"\/><param name="stretchToFit" value="0"\/><param name="uiMode" value="full"\/><param name="volume" value="100"\/><param name="windowlessVideo" value="1"\/><\/object>';
   document.getElementById('playhere').innerHTML=str;
}
// that's your video file location
 play('D:\\Video\\samplevideo.mp4')
</code>```

but that way isn't supported on chrome browser.

Excuse me,I'm new to speak English.

Title: How to play video in HTML page

Body:
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

<video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

<video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

Body:
I can give you some pieces of advice.First,you can use the absolute path about video,place the video file on the server,then you can get a path such as www.xxx.com/movie.mp4,and you can write the code on your HTML page,like this:

<video width="320" height="240" autoplay>
  <source src="www.xxx.com/movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

Second,you can place your video file on the directory as same as the HTML page location.For example,if your HTML page in the directory which called test.you can create a directory which called src,and you can write the code on your HTML page,like this:

<video width="320" height="240" autoplay>
  <source src="./src/movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

Third,you can use the input tag to upload the local video file,the HTML code as below:

  <input type="file" id="myInput"/>
  <video controls autoplay></video>

the js code as below:

     var input = document.getElementById('myInput'),
         video = document.getElementById('myVideo');
        input.onchange = function () {
            var file = this.files[0];
            var url = URL.createObjectURL(file);
            video.innerHTML = '<source src="' + url + '" type="video/mp4">';
        }

Fourth,use the object tag.you can write the code,like this:

//the HTML code
<div id="playhere"></div>

//js code
function play(fn){
  var str='<object id="MediaPlayer" height="300" classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6" style="width:70%"><param name="URL" value=\''+fn+'\'\/><param name="autoStart" value="1"\/><param name="balance" value="0"\/><param name="baseURL" value=""\/><param name="currentPosition" value="0"\/><param name="currentMarker" value="0"\/><param name="defaultFrame" value=""\/><param name="enabled" value="1"\/><param name="enableErrorDialogs" value="0"\/><param name="enableContextMenu" value="0"\/><param name="fullScreen" value="0"\/><param name="invokeURLs" value="1"\/><param name="mute" value="0"\/><param name="playCount" value="1"\/><param name="rate" value="1"\/><param name="stretchToFit" value="0"\/><param name="uiMode" value="full"\/><param name="volume" value="100"\/><param name="windowlessVideo" value="1"\/><\/object>';
   document.getElementById('playhere').innerHTML=str;
}
// that's your video file location
 play('D:\\Video\\samplevideo.mp4')

but that way isn't supported on chrome browser.

Excuse me,I'm new to speak English.


问:
New Google Places Autocomplete and its pricing
I am using the new Place Autocomplete that is from the new static Google Places SDK client library (here). So it is really easy to use and I just got this tutorial and it is working as expected.

To add this in the project, I have to add following dependency in the Gradle file:

implementation ‘com.google.android.libraries.places:places:1.0.0’

I have been reading Google pricing/usage and billing, but I have not figured out the pricing of this new Autocomplete (library version). All I found was this, but to me it looks like it is for the web version, as I do not think the session needs to maintain this new client library version.

As I am not able to figure out pricing for the Places Auto complete (library version), is it free? Or if it is not free, what are billing criteria for this?

答:
It costs less than US$3 for 1000 requests, but as a user you have US$200 monthly credit equivalent free usage, so the API is free as long as you don't exceed this.

Perhaps this pricing table would be helpful.


问:
React-datepicker with a Formik form
I'm trying to use react-datepicker in a Formik form.

I have:

```<code>import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

class Fuate extends React.Component {
    state = {
        dueDate: new Date()

    }

<Formik
                initialValues={initialValues}
                validationSchema={Yup.object().shape({
                    title: Yup.string().required("A title is required "),
                })}

                onSubmit={this.handleSubmit}

                render={({
                    errors,
                    status,
                    touched,
                    setFieldValue,
                    setFieldTouched,
                    handleChange,
                    handleBlur,
                    handleSubmit,
                    isSubmitting,
                    dirty,
                    values
                }) => {

                return (
                    <div>
            ...

<DatePicker
                                            name={'dueDate'}
                                            value={values['dueDate']}
                                            onChange={e => setFieldValue('dueDate', e)}
                                        />
                                        <DatePicker
                                        style={{ width: 180 }}
                                        date={values.dueDate}
                                        mode="date"
                                        format="YYYY-MM-DD"
                                        minDate={Date.now.toString()}
                                        maxDate="2050-06-01"
                                        confirmBtnText="Confirm"
                                        cancelBtnText="Cancel"
                                        showIcon={false}
                                        customStyles={{
                                            dateInput: {
                                            marginLeft: 0,
                                            borderColor: "#fff"
                                            }
                                        }}
                                        onDateChange={date => setFieldValue("dueDate", date)}
                                        onTouch={setFieldTouched}
                                        />
</code>```

For both of these options, the form renders, I can select a date on the calendar but it does not appear in the box and the state value is not updated with the selection.

There are no errors in the console, but the warning says:

Starting with v2.0.0-beta.1 date-fns doesn't accept strings as
  arguments. Please use parseISO to parse strings. See:
  toDate @ index.js:45

I tried making the initial state:

```<code>dueDate: new Date().toISOString(),
</code>```

but it makes no difference.

I've seen lots of posts about setting this up with Antd's date picker, but can't find instructions for how to do it with react-datepicker.

答:
react-datepicker can used with Formik by utilising setFieldValue,

```<code>const DatePickerField = ({ name, value, onChange }) => {
    return (
        <DatePicker
            selected={(value && new Date(value)) || null}
            onChange={val => {
                onChange(name, val);
            }}
        />
    );
};

const App = () => (
    <Formik
        initialValues={{ date: "" }}
        ...
    >
        {props => {
            const {
                values,
                handleSubmit,
                setFieldValue
                ...
            } = props;
            return (
                <form onSubmit={handleSubmit}>
                    <DatePickerField
                        name="date"
                        value={values.date}
                        onChange={setFieldValue}
                    />
                    ...
</code>```

CodeSandbox demo here

Title: React-datepicker with a Formik form

Body:
I'm trying to use react-datepicker in a Formik form.

I have:

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

class Fuate extends React.Component {
    state = {
        dueDate: new Date()

    }

<Formik
                initialValues={initialValues}
                validationSchema={Yup.object().shape({
                    title: Yup.string().required("A title is required "),
                })}

                onSubmit={this.handleSubmit}

                render={({
                    errors,
                    status,
                    touched,
                    setFieldValue,
                    setFieldTouched,
                    handleChange,
                    handleBlur,
                    handleSubmit,
                    isSubmitting,
                    dirty,
                    values
                }) => {

                return (

            ...

<DatePicker
                                            name={'dueDate'}
                                            value={values['dueDate']}
                                            onChange={e => setFieldValue('dueDate', e)}
                                        />
                                        <DatePicker
                                        style={{ width: 180 }}
                                        date={values.dueDate}
                                        mode="date"
                                        format="YYYY-MM-DD"
                                        minDate={Date.now.toString()}
                                        maxDate="2050-06-01"
                                        confirmBtnText="Confirm"
                                        cancelBtnText="Cancel"
                                        showIcon={false}
                                        customStyles={{
                                            dateInput: {
                                            marginLeft: 0,
                                            borderColor: "#fff"
                                            }
                                        }}
                                        onDateChange={date => setFieldValue("dueDate", date)}
                                        onTouch={setFieldTouched}
                                        />

For both of these options, the form renders, I can select a date on the calendar but it does not appear in the box and the state value is not updated with the selection.

There are no errors in the console, but the warning says:

Starting with v2.0.0-beta.1 date-fns doesn't accept strings as
  arguments. Please use parseISO to parse strings. See:
  toDate @ index.js:45

I tried making the initial state:

dueDate: new Date().toISOString(),

but it makes no difference.

I've seen lots of posts about setting this up with Antd's date picker, but can't find instructions for how to do it with react-datepicker.

Body:
react-datepicker can used with Formik by utilising setFieldValue,

const DatePickerField = ({ name, value, onChange }) => {
    return (
        <DatePicker
            selected={(value && new Date(value)) || null}
            onChange={val => {
                onChange(name, val);
            }}
        />
    );
};

const App = () => (
    <Formik
        initialValues={{ date: "" }}
        ...
    >
        {props => {
            const {
                values,
                handleSubmit,
                setFieldValue
                ...
            } = props;
            return (
                <form onSubmit={handleSubmit}>
                    <DatePickerField
                        name="date"
                        value={values.date}
                        onChange={setFieldValue}
                    />
                    ...

CodeSandbox demo here


问:
How to loop through two lists simultaneously?
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

```<code>For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next
</code>```

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

答:
The answers to my question is-it-possible-to-iterate-over-two-ienumerable-objects-at-the-same-time may help</p>

```<code>  Dim listA As List(Of A)
            Dim listb As List(Of B)

            listA.Zip(listb, Function(a, b) a.property1 = b.property1).ForEach(AddressOf Print)

Shared Sub Print(ByVal s As A)
    Console.WriteLine(s.Property1)
End Sub
</code>```

Body:
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

Body:
The answers to my question is-it-possible-to-iterate-over-two-ienumerable-objects-at-the-same-time may help

  Dim listA As List(Of A)
            Dim listb As List(Of B)

            listA.Zip(listb, Function(a, b) a.property1 = b.property1).ForEach(AddressOf Print)

Shared Sub Print(ByVal s As A)
    Console.WriteLine(s.Property1)
End Sub


问:
No response data available for this request after POST requests in AJAX
I used AJAX POST request to fill my datatable. In my php file, i have a query and store it on array and return as json. But it returns "No response data available for this request" even though the fields are the same in php and database. If I include UserName error will occur. Please help me fix this one.

I already alter my Database field name from UserName to username but still won't work.

PHP File. (user_action.php)

```<code>if ($_POST["action"] == 'fetch') {
    $query = "SELECT * FROM userslist ";
    if (isset($_POST["search"]["value"])) {
        $query .= 'WHERE UserName LIKE "%' . $_POST["search"]["value"] . '%" ';
    }
    if (isset($_POST["order"])) {
        $query .= 'ORDER BY ' . $_POST['order']['0']['column'] . ' ' . $_POST['order']['0']['dir'] . ' ';
    } else {
        $query .= 'ORDER BY id DESC ';
    }
    if ($_POST["length"] != -1) {
        $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
    }

    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    // var_dump($result);
    // exit();
    $data = array();
    $filtered_rows = $statement->rowCount();
    foreach ($result as $row) {
        // var_dump($row["window"]);
        // exit();
        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row['UserName'];
        $sub_array[] = $row["UserDesignation"];
        $sub_array[] = $row["UserType"];
        $sub_array[] = $row["UserDesc"];
        $sub_array[] = $row["status"];
        $sub_array[] = $row["window"];
        $sub_array[] = '<button type="button" name="edit_user" class="btn btn-primary btn-sm edit_user" id="' . $row["id"] . '"><i class="fa fa-pencil"></i> Edit</button> <button type="button" name="delete_user" class="btn btn-danger btn-sm delete_user" id="' . $row["id"] . '"><i class="fa fa-trash"></i> Delete</button>';
        $data[] = $sub_array;
    }

    $output = array(
        "draw"    => intval($_POST["draw"]),
        "recordsTotal"  =>  $filtered_rows,
        "recordsFiltered" => get_total_records($connect, 'userslist'),
        "data"    => $data
    );
    echo json_encode($output);
}
</code>```

AJAX (user.php)

```<code>var dataTable = $('#user_table').DataTable({
    "processing": true,
    "serverSide": true,
    "order": [],
    "ajax": {
        url: "dal/user_action.php",
        type: "POST",
        data: {
            action: 'fetch'
        }
        // dataType: "json",
        // error: function(result) {
        //     alert(result);
        // }0
    },
    "columnDefs": [{
        "targets": [0, 1, 2, 3, 4, 5, 6],
        // "targets": [0, 1, 2, 3, 4, 5, 6, 7],
        "orderable": false,
    }, ],
});
</code>```

Errors:

DataTables warning: table id=user_table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

and

No response data available for this request

答:
It looks like your query is getting malformed in this case because you have not set the value of $_POST['length'] and the following comparison evaluates to true

```<code>if ($_POST["length"] != -1){ ... }
</code>```

Try setting default values first

```<code>$length = (isset($_POST["length"]))? $_POST["length"] : -1;
$start = (isset($_POST["start"]))? $_POST["start"] : 0;
if ($_POST["length"] > -1) {
    $query .= 'LIMIT ' . $start . ', ' . $length;
}
</code>```

Body:
I used AJAX POST request to fill my datatable. In my php file, i have a query and store it on array and return as json. But it returns "No response data available for this request" even though the fields are the same in php and database. If I include UserName error will occur. Please help me fix this one.

I already alter my Database field name from UserName to username but still won't work.

PHP File. (user_action.php)

if ($_POST["action"] == 'fetch') {
    $query = "SELECT * FROM userslist ";
    if (isset($_POST["search"]["value"])) {
        $query .= 'WHERE UserName LIKE "%' . $_POST["search"]["value"] . '%" ';
    }
    if (isset($_POST["order"])) {
        $query .= 'ORDER BY ' . $_POST['order']['0']['column'] . ' ' . $_POST['order']['0']['dir'] . ' ';
    } else {
        $query .= 'ORDER BY id DESC ';
    }
    if ($_POST["length"] != -1) {
        $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
    }

    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    // var_dump($result);
    // exit();
    $data = array();
    $filtered_rows = $statement->rowCount();
    foreach ($result as $row) {
        // var_dump($row["window"]);
        // exit();
        $sub_array = array();
        $sub_array[] = $row["id"];
        $sub_array[] = $row['UserName'];
        $sub_array[] = $row["UserDesignation"];
        $sub_array[] = $row["UserType"];
        $sub_array[] = $row["UserDesc"];
        $sub_array[] = $row["status"];
        $sub_array[] = $row["window"];
        $sub_array[] = '<button type="button" name="edit_user" class="btn btn-primary btn-sm edit_user" id="' . $row["id"] . '"> Edit</button> <button type="button" name="delete_user" class="btn btn-danger btn-sm delete_user" id="' . $row["id"] . '"> Delete</button>';
        $data[] = $sub_array;
    }

    $output = array(
        "draw"    => intval($_POST["draw"]),
        "recordsTotal"  =>  $filtered_rows,
        "recordsFiltered" => get_total_records($connect, 'userslist'),
        "data"    => $data
    );
    echo json_encode($output);
}

AJAX (user.php)

var dataTable = $('#user_table').DataTable({
    "processing": true,
    "serverSide": true,
    "order": [],
    "ajax": {
        url: "dal/user_action.php",
        type: "POST",
        data: {
            action: 'fetch'
        }
        // dataType: "json",
        // error: function(result) {
        //     alert(result);
        // }0
    },
    "columnDefs": [{
        "targets": [0, 1, 2, 3, 4, 5, 6],
        // "targets": [0, 1, 2, 3, 4, 5, 6, 7],
        "orderable": false,
    }, ],
});

Errors:

DataTables warning: table id=user_table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

and

No response data available for this request

Body:
It looks like your query is getting malformed in this case because you have not set the value of $_POST['length'] and the following comparison evaluates to true

if ($_POST["length"] != -1){ ... }

Try setting default values first

$length = (isset($_POST["length"]))? $_POST["length"] : -1;
$start = (isset($_POST["start"]))? $_POST["start"] : 0;
if ($_POST["length"] > -1) {
    $query .= 'LIMIT ' . $start . ', ' . $length;
}


问:
Is there a Yarn equivalent for "npm dedupe"?
Just tried out Yarn and indeed it's mega-fast. After running yarn in the console with a loaded package.json, it installed everything. I then ran npm dedupe expecting nothing much to happen since Yarn is so optimized, but it removed a ton of stuff. Is there some Yarn equivalent to npm dedupe?

Addition:

As noted in my comment below, I thought perhaps yarn install --flat might be an npm dedupe equivalent as the Yarn documentation describes it as "installing one and only one version of a package". So I played around with --flat and there's a couple things to note:

It will prompt you to choose what version of a package to install when the tree results in requests for more than one version. I could imagine this being one hell of a task for larger projects. I just picked the latest version for each package I was prompted for and as you can imagine, trying to run the app resulted in cannot find module errors.

I ran npm dedupe after doing a yarn install --flat and it still resulted in a ton of removals. This was a surprise to me.

So I'm taking it that npm dedupe is doing some other magic under the hood and I'm just naive about processes that I need not be concerned with. Perhaps it's just best to leave the tree alone and forget about --flat and dedupe altogether.

答: It seems like even now Yarn doesn't do the greatest job of minimizing duplicate dependencies. Running yarn --flat forces there to be only one version of a dependency even when they may not be compatible, so that's not ideal. You can use the yarn-deduplicate package to minimize the number of duplicates, while still allowing some in cases where there are not overlapping requirements. yarn-deduplicate also has a --fail option which will return a non-zero (failing) status. This can be useful to run on CI to ensure that anybody who modifies dependencies doesn't introduce new duplicates.


问:
Need help on extracting and spliting url in to seperate variables
I have one raw input from end user in to a variable as below
javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')

I want to extract url from the above input.

I want to split the url using '/' in to seperate variables.

Input :

$DSURL = "javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')"

```<code>
[regex]$regex = '(?<=https:\/\/\HS\\/v1\/dev\/A\?t=)(.*)(?=' )'

$regex.Matches($DSURL).Value
</code>```

$1 = https://HS/v1/dev/A/Machinename/SNAPNAME
$2 = Machinename
$3 = SNAPNAME

But it is not working,
I think the regex used is wrong,
Please help

答:
this uses the [uri] type accelerator to convert the uri string into a uri object. then it uses the .Segments property to grab the last two segments and put them into $Vars.

you may want to look at the various properties stored in the $UriObject variable for some other interesting info. [grin]

```<code>$DSUrl = "javascript:DS('https://HS/v1/dev/A/SpiffyDoodleServer/SomeSortOfThing','XXXXX')"

$CleanedDSU = $DSUrl.Split('(')[1].Split(',')[0].Trim("'")
$UriObject = [uri]$CleanedDSU

$MachineName = $UriObject.Segments[-2].Trim('/')
$SnapName = $UriObject.Segments[-1]

$DSUrl
$CleanedDSU
$MachineName
$SnapName
</code>```

output ...

```<code>javascript:DS('https://HS/v1/dev/A/SpiffyDoodleServer/SomeSortOfThing','XXXXX')
https://HS/v1/dev/A/SpiffyDoodleServer/SomeSortOfThing
SpiffyDoodleServer
SomeSortOfThing
</code>```

Body:
I have one raw input from end user in to a variable as below
javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')

I want to extract url from the above input.

I want to split the url using '/' in to seperate variables.

Input :

$DSURL = "javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')"

[regex]$regex = '(?<=https:\/\/\HS\\/v1\/dev\/A\?t=)(.*)(?=' )'

$regex.Matches($DSURL).Value

$1 = https://HS/v1/dev/A/Machinename/SNAPNAME
$2 = Machinename
$3 = SNAPNAME

But it is not working,
I think the regex used is wrong,
Please help

Body:
this uses the [uri] type accelerator to convert the uri string into a uri object. then it uses the .Segments property to grab the last two segments and put them into $Vars.

you may want to look at the various properties stored in the $UriObject variable for some other interesting info. [grin]

$DSUrl = "javascript:DS('https://HS/v1/dev/A/SpiffyDoodleServer/SomeSortOfThing','XXXXX')"

$CleanedDSU = $DSUrl.Split('(')[1].Split(',')[0].Trim("'")
$UriObject = [uri]$CleanedDSU

$MachineName = $UriObject.Segments[-2].Trim('/')
$SnapName = $UriObject.Segments[-1]

$DSUrl
$CleanedDSU
$MachineName
$SnapName

output ...

javascript:DS('https://HS/v1/dev/A/SpiffyDoodleServer/SomeSortOfThing','XXXXX')
https://HS/v1/dev/A/SpiffyDoodleServer/SomeSortOfThing
SpiffyDoodleServer
SomeSortOfThing


问:
How can I alter this column so Pandas will recognize it?
I'm working with a csv that lists citations issued by a local city to residents who violated a homesharing law. One of the columns has the addresses of the violators. I added another column with the census tracts that those addresses are located in, but pandas is not recognizing it for some reason.

For example, one of the census tracts that appears multiple times in the census_tract column is 7002.00. But when I enter

```<code>citations[citations.census_tract == '7002.00']
</code>```

All I get are the column headers with 0 rows.

But when I enter:

```<code>citations.census_tract
</code>```

I get an accurate list of the census tracts in the census_tract column

What should I do to the column so pandas will read it when I try to get an output == to a specific census tract?

答:
It seems that values from census_tract column have been read as float.
If this is what you intend then change the instruction in question to:

```<code>citations[citations.census_tract == 7002.00]
</code>```

(without apostrophes).

Another possibility is that this column contains values only "looking like" float,
but actually they should be treated as strings.

If this is the case, read the csv file with respective parameter concerning
the type of this column. Something like:

```<code>types_dict = {'census_tract': string}
citations = read_csv('input.csv', dtype=types_dict)
</code>```

Then your instruction should execute withot error.

The second version of your instruction (citations[citations.census_tract])
is wrong, because:

pandas reads values from census_tract column,

looks in citations for columns with names just read.

Body:
I'm working with a csv that lists citations issued by a local city to residents who violated a homesharing law. One of the columns has the addresses of the violators. I added another column with the census tracts that those addresses are located in, but pandas is not recognizing it for some reason.

For example, one of the census tracts that appears multiple times in the census_tract column is 7002.00. But when I enter

citations[citations.census_tract == '7002.00']

All I get are the column headers with 0 rows.

But when I enter:

citations.census_tract

I get an accurate list of the census tracts in the census_tract column

What should I do to the column so pandas will read it when I try to get an output == to a specific census tract?

Body:
It seems that values from census_tract column have been read as float.
If this is what you intend then change the instruction in question to:

citations[citations.census_tract == 7002.00]

(without apostrophes).

Another possibility is that this column contains values only "looking like" float,
but actually they should be treated as strings.

If this is the case, read the csv file with respective parameter concerning
the type of this column. Something like:

types_dict = {'census_tract': string}
citations = read_csv('input.csv', dtype=types_dict)

Then your instruction should execute withot error.

The second version of your instruction (citations[citations.census_tract])
is wrong, because:

pandas reads values from census_tract column,

looks in citations for columns with names just read.


问:
Angular 7 : how to tell Angular compiler / builder not to include data from js?
I have a project where I build a static web just for diplaying items. I don't have backend system so I just use Angular to display list of items from js. I want user able to update their item from js without re-compiling the angular app.

here is my sample https://stackblitz.com/edit/mockdatatestangular?embed=1&file=src/app/app.component.html

in here I have mockupdata.ts where I store all data that need to be displayed. I want this to be editable / renewable (I mean I can just upload new mockupdata.ts to server without re compile the entire app).

Is it possible to do that ?

答:
When you compile your Angular code, you turn it into JS code in one or more JS files. Your Angular app can't "read" from a TypeScript file. It's not dynamic in that way. In the process you're describing, your data is hardcoded in the final bundle.

What you might try doing is uploading your data in a JSON file and reading it from there, as long as your server allows for it. If not, you'll need some basic server which can return your data as JSON.


问:
Define multiple variable of same datatype in Azure Logic Apps
I am creating a Azure Logic App. I need to Define multiple variable of same datatype. What is the quickest / good way to define it. I tried   code view  to add more variables but seems its not supported yet:

答:
What is the purpose of all the variables except for the obvious to store the data? My question is. Is it possible to parse the data into dynamic content by a Parse JSON action which a schema to store them as dynamic content with type string?

Otherwise, you will have to add multiple Initialize Variable actions after each other.

You could also store the data in a Variable array and work with it from there. Store it in an array and if you prefer Javascript inline Code


问:
anyone know of a plugin (or service) email autoresponder for trac?
Eric Willis' response to this question:

https://stackoverflow.com/questions/563041/receive-emails-in-a-net-service-c

prompted me to start thinking of creating a general purpose (initially for trac only) autoresponder and issue creator that listens to some "support" email account, creates an issue in your issue tracker and responds to the client with the issue id.  (I like fogbugz implementation but I have other projects that can't afford the license)

I am thinking of open sourcing this, so please let me know if there is another effort/project.

The goal is to make this generic to be able to use a number of different inputs (pop email for now) and a number of different issue trackers (trac for now)

I also think having it do the "whine" like bugzilla and others have (weekly/periodic emails for open assigned tasks) - or perhaps that is just another service that shares code...

So, I think the question is: does anyone know of an existing open source project?  If not I think i will start one.  I might do it in .NET/Mono, but I am not sure what the implications are for that for running as a service and what that means for non Win32 OS...

I suspect the biggest issues will be:

spam and how/where to handle that

outgoing email integration - email from your support to client and integrating with issue (CC field works, but is not ideal)

Parsing emails to the support address so as to only add the new information and not the existing - particularly when email is mixed with question/response...

答:
It already exists for trac.  It's called email2trac

I just looked at my ticket e-mails from email2trac and the ticket number is in the subject line.

OwnerDisplayName: Tim

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: JPunyon

LastEditorDisplayName: JPunyon


问:
OpenCV for ARM (Beagleboard) using YUYV instead of JPEG compression?
I am running OpenCV on a Beagleboard xM with a webcam under Ubuntu. The webcam runs fine, but only in YUYV mode. I.e., luvcview using jpeg compression has many frames which are half cut-off, incorrect colors etc. But luvcview -f YuYV works perfectly.

Is it possible to disable jpeg compression for OpenCV?

I've tried building and installing openCV with the make option: --without-jpeg, but it takes 4 hours to complete the make and make install and usually crashes at 90%+ completed.

Is there a way to cross-compile this no-jpeg version of OpenCV for ARM, or a way to disable jpeg using pre-built installation packages?

Error during make install:

[ 95%] Building CXX object tests/cv/CMakeFiles/opencv_test.dir/src/amoments.o
Linking CXX executable ../../bin/opencv_test
CMakeFiles/opencv_test.dir/src/highguitest.o:  In function `CV_HighGuiTest::run(int)':

... etc

../../lib/libopencv_features2d.so.2.2.0: undefined reference to cv::SIFT;:SIFT(double, bool bool, int, int, int, int))
... etc

collect2: ld returned 1 exit status
make[2]: * [bin/opencv_test] Error 1
make[1]: * [tests/cv/CMakeFiles/opencv_test.dir/all] Error 2
make: * [all] Error 2
(back to bash)

答:
I am having the same issue. This might help: http://tech.groups.yahoo.com/group/OpenCV/message/77273

you can enable SIFT in modules/features2d/src/sift.cpp. you can search for #ifdef arm in the file. commenting the line 51-53 in sift.cpp e.g.: //#define ARM_NO_SIFT

Also if you are using a beagle you'll need to run cmake with the -DWITH_JPEG=OFF option.


问:
Sort array of days in ascending order
I have an array that contains unique strings of day names. The day names will be in random order. - eg:

```<code>["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"]
</code>```

I want to use javascript to sort that array so that it will be in ascending order.

```<code>["Wed 3pm", "Sat 10am", "Sat 4pm", "Sun 10am", "Sun 4pm"]
</code>```

Can anybody suggest the best way to do that?

Thank you

答:
You can use the combination of map and sort. Here I am converting time in 24 Hours format for easy comparison of numbers.

var array = ["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"],
mapping = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 7 },

result = array
  .map((time, i) => {
    const hour = parseInt(time.split(" ")[1], 10);
    const hour24 = time.indexOf("am") > -1 ? hour : hour + 12;
    return {
      index: i,
      day: mapping[time.split(" ")[0]],
      hour24
    }
  })
  .sort((a, b) => a.day - b.day || a.hour24 - b.hour24)
  .map(({
    index
  }) => array[index]);

console.log(result);```

Title: Sort array of days in ascending order

Body:
I have an array that contains unique strings of day names. The day names will be in random order. - eg:

["Sun 10am", "Sat 4pm", "Sat 10am", "Wed 3pm", "Sun 4pm"]

I want to use javascript to sort that array so that it will be in ascending order.

["Wed 3pm", "Sat 10am", "Sat 4pm", "Sun 10am", "Sun 4pm"]

Can anybody suggest the best way to do that?

Thank you


问:
Remove background (from edges) from image and plot histogram
Using python, I want to remove background of an image and plot histogram (bar) of the remaining part of the image.  In particular, I want to remove a black background into which the image has been embedded. This black background is in the top right, top left, bottom right and bottom left of the image. Following is my image:

The useful part of the image is the circular thing in the center, and I want to draw a histogram for this useful part of the image. How can I remove the said background and plot the histogram?

Following is my code of what I have done so far.

```<code>from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.pyplot import bar
import numpy as np

im_gray = Image.open('image.png').convert('L')
im_arr = np.array( im_gray )
im_flat = im_arr.ravel()

mark_bkg = np.where( im_flat != im_arr[0,0]  )[0]
im_no_bkg = im_flat[ mark_bkg ]

hist, bin_edges = np.histogram(im_no_bkg, bins=30, density=False)

plt.figure(1)
bar( x=bin_edges[:-1], height=hist, width=1.0, bottom=None, align='center', data=None )
plt.show()
</code>```

答:
Incase you store the image as grayscale [0-255].

To hide the black 255 background, apply a mask() on the image.

```<code># Removing black background
img = np.array([...])
img = np.ma.masked_equal(img, 255)

# Plotting histogram
plt.hist(img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
plt.show()
</code>```

Plotting

Body:
Using python, I want to remove background of an image and plot histogram (bar) of the remaining part of the image.  In particular, I want to remove a black background into which the image has been embedded. This black background is in the top right, top left, bottom right and bottom left of the image. Following is my image:

The useful part of the image is the circular thing in the center, and I want to draw a histogram for this useful part of the image. How can I remove the said background and plot the histogram?

Following is my code of what I have done so far.

from PIL import Image
import matplotlib.pyplot as plt
from matplotlib.pyplot import bar
import numpy as np

im_gray = Image.open('image.png').convert('L')
im_arr = np.array( im_gray )
im_flat = im_arr.ravel()

mark_bkg = np.where( im_flat != im_arr[0,0]  )[0]
im_no_bkg = im_flat[ mark_bkg ]

hist, bin_edges = np.histogram(im_no_bkg, bins=30, density=False)

plt.figure(1)
bar( x=bin_edges[:-1], height=hist, width=1.0, bottom=None, align='center', data=None )
plt.show()

Body:
Incase you store the image as grayscale [0-255].

To hide the black 255 background, apply a mask() on the image.

# Removing black background
img = np.array([...])
img = np.ma.masked_equal(img, 255)

# Plotting histogram
plt.hist(img.ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
plt.show()

Plotting