问:
'latLng' is not exported by 'node_modules/leaflet/dist/leaflet-src.js' Rollup build fails on leaflet
I'm using angular-seed by Minko.Also using @asymmetrik/angular2-leaflet.The normal production build works well.When running npm run build.prod.rollup.aot it fails with error.

```<code>dist/tmp/app/home/demo/leaflet-d3/ping/ping-demo.component.js (23:21) 'tile
Layer' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
dist/tmp/app/home/demo/leaflet-d3/ping/ping-demo.component.js (41:22) 'latL
ng' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
dist/tmp/app/home/demo/leaflet-d3/ping/ping-demo.component.js (68:31) 'circ
le' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
node_modules/@asymmetrik/angular2-leaflet/dist/leaflet/core/leaflet.directive.js (6:32)
'latLng' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
node_modules/@asymmetrik/angular2-leaflet/dist/leaflet/core/leaflet.directive.js (20:21)
 'map' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
node_modules/@asymmetrik/angular2-leaflet/dist/leaflet/layers/control/leaflet-control-la
yers.wrapper.js (13:31) 'control' is not exported by 'node_modules/leaflet/dist/leaflet-
src.js'
</code>```

project.config.ts
Rollup named import

```<code>this.ROLLUP_NAMED_EXPORTS = [
      ...this.ROLLUP_NAMED_EXPORTS,
      {'node_modules/leaflet/dist/leaflet.js': [  'leaflet' ]},

    ];
</code>```

Additional packages

```<code>let additionalPackages: ExtendPackages[] = [
      {
        name: 'leaflet',
        path: 'node_modules/leaflet/dist/leaflet.js'
      },
      {
        name: '@asymmetrik/angular2-leaflet',
        path: 'node_modules/@asymmetrik/angular2-leaflet/dist/bundles/angular2-leaflet.js'
      }
     ];
</code>```

Rollup config (build.bundles.app.rollup.aot.ts)

```<code>import Config from '../../config';
import { writeFile } from 'fs';
import { join } from 'path';

const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const includePaths = require('rollup-plugin-includepaths');
const rollup = require('rollup');

const alias = require('rollup-plugin-alias');

const config = {
  entry: join(Config.TMP_DIR, Config.BOOTSTRAP_FACTORY_PROD_MODULE),
  sourceMap: true,
  treeshake: true,
  moduleName: 'main',
  plugins: [
    includePaths({
      include: {},
      paths: [join(Config.TMP_DIR, 'app')],
      external: [],
      extensions: ['.js', '.json', '.html', '.ts']
    }),
    alias({
            jszip: join(__dirname, '../../../node_modules/jszip/dist/jszip.min.js')
        }),
    nodeResolve({
      jsnext: true, main: true, module: true
    }),
    commonjs({ //See project.config.ts to extend
      include: Config.ROLLUP_INCLUDE_DIR,
      namedExports: Config.getRollupNamedExports()
    })
  ]
};
export = (done: any) => {
  rollup.rollup(config)
    .then((bundle: any) => {
      const result = bundle.generate({
        format: 'iife'
      });
      const path = join(Config.TMP_DIR, 'bundle.js');
      writeFile(path, result.code, (error: any) => {
        if (error) {
          console.error(error);
          process.exit(0);
        }
        done();
      });
    })
    .catch((error: any) => {
      console.error(error);
      process.exit(0);
    });
};
</code>```

答:
The problem was with the rollup build.When I run npm run build.prod.rollup.aot those above errors began to appear.But I fixed the issue.The problem was with named exports. leaflet-src.js was not exporting the required modules.So i added the missing things named exports in project.config.ts.

```<code>this.ROLLUP_NAMED_EXPORTS = [
      ...this.ROLLUP_NAMED_EXPORTS,
      {'node_modules/leaflet/dist/leaflet.js': [  'leaflet' ]},
      {'node_modules/leaflet/dist/leaflet-src.js': [  'latLng', 'map','control' ]},

    ];
</code>```

Now its working as expected.

Body:
I'm using angular-seed by Minko.Also using @asymmetrik/angular2-leaflet.The normal production build works well.When running npm run build.prod.rollup.aot it fails with error.

dist/tmp/app/home/demo/leaflet-d3/ping/ping-demo.component.js (23:21) 'tile
Layer' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
dist/tmp/app/home/demo/leaflet-d3/ping/ping-demo.component.js (41:22) 'latL
ng' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
dist/tmp/app/home/demo/leaflet-d3/ping/ping-demo.component.js (68:31) 'circ
le' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
node_modules/@asymmetrik/angular2-leaflet/dist/leaflet/core/leaflet.directive.js (6:32)
'latLng' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
node_modules/@asymmetrik/angular2-leaflet/dist/leaflet/core/leaflet.directive.js (20:21)
 'map' is not exported by 'node_modules/leaflet/dist/leaflet-src.js'
node_modules/@asymmetrik/angular2-leaflet/dist/leaflet/layers/control/leaflet-control-la
yers.wrapper.js (13:31) 'control' is not exported by 'node_modules/leaflet/dist/leaflet-
src.js'

project.config.ts
Rollup named import

this.ROLLUP_NAMED_EXPORTS = [
      ...this.ROLLUP_NAMED_EXPORTS,
      {'node_modules/leaflet/dist/leaflet.js': [  'leaflet' ]},

    ];

Additional packages

let additionalPackages: ExtendPackages[] = [
      {
        name: 'leaflet',
        path: 'node_modules/leaflet/dist/leaflet.js'
      },
      {
        name: '@asymmetrik/angular2-leaflet',
        path: 'node_modules/@asymmetrik/angular2-leaflet/dist/bundles/angular2-leaflet.js'
      }
     ];

Rollup config (build.bundles.app.rollup.aot.ts)

import Config from '../../config';
import { writeFile } from 'fs';
import { join } from 'path';

const nodeResolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const includePaths = require('rollup-plugin-includepaths');
const rollup = require('rollup');

const alias = require('rollup-plugin-alias');

const config = {
  entry: join(Config.TMP_DIR, Config.BOOTSTRAP_FACTORY_PROD_MODULE),
  sourceMap: true,
  treeshake: true,
  moduleName: 'main',
  plugins: [
    includePaths({
      include: {},
      paths: [join(Config.TMP_DIR, 'app')],
      external: [],
      extensions: ['.js', '.json', '.html', '.ts']
    }),
    alias({
            jszip: join(__dirname, '../../../node_modules/jszip/dist/jszip.min.js')
        }),
    nodeResolve({
      jsnext: true, main: true, module: true
    }),
    commonjs({ //See project.config.ts to extend
      include: Config.ROLLUP_INCLUDE_DIR,
      namedExports: Config.getRollupNamedExports()
    })
  ]
};
export = (done: any) => {
  rollup.rollup(config)
    .then((bundle: any) => {
      const result = bundle.generate({
        format: 'iife'
      });
      const path = join(Config.TMP_DIR, 'bundle.js');
      writeFile(path, result.code, (error: any) => {
        if (error) {
          console.error(error);
          process.exit(0);
        }
        done();
      });
    })
    .catch((error: any) => {
      console.error(error);
      process.exit(0);
    });
};

Body:
The problem was with the rollup build.When I run npm run build.prod.rollup.aot those above errors began to appear.But I fixed the issue.The problem was with named exports. leaflet-src.js was not exporting the required modules.So i added the missing things named exports in project.config.ts.

this.ROLLUP_NAMED_EXPORTS = [
      ...this.ROLLUP_NAMED_EXPORTS,
      {'node_modules/leaflet/dist/leaflet.js': [  'leaflet' ]},
      {'node_modules/leaflet/dist/leaflet-src.js': [  'latLng', 'map','control' ]},

    ];

Now its working as expected.


来源: stackexchange

问:
Running javascript on Khan academy page

I'm working through The Algorithms section of Khan Academy. I'm  working on the challenge at https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/p/challenge-binary-search

How do I run the program, after I write it?

答: It runs automatically. Try removing the println line of code and you will see the black box that is outputting the result disappears.

ContentLicense: CC BY-SA 3.0

Title: Running javascript on Khan academy page


问:
Update variables in Realm
This is my class:

```<code>class realmTickets: Object {
    dynamic var TicketPrices = 0
}

class realmXP: Object {
    dynamic var XP = 0
}

class dataReference: Object {
    var dataRefVersion = 0.0
    var xpTable = List<realmXP>()
    var ticketPricesTable = List<realmTickets>()
}
</code>```

How do I update dataRefVersion?

I tried:

```<code>  currentDataReference.dataRefVersion = newestDataRef
  try! self.realm.write {
  self.realm.add(currentDataReference, update: true)
  currentDataReference.dataRefVersion = newestDataRef
 }
</code>```

Where newestDataRef is 1.0

This is how currentDataReference is made:

```<code>let dataRef = self.realm.objects(dataReference)
currentDataReference = dataRef.first!
</code>```

There is only 1 object in realm.objects.

When reloading the object, it is always set to 0.0

答:
Properties of built-in types (strings, integers, etc.) must be declared with the dynamic modifier to make it possible for Realm Swift to provide getters that retrieve values from the underlying Realm file. Without the dynamic modifier, the Swift compiler generates access to the underlying instance variable, which does not contain any data for objects loaded from a Realm file.

In addition, your two List<T> properties should really be declared with let. See Why does Realm suggest that List<T> properties be declared using "let"? for an explanation.

Title: Update variables in Realm

Body:
This is my class:

class realmTickets: Object {
    dynamic var TicketPrices = 0
}

class realmXP: Object {
    dynamic var XP = 0
}

class dataReference: Object {
    var dataRefVersion = 0.0
    var xpTable = List<realmXP>()
    var ticketPricesTable = List<realmTickets>()
}

How do I update dataRefVersion?

I tried:

  currentDataReference.dataRefVersion = newestDataRef
  try! self.realm.write {
  self.realm.add(currentDataReference, update: true)
  currentDataReference.dataRefVersion = newestDataRef
 }

Where newestDataRef is 1.0

This is how currentDataReference is made:

let dataRef = self.realm.objects(dataReference)
currentDataReference = dataRef.first!

There is only 1 object in realm.objects.

When reloading the object, it is always set to 0.0


问:
Give keycode 2 different functions
I am using code to make the spacebar do something for an HTML 5 game. It works great, but the page that displays the game also has a Search Box, and visitors will not be able to use the spacebar properly in the Search Box on that page.

Below is the the code I am using for the spacebar on the game's page.

The Search Box is input type search, so I was wondering if a function could be make for :search, to revert the spacebar to work correctly inside the Search Box.

```<code>var hit = document.getElementById("hit");

document.onkeydown = function(e)
{
    if (e.keyCode == 32)
    {
        e.preventDefault();
        hit.click();
    }
};
</code>```

thanks

答:
There are many ways you could do this, here's one:</p>

```<code>var hit = document.getElementById("hit");

document.onkeydown = function(e) {
  if (e.keyCode == 32) {
    if (e.currentTarget.type === 'input') { //Or whatever check you want here
      // Do things for your searchBox
      return; //Prevent rest of the function from running
    }
    e.preventDefault();
    hit.click();
  }
};
</code>```

Title: Give keycode 2 different functions

Body:
I am using code to make the spacebar do something for an HTML 5 game. It works great, but the page that displays the game also has a Search Box, and visitors will not be able to use the spacebar properly in the Search Box on that page.

Below is the the code I am using for the spacebar on the game's page.

The Search Box is input type search, so I was wondering if a function could be make for :search, to revert the spacebar to work correctly inside the Search Box.

var hit = document.getElementById("hit");

document.onkeydown = function(e)
{
    if (e.keyCode == 32)
    {
        e.preventDefault();
        hit.click();
    }
};

thanks

Body:
There are many ways you could do this, here's one:

var hit = document.getElementById("hit");

document.onkeydown = function(e) {
  if (e.keyCode == 32) {
    if (e.currentTarget.type === 'input') { //Or whatever check you want here
      // Do things for your searchBox
      return; //Prevent rest of the function from running
    }
    e.preventDefault();
    hit.click();
  }
};


问:
Regex Match All Except Leading and Trailing Spaces Around Commas (including comma)
I'm trying to match everything except commas and any spaces around them. However, I would like it to match spaces between words. This is what I have so far:

```<code>/[^,\s][a-zA-Z0-9_ !@#$%^&*()]+/gi
</code>```

It's matching everything except commas and trailing spaces, but it's including the leading spaces. Here's the link to test it regex101.

I'm trying to wrap span tags around key terms. This is what I would want the end result to be:

```<code><span>Some text</span>   ,    <span>Some more     text</span>
</code>```

I'm currently using

```<code>.replace(/([^,\s][a-zA-Z0-9_ !@#$%^&*()]+)/gi, "<span>$1</span>")
</code>```

and it updates the span tags in a contenteditable div. I'm using it to place bubbles using CSS around key terms, and are updated after every input. Any help would be greatly appreciated! Thanks!

答:
The regex would be:

```<code>([\s\S]+?)(\s*,\s*|$)
</code>```

then within replace() method back-reference to both capturing groups:

const regex = /([\s\S]+?)(\s*,\s*|$)/g;

const str = `uncased is a test   ,  vertical this is a tests
80000   ,     bertical
80000     ,       vertical
#303 cardio  endo,  kljafklj\$!asdfkj`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, '$1$2');

console.log(result);```

Body:
I'm trying to match everything except commas and any spaces around them. However, I would like it to match spaces between words. This is what I have so far:

/[^,\s][a-zA-Z0-9_ !@#$%^&*()]+/gi

It's matching everything except commas and trailing spaces, but it's including the leading spaces. Here's the link to test it regex101.

I'm trying to wrap span tags around key terms. This is what I would want the end result to be:

Some text   ,    Some more     text

I'm currently using

.replace(/([^,\s][a-zA-Z0-9_ !@#$%^&*()]+)/gi, "$1")

and it updates the span tags in a contenteditable div. I'm using it to place bubbles using CSS around key terms, and are updated after every input. Any help would be greatly appreciated! Thanks!

Body:
The regex would be:

([\s\S]+?)(\s*,\s*|$)

then within replace() method back-reference to both capturing groups:

const regex = /([\s\S]+?)(\s*,\s*|$)/g;

const str = `uncased is a test   ,  vertical this is a tests
80000   ,     bertical
80000     ,       vertical
#303 cardio  endo,  kljafklj\$!asdfkj`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, '<span>$1</span>$2');

console.log(result);


问:
Why are string in .net case sensitive by default?
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

```<code>"John Smith" == "JOHN SMITH"
</code>```

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords

答:
You cannot change the behaviour of existing classes. System.String class which is defined in mscorelib/system.core overrides == and defines a cases sensitive equality.

All you can do is to add an extension method to the string and implement a case-insensitive:

```<code>public static class StringEqualityExtension
{
    public static bool StringEquals(this string value, string other)
    {
       return value.ToLower()==other.ToLower();
    }
}

// usage
string myString = "Some112";
string other = "sOME112";

bool equal = myString.StringEquals(myString);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

"John Smith" == "JOHN SMITH"

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords

Body:
You cannot change the behaviour of existing classes. System.String class which is defined in mscorelib/system.core overrides == and defines a cases sensitive equality.

All you can do is to add an extension method to the string and implement a case-insensitive:

public static class StringEqualityExtension
{
    public static bool StringEquals(this string value, string other)
    {
       return value.ToLower()==other.ToLower();
    }
}

// usage
string myString = "Some112";
string other = "sOME112";

bool equal = myString.StringEquals(myString);


问:
Javascript - Better Alternate to Recursive call
I have this following problem.
I need to calculate a number x based on time t, x would be represented as M(t).
We have the following

M(0) = 1

M(1) = 1

M(2) = 2

M(2t) = M(t) + M(t + 1) + t (for t > 1)

M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)

With that being said the first thing i had in mind to implement this is by using recursion

```<code>function CalculateForTime(t) {
    if (t == 0 || t == 1) {
        return 1;
    }
    else if (t == 2) {
        return 2;
    }
    else if (t % 2 == 0) {
        t = t / 2;
        return CalculateForTime(t) + CalculateForTime(t + 1) + t;
    }
    else {
        t = (t - 1) / 2;
        return CalculateForTime(t - 1) + CalculateForTime(t) + 1;
    }
}
</code>```

This works however it breaks when running on a large number t for example 1^20

I tried looking into tail call recursion or substituting the recursion approach to an iteration approach but couldn't really figure it out.

If tail recursion or iteration is the way to go then please I need help on converting this. If not then I'm open to different methods on making this more optimized.

Thank you,
Omar.

答:
You could store the values in an array,then theres no need to recalc...

var times=[1,1,2];
function CalculateForTime(t) {
    t = Math.floor(t / 2);
        return times[t]||(times[t]=CalculateForTime(t) + CalculateForTime(t + 1) + t);
}

console.log(
CalculateForTime(100),
CalculateForTime(1000),
CalculateForTime(10000),
);
console.log(times.slice(0,100));```

Body:
I have this following problem.
I need to calculate a number x based on time t, x would be represented as M(t).
We have the following

M(0) = 1

M(1) = 1

M(2) = 2

M(2t) = M(t) + M(t + 1) + t (for t > 1)

M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)

With that being said the first thing i had in mind to implement this is by using recursion

function CalculateForTime(t) {
    if (t == 0 || t == 1) {
        return 1;
    }
    else if (t == 2) {
        return 2;
    }
    else if (t % 2 == 0) {
        t = t / 2;
        return CalculateForTime(t) + CalculateForTime(t + 1) + t;
    }
    else {
        t = (t - 1) / 2;
        return CalculateForTime(t - 1) + CalculateForTime(t) + 1;
    }
}

This works however it breaks when running on a large number t for example 1^20

I tried looking into tail call recursion or substituting the recursion approach to an iteration approach but couldn't really figure it out.

If tail recursion or iteration is the way to go then please I need help on converting this. If not then I'm open to different methods on making this more optimized.

Thank you,
Omar.


问:
How to transfer en bloc all the cells of a Jupyter Notebook?
So I found this great visualization of Newton's unconstrained optimization on a Jupyter Notebook within Louis Tiao's public account, and I want to run it on my laptop.

With other platforms, I'd be able to just copy and paste (including the annotations), and get it ready to "play". But with Notebook, I have to deal with multiple cells, and copy and paste each one separately, and in order.

Is there a more expeditious way of transferring the code?

答:
A jupyter notebook is stored in a file with a .ipynb extension.  The internals of the file a specially formatted text called json (or similar to it).

Right click the link and save as name.ipynb (it defaults to this in windows on chrome) and choose a location to save it.  The best location is one where you have all your notebooks by default.

Then run jupyter and open the file.


问:
How to set up the root servlet in Tomcat 6?
Sorry for beginner's questions but I wonder how can I set the root servlet in Tomcat 6?
For example I want to access my servlet on

localhost:8080, not on

```<code>localhost:8080/myservlet
</code>```

Thanks!

答:
This is an old thread, but Jigar Joshi's answer wasn't working for me on Tomcat 8.0 and Servlet 3.1. So I used the following mapping in web.xml.

```<code><servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern></url-pattern>
</servlet-mapping>
</code>```

In section 12.2, Servlet 3.0 specification states that:

The empty string ("") is a special UR L pattern that exactly maps to
  the  application's context root, i.e., requests  of the form
  http://host:port//. In this case the path info is  ’ /
  ’  and the servlet path and context path is  empty string (““).

Body:
Sorry for beginner's questions but I wonder how can I set the root servlet in Tomcat 6?
For example I want to access my servlet on

localhost:8080, not on

localhost:8080/myservlet

Thanks!

Body:
This is an old thread, but Jigar Joshi's answer wasn't working for me on Tomcat 8.0 and Servlet 3.1. So I used the following mapping in web.xml.

<servlet-mapping>
    <servlet-name>myServlet</servlet-name>
    <url-pattern></url-pattern>
</servlet-mapping>

In section 12.2, Servlet 3.0 specification states that:

The empty string ("") is a special UR L pattern that exactly maps to
  the  application's context root, i.e., requests  of the form
  http://host:port//. In this case the path info is  ’ /
  ’  and the servlet path and context path is  empty string (““).


问:
Mediaelement in Windows 8 Metro App
I have a scenario specific to my app. I am managing music file playlist in XML for my metro app. And its saving music files actual path like this

D:\MyMedia\1.mp3

I have media element in my XAML page and I am setting its Source like this.

```<code> mediaElement.Source = new Uri(@"D:\MyMedia\1.mp3", UriKind.Absolute);
 mediaElement.Play();
</code>```

but its not playing the media and its giving the error like this

```<code>MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED : HRESULT - 0x80070005
</code>```

So someone tell me how I can play some media file in MediaElement of metro app with absoulte path. Or how I can get stream of my local file to play this media in my mediaElement of Metro app.

答:
I know it's an old problem, I found a really simple solution..</p>

```<code>Windows.Storage.StorageFile file = null;
mediaElement player = new MediaElement();

    async Task PlayAsync()
    {
        if (file == null)
        {
            file = await OpenFileAsync();

            try { player.MediaOpened -= Player_MediaOpenedAsync; } catch { }
            try { player.MediaEnded -= Player_MediaEnded; } catch { }
            try { player.MediaFailed -= Player_MediaFailed; } catch { }

            player.MediaOpened += Player_MediaOpenedAsync;
            player.MediaEnded += Player_MediaEnded;
            player.MediaFailed += Player_MediaFailed;

            player.SetPlaybackSource(MediaSource.CreateFromStorageFile(file)); //Works with media playback..
            //player.Source = new Uri(mediasource, UriKind.RelativeOrAbsolute); //Doesn't work with media playback for some reason..
            Playing = true;
            Paused = false;
        }
        else
        {
            if (Paused)
            {
                player.Play();
                Paused = false;
            }
            else
            {
                player.Pause();
                Paused = true;
            }
        }
    }

    async Task<StorageFile> OpenFileAsync()
    {
        try
        {
            var ofd = new FileOpenPicker();
            ofd.FileTypeFilter.Add("*");
            return await ofd.PickSingleFileAsync();
        }
        catch { }
        return null;
    }
</code>```

Title: Mediaelement in Windows 8 Metro App

Body:
I have a scenario specific to my app. I am managing music file playlist in XML for my metro app. And its saving music files actual path like this

D:\MyMedia\1.mp3

I have media element in my XAML page and I am setting its Source like this.

 mediaElement.Source = new Uri(@"D:\MyMedia\1.mp3", UriKind.Absolute);
 mediaElement.Play();

but its not playing the media and its giving the error like this

MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED : HRESULT - 0x80070005

So someone tell me how I can play some media file in MediaElement of metro app with absoulte path. Or how I can get stream of my local file to play this media in my mediaElement of Metro app.

Body:
I know it's an old problem, I found a really simple solution..

Windows.Storage.StorageFile file = null;
mediaElement player = new MediaElement();

    async Task PlayAsync()
    {
        if (file == null)
        {
            file = await OpenFileAsync();

            try { player.MediaOpened -= Player_MediaOpenedAsync; } catch { }
            try { player.MediaEnded -= Player_MediaEnded; } catch { }
            try { player.MediaFailed -= Player_MediaFailed; } catch { }

            player.MediaOpened += Player_MediaOpenedAsync;
            player.MediaEnded += Player_MediaEnded;
            player.MediaFailed += Player_MediaFailed;

            player.SetPlaybackSource(MediaSource.CreateFromStorageFile(file)); //Works with media playback..
            //player.Source = new Uri(mediasource, UriKind.RelativeOrAbsolute); //Doesn't work with media playback for some reason..
            Playing = true;
            Paused = false;
        }
        else
        {
            if (Paused)
            {
                player.Play();
                Paused = false;
            }
            else
            {
                player.Pause();
                Paused = true;
            }
        }
    }

    async Task<StorageFile> OpenFileAsync()
    {
        try
        {
            var ofd = new FileOpenPicker();
            ofd.FileTypeFilter.Add("*");
            return await ofd.PickSingleFileAsync();
        }
        catch { }
        return null;
    }


答:
You could use a hash table, because for an array it would generate holes with no value.

function calculateForTime(t) {
    var k = t;
    if (k in lookup) {
        return lookup[k];
    }
    if (t == 0 || t == 1) {
        return lookup[k] = 1;
    }
    if (t == 2) {
        return lookup[k] = 2;
    }
    if (t % 2 == 0) {
        t = t / 2;
        return lookup[k] = calculateForTime(t) + calculateForTime(t + 1) + t;
    }
    t = (t - 1) / 2;
    return lookup[k] = calculateForTime(t - 1) + calculateForTime(t) + 1;
}

var lookup = {};
console.log(calculateForTime(1e10));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Javascript - Better Alternate to Recursive call

Body:
You could use a hash table, because for an array it would generate holes with no value.

function calculateForTime(t) {
    var k = t;
    if (k in lookup) {
        return lookup[k];
    }
    if (t == 0 || t == 1) {
        return lookup[k] = 1;
    }
    if (t == 2) {
        return lookup[k] = 2;
    }
    if (t % 2 == 0) {
        t = t / 2;
        return lookup[k] = calculateForTime(t) + calculateForTime(t + 1) + t;
    }
    t = (t - 1) / 2;
    return lookup[k] = calculateForTime(t - 1) + calculateForTime(t) + 1;
}

var lookup = {};
console.log(calculateForTime(1e10));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to determine whether a file has been closed
I'm writing a unit test, and I'm trying to find a way to test whether my class has properly closed a file handle (it uses old-style open() and close()). Ideally I'd like to be able to do it without having access to the actual handle - I want to be able to check a file in the file system and determine whether it is currently open elsewhere.

I've tried doing it through exclusive file locks, but I haven't had much luck. Besides, file locks are very much not cross-platform (this needs to work on Solaris, Linux and Windows).

Any suggestions?

答: If you want to know if a given file in a filesystem is open by some process on the machine, there's a useful tool called lsof which can tell you this for a variety of unix and unix-like systems.</p>


答:
Inside the above function you must check if the cursor is in your search box, and if it is then skip the rest of the function

Have rewritten your code as below, hope it helps

```<code>var hit = document.getElementById("hit");
document.onkeydown = function(e)
{

if (document.activeElement.nodeName != 'TEXTAREA' && document.activeElement.nodeName != 'INPUT') {

    if (e.keyCode == 32)
    {
        e.preventDefault();
        hit.click();
    }
}
};
</code>```

Cheers mate!

Title: Give keycode 2 different functions

Body:
Inside the above function you must check if the cursor is in your search box, and if it is then skip the rest of the function

Have rewritten your code as below, hope it helps

var hit = document.getElementById("hit");
document.onkeydown = function(e)
{

if (document.activeElement.nodeName != 'TEXTAREA' && document.activeElement.nodeName != 'INPUT') {

    if (e.keyCode == 32)
    {
        e.preventDefault();
        hit.click();
    }
}
};

Cheers mate!


问:
Handling firebase real time changes in progressive web app
I'm fetching the top news from hacker news API which is using firebase. I'm planning to build a progressive web app hence, I'm planning to cache the results into the localstorage.

The current code is here, which fetch and render the top stories. The code is here:

```<code>var ref = new Firebase("http://hacker-news.firebaseio.com/v0/");
var itemRef = ref.child('item');

var topStories = [];

var storyCallback = function(snapshot) {
    var story = snapshot.val();
    var html = '';

    if(story.score) {
        html = '<i>'+story.score+'</i> <a href="'+story.url+'" id="article_a">'+story.title+'</a>'
    }

    document.getElementById(topStories.indexOf(story.id)).innerHTML = html;
}

ref.child('topstories').once('value', function(snapshot) {
    topStories = snapshot.val();

    for(var i = 0; i < topStories.length; i++) {
        var element = document.createElement("P");
        element.id = i;
        document.getElementById('items').appendChild(element);

        itemRef.child(topStories[i]).on('value', storyCallback);
    }
});

ref.child('topstories').on('child_changed', function(snapshot, prevChildName) {
    var ref = snapshot.ref()
    var index = ref.name();

    var oldItemId = topStories[index];
    itemRef.child(oldItemId).off();

    var newItemId = snapshot.val();

    topStories[index] = newItemId
    itemRef.child(newItemId).on('value', storyCallback);
});
</code>```

If I add each stories into the localstorage (by tweaking the above code), how can I skip fetching it from firebase the next time (if it already presents and doesn't changed)?

Note that doesn't change part is important because I can easily get from local storage using the key, how ever it should be in sync with firebase as well. So wondering whether firebase has some way to handle this

答:
If I'm not missing any point you can simply check whether they already exists in local storage or not

```<code>if(localStorage.getItem('key')){
 //display here
 }else{

//fetch
//save for next time
localStorage.setItem('key', JSON.stringify('yourdata'));
 //and display here
}
</code>```

Also you can generalize your function for fetching, display or rendering so you can call at multiple place.

Body:
I'm fetching the top news from hacker news API which is using firebase. I'm planning to build a progressive web app hence, I'm planning to cache the results into the localstorage.

The current code is here, which fetch and render the top stories. The code is here:

var ref = new Firebase("http://hacker-news.firebaseio.com/v0/");
var itemRef = ref.child('item');

var topStories = [];

var storyCallback = function(snapshot) {
    var story = snapshot.val();
    var html = '';

    if(story.score) {
        html = ''+story.score+' '+story.title+''
    }

    document.getElementById(topStories.indexOf(story.id)).innerHTML = html;
}

ref.child('topstories').once('value', function(snapshot) {
    topStories = snapshot.val();

    for(var i = 0; i < topStories.length; i++) {
        var element = document.createElement("P");
        element.id = i;
        document.getElementById('items').appendChild(element);

        itemRef.child(topStories[i]).on('value', storyCallback);
    }
});

ref.child('topstories').on('child_changed', function(snapshot, prevChildName) {
    var ref = snapshot.ref()
    var index = ref.name();

    var oldItemId = topStories[index];
    itemRef.child(oldItemId).off();

    var newItemId = snapshot.val();

    topStories[index] = newItemId
    itemRef.child(newItemId).on('value', storyCallback);
});

If I add each stories into the localstorage (by tweaking the above code), how can I skip fetching it from firebase the next time (if it already presents and doesn't changed)?

Note that doesn't change part is important because I can easily get from local storage using the key, how ever it should be in sync with firebase as well. So wondering whether firebase has some way to handle this

Body:
If I'm not missing any point you can simply check whether they already exists in local storage or not

if(localStorage.getItem('key')){
 //display here
 }else{

//fetch
//save for next time
localStorage.setItem('key', JSON.stringify('yourdata'));
 //and display here
}

Also you can generalize your function for fetching, display or rendering so you can call at multiple place.


问:
How does the linker handle identical template instantiations across translation units?
Suppose I have two translation-units:

foo.cpp

```<code>void foo() {
  auto v = std::vector<int>();
}
</code>```

bar.cpp

```<code>void bar() {
  auto v = std::vector<int>();
}
</code>```

When I compile these translation-units, each will instantiate std::vector<int>.

My question is: how does this work at the linking stage?

Do both instantiations have different mangled names?

Does the linker remove them as duplicates?

答:
Different implementations use different strategies for this.

The GNU compiler, for example, marks template instantiations as weak symbols. Then at link time, the linker can throw away all definitions but one of the same weak symbol.

The Sun Solaris compiler, on the other hand, does not instantiate templates at all during normal compilation. Then at link time, the linker collects all template instantiations needed to complete the program, and then goes ahead and calls the compiler in a special template-instantiation mode. Thus exactly one instantiation is produced for each template. There are no duplicates to merge or get rid of.

Each approach has its own advantages and disadvantages.

Body:
Suppose I have two translation-units:

foo.cpp

void foo() {
  auto v = std::vector<int>();
}

bar.cpp

void bar() {
  auto v = std::vector<int>();
}

When I compile these translation-units, each will instantiate std::vector<int>.

My question is: how does this work at the linking stage?

Do both instantiations have different mangled names?

Does the linker remove them as duplicates?


问:
Swift, MKPolyline how to create polyline between coordinate point
Hi I wrote this code to draw a polyline between some point:

```<code>var arrayToDraw: Array<Any> = []
var forpolyline: Array<CLLocationDegrees> = []
var forpolyline2: CLLocationCoordinate2D = CLLocationCoordinate2D.init()

func showRoute() {
    for h in 0...(orderFinalDictionary.count - 1){
        arrayToDraw = orderFinalDictionary[h].value
        print(arrayToDraw)
        var arrayToDrawCount = arrayToDraw.count
        for n in 0...(arrayToDrawCount - 1){
            forpolyline = (arrayToDraw[n] as! Array<CLLocationDegrees>)
            forpolyline2.latitude = (forpolyline[0])
            forpolyline2.longitude = (forpolyline[1])
            print(forpolyline2)
                var geodesic = MKPolyline(coordinates: &forpolyline2, count: 1)
                self.mapView.add(geodesic)
        }
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.red
    renderer.lineWidth = 3

    return renderer
}
</code>```

It takes coordinates from a Dictionary, put it in a array(arraToDraw) and I use forpolyline and forpolyline2 to cast values.

Now the problem is that it only draw dots on the coordinates how can I connect that?

答:
You're creating multiple polylines with a single point, instead of a single polyline with multiple points. It's hard to get the code right without knowing your dictionary structure, but this should be more in line with what you're trying to do:</p>

```<code>var arrayToDraw: Array<Any> = []
var forpolyline: Array<CLLocationDegrees> = []
var forpolyline2: CLLocationCoordinate2D = [CLLocationCoordinate2D]()

func showRoute() {
    for h in 0...(orderFinalDictionary.count - 1){
        arrayToDraw = orderFinalDictionary[h].value
        print(arrayToDraw)
        var arrayToDrawCount = arrayToDraw.count
        for n in 0...(arrayToDrawCount - 1){
            forpolyline = (arrayToDraw[n] as! Array<CLLocationDegrees>)
            forpolyline2.append(CLLocationCoordinate2D(latitude: forpolyline[0], longitude: forpolyline[1]))
        }
        print(forpolyline2)
        let geodesic = MKPolyline(coordinates: &forpolyline2, count: forpolyline2.count)
        self.mapView.add(geodesic)
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.red
    renderer.lineWidth = 3

    return renderer
}
</code>```

Body:
Hi I wrote this code to draw a polyline between some point:

var arrayToDraw: Array<Any> = []
var forpolyline: Array<CLLocationDegrees> = []
var forpolyline2: CLLocationCoordinate2D = CLLocationCoordinate2D.init()

func showRoute() {
    for h in 0...(orderFinalDictionary.count - 1){
        arrayToDraw = orderFinalDictionary[h].value
        print(arrayToDraw)
        var arrayToDrawCount = arrayToDraw.count
        for n in 0...(arrayToDrawCount - 1){
            forpolyline = (arrayToDraw[n] as! Array<CLLocationDegrees>)
            forpolyline2.latitude = (forpolyline[0])
            forpolyline2.longitude = (forpolyline[1])
            print(forpolyline2)
                var geodesic = MKPolyline(coordinates: &forpolyline2, count: 1)
                self.mapView.add(geodesic)
        }
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.red
    renderer.lineWidth = 3

    return renderer
}

It takes coordinates from a Dictionary, put it in a array(arraToDraw) and I use forpolyline and forpolyline2 to cast values.

Now the problem is that it only draw dots on the coordinates how can I connect that?

Body:
You're creating multiple polylines with a single point, instead of a single polyline with multiple points. It's hard to get the code right without knowing your dictionary structure, but this should be more in line with what you're trying to do:

var arrayToDraw: Array<Any> = []
var forpolyline: Array<CLLocationDegrees> = []
var forpolyline2: CLLocationCoordinate2D = [CLLocationCoordinate2D]()

func showRoute() {
    for h in 0...(orderFinalDictionary.count - 1){
        arrayToDraw = orderFinalDictionary[h].value
        print(arrayToDraw)
        var arrayToDrawCount = arrayToDraw.count
        for n in 0...(arrayToDrawCount - 1){
            forpolyline = (arrayToDraw[n] as! Array<CLLocationDegrees>)
            forpolyline2.append(CLLocationCoordinate2D(latitude: forpolyline[0], longitude: forpolyline[1]))
        }
        print(forpolyline2)
        let geodesic = MKPolyline(coordinates: &forpolyline2, count: forpolyline2.count)
        self.mapView.add(geodesic)
    }
}

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
    renderer.strokeColor = UIColor.red
    renderer.lineWidth = 3

    return renderer
}


问:
simpleXml to array behaviour looks strange to me and - breaks at 9941 items
EDIT3: It seems that the problem occurs on my localhost XAMPP PHP 5.3 setup, not on any of the remote servers running php 5.2 that I've tested. Still unclear if its php or xampp (or maybe the combination) that causes the error /EDIT3

I have an xml with about 12000 names to add to an array.
The xml structure looks like this:

```<code><smdusersync datetime="2010-12-13 13:51:16">
  <userstoadd>
    <User fnamn="Adam" enamn="Svensson" email="adam@darkeye.se" password="3906" />
    <User fnamn="Brooke" enamn="Jarnbjer" email="brooke@gmail.com" password="2729" />
    <User fnamn="Caesar" enamn="Carlsson" email="caesar@comhem.se" password="1668" />
   <!-- about 12000 other users -->
  </userstoadd>
  <userstoremove>
  </userstoremove>
</smdusersync>
</code>```

EDIT2: I've tried with other xml examples, including programmatically generated with no attbutes etc, and that doesn't matter - still the same problem described below... /EDIT2

When running a simple foreach loop on the xml userstoadd child, strange things start to
happen when I push objects to an array.

(Please note that the example below has the code that causes the error - it's not a useful example in any way...)

Running a simple foreach loop (here just pushing a testcounter to the array) works as expected:

```<code>    $user_xml = simplexml_load_file('users.xml');
    $xml_count = $user_xml->userstoadd->children()->count();
    $users_arr = array();
    $test_count = 0;
    foreach ($user_xml->userstoadd->children() as $user) {

        array_push($users_arr, $test_count); // << Works as expected!
        $test_count++;
    }
    echo $xml_count, '/', $test_count;
</code>```

The $xml_count and $test_count always have the same value.

When I do the same, except for that I push a simple object to the array, everything works fine if the number of xml users <= 9940:

```<code>    $user_xml = simplexml_load_file('users.xml');
    $xml_count = $user_xml->userstoadd->children()->count();
    $users_arr = array();
    $test_count = 0;
    foreach ($user_xml->userstoadd->children() as $user) {
        $dummy_object = new StdClass();  // << Empty dummy object
        array_push($users_arr, $dummy_object); // << CAUSES ERROR if more than 9940 items...!
        $test_count++;
    }
    echo $xml_count, '/', $test_count; // << SHOULD BE THE SAME!
</code>```

When having 9940 xml user items, the output is as expected 9940/9940.
BUT when having 9941 xml user items, the output is 9941/19881!
And when having 9942 xml user items, the output is 9942/19882!

Suddenly almost 10000 difference! And the content of the user items doesn't seem to matter... I've copied and moved xml user items with the same result...

EDIT: When more than 9940 items, it suddeny doubles so that 9941 items give (9940 x 2) + 1 = 19881.
No difference when using one single xml user item 12000 times. /EDIT

Any idea what's going on here?

答:
The following insanity solves the problem for me:

You might want to comment out the test(50000); line.

```<code><?php

test(9996); // works                         (echoes 9996/9996/9996)
test(9997); // BREAKS on my XAMPP php 5.3.1! (echoes 9997/19993/19993)
test(50000); // test with larger number

function test($items_to_create) {
    $xml_str = '<root>' . chr(13);
    for($i=0; $i<$items_to_create; $i++) {
        $xml_str .= '<item attr="t' . $i . '"/>' . chr(13);
    }
    $xml_str .= '</root>';

    $xml = new SimpleXMLElement($xml_str);

    $xml_children = $xml->children();
    $xml_count = $xml_children->count();
    $arr = array();
    $test_count = 0;

    /*
    foreach ($xml->children() as $user) {
        $dummy_object = new StdClass();
        array_push($arr, $dummy_object);
        $test_count++;
    }
    */

    for ($i=0; $i<$xml_count; $i++) {
        $dummy_object = new StdClass();
        $dummy_object->foo = $xml_children[$i]->attributes()->attr;
        array_push($arr, $dummy_object);
        $test_count++;
    }

    $arr_count = count($arr);
    echo '<br />CTRL+F for me:', $xml_count, '/', $test_count , '/', $arr_count, '<hr />';
    echo '```', print_r($arr, true), '```';
}
?>
</code>```

Does it fix it for you?

Body:
EDIT3: It seems that the problem occurs on my localhost XAMPP PHP 5.3 setup, not on any of the remote servers running php 5.2 that I've tested. Still unclear if its php or xampp (or maybe the combination) that causes the error /EDIT3

I have an xml with about 12000 names to add to an array.
The xml structure looks like this:

<smdusersync datetime="2010-12-13 13:51:16">
  <userstoadd>
    <User fnamn="Adam" enamn="Svensson" email="adam@darkeye.se" password="3906" />
    <User fnamn="Brooke" enamn="Jarnbjer" email="brooke@gmail.com" password="2729" />
    <User fnamn="Caesar" enamn="Carlsson" email="caesar@comhem.se" password="1668" />

  </userstoadd>
  <userstoremove>
  </userstoremove>
</smdusersync>

EDIT2: I've tried with other xml examples, including programmatically generated with no attbutes etc, and that doesn't matter - still the same problem described below... /EDIT2

When running a simple foreach loop on the xml userstoadd child, strange things start to
happen when I push objects to an array.

(Please note that the example below has the code that causes the error - it's not a useful example in any way...)

Running a simple foreach loop (here just pushing a testcounter to the array) works as expected:

    $user_xml = simplexml_load_file('users.xml');
    $xml_count = $user_xml->userstoadd->children()->count();
    $users_arr = array();
    $test_count = 0;
    foreach ($user_xml->userstoadd->children() as $user) {

        array_push($users_arr, $test_count); // << Works as expected!
        $test_count++;
    }
    echo $xml_count, '/', $test_count;

The $xml_count and $test_count always have the same value.

When I do the same, except for that I push a simple object to the array, everything works fine if the number of xml users <= 9940:

    $user_xml = simplexml_load_file('users.xml');
    $xml_count = $user_xml->userstoadd->children()->count();
    $users_arr = array();
    $test_count = 0;
    foreach ($user_xml->userstoadd->children() as $user) {
        $dummy_object = new StdClass();  // << Empty dummy object
        array_push($users_arr, $dummy_object); // << CAUSES ERROR if more than 9940 items...!
        $test_count++;
    }
    echo $xml_count, '/', $test_count; // << SHOULD BE THE SAME!

When having 9940 xml user items, the output is as expected 9940/9940.
BUT when having 9941 xml user items, the output is 9941/19881!
And when having 9942 xml user items, the output is 9942/19882!

Suddenly almost 10000 difference! And the content of the user items doesn't seem to matter... I've copied and moved xml user items with the same result...

EDIT: When more than 9940 items, it suddeny doubles so that 9941 items give (9940 x 2) + 1 = 19881.
No difference when using one single xml user item 12000 times. /EDIT

Any idea what's going on here?

Body:
The following insanity solves the problem for me:

You might want to comment out the test(50000); line.

<?php

test(9996); // works                         (echoes 9996/9996/9996)
test(9997); // BREAKS on my XAMPP php 5.3.1! (echoes 9997/19993/19993)
test(50000); // test with larger number

function test($items_to_create) {
    $xml_str = '<root>' . chr(13);
    for($i=0; $i<$items_to_create; $i++) {
        $xml_str .= '<item attr="t' . $i . '"/>' . chr(13);
    }
    $xml_str .= '</root>';

    $xml = new SimpleXMLElement($xml_str);

    $xml_children = $xml->children();
    $xml_count = $xml_children->count();
    $arr = array();
    $test_count = 0;

    /*
    foreach ($xml->children() as $user) {
        $dummy_object = new StdClass();
        array_push($arr, $dummy_object);
        $test_count++;
    }
    */

    for ($i=0; $i<$xml_count; $i++) {
        $dummy_object = new StdClass();
        $dummy_object->foo = $xml_children[$i]->attributes()->attr;
        array_push($arr, $dummy_object);
        $test_count++;
    }

    $arr_count = count($arr);
    echo '<br />CTRL+F for me:', $xml_count, '/', $test_count , '/', $arr_count, '<hr />';
    echo '<pre>', print_r($arr, true), '</pre>';
}
?>

Does it fix it for you?


答:
You can stop the 'keydown' events from the search bar from propagating upwards by calling event.stopPropagation():

document.addEventListener('keydown', function(e) {
  console.log('hit!');
  e.preventDefault();
});

let search = document.getElementById("search");

search.addEventListener('keydown', function(e) {
  console.log("search!");
  e.stopPropagation();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="search"><input name="query" type="text"><input type="submit" value="search"></form></code>```

Title: Give keycode 2 different functions

Body:
I am using code to make the spacebar do something for an HTML 5 game. It works great, but the page that displays the game also has a Search Box, and visitors will not be able to use the spacebar properly in the Search Box on that page.

Below is the the code I am using for the spacebar on the game's page.

The Search Box is input type search, so I was wondering if a function could be make for :search, to revert the spacebar to work correctly inside the Search Box.

var hit = document.getElementById("hit");

document.onkeydown = function(e)
{
    if (e.keyCode == 32)
    {
        e.preventDefault();
        hit.click();
    }
};

thanks

Body:
You can stop the 'keydown' events from the search bar from propagating upwards by calling event.stopPropagation():

document.addEventListener('keydown', function(e) {
  console.log('hit!');
  e.preventDefault();
});

let search = document.getElementById("search");

search.addEventListener('keydown', function(e) {
  console.log("search!");
  e.stopPropagation();
});

<form id="search"><input name="query" type="text"><input type="submit" value="search"></form>


问:
hosting WordPress on Docker or on Physical host
I am planning to create a shared WordPress hosting system for clients.

The needed services are : PHP, MySQL/MariaDB, SFTP, (Nginx/Apache : which one is better and faster and more secure ? )

If i am going to use Docker then the applications are going to be
mounted on a volume on the Docker host the container will include the
PHP files.

If on a physical CentOS or Ubuntu host then all the websites will
share the same PHP files.

The Nginx/Apache will be one for all the websites, and one database engine to serve them all.

Have anyone done such scenario?
what do you suggest, what are the advantages and disadvantages in both cases.

答: Nginx with Fastcgi is more secure and fast. You can limit max request/ip after the connection will throttled. For database use mariadb. For caching the whole wordpress site use memcached. It will load your whole site in ram and reduce server load. Best for static wordpress site as well as dynamic.</p>


问:
Adding columns in Spark dataframe based on rules
I have a dataframe df, which contains below data:

```<code>**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z
</code>```

i have been provided 2 rules, which are as below:

```<code>**rule_id**   **rule_name**  **product value**  **priority**
   123              ABC             A,B               1
   456              DEF             A,B,D             2
</code>```

Requirement is to apply these rules on dataframe df in priority order, customers who have passed rule 1, should not be considered for rule 2 and in final dataframe add two more columns rule_id and rule_name, i have written below code to achieve it:

```<code>val rule_name = when(col("product").isin("A","B"), "ABC").otherwise(when(col("product").isin("A","B","D"), "DEF").otherwise(""))
val rule_id = when(col("product").isin("A","B"), "123").otherwise(when(col("product").isin("A","B","D"), "456").otherwise(""))
val df1 = df_customers.withColumn("rule_name" , rule_name).withColumn("rule_id" , rule_id)
df1.show()
</code>```

Final output looks like below:

```<code>**customers**   **product**   **Val_id**  **rule_name**  **rule_id**
     1               A            1           ABC            123
     2               B            X           ABC            123
     3               C
     4               D            Z           DEF            456
</code>```

Is there any better way to achieve it, adding both columns by just going though entire dataset once instead of going through entire dataset twice?

答:
Question : Is there any better way to achieve it, adding both columns
  by just going though entire dataset once instead of going through
  entire dataset twice?

Answer : you  can have a Map return type in scala...

Limitation : This udf if you are using with With Column for example
  column name is ruleIDandRuleName then you can use a single fuction
  with Map data type or any acceptable data type of spark sql column.
  Other wise you cant use the below mentioned approach

shown in the below example snippet

```<code>      def ruleNameAndruleId = udf((product : String) => {
 if(Seq("A", "B").contains(product)) Map("ruleName"->"ABC","ruleId"->"123")
    else if(Seq("A", "B", "D").contains(product)) (Map("ruleName"->"DEF","ruleId"->"456")
    else (Map("ruleName"->"","ruleId"->"") })
</code>```

caller will be

```<code>df.withColumn("ruleIDandRuleName",ruleNameAndruleId(product here) ) // ruleNameAndruleId  will return a map containing rulename and rule id
</code>```

Body:
I have a dataframe df, which contains below data:

**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z

i have been provided 2 rules, which are as below:

**rule_id**   **rule_name**  **product value**  **priority**
   123              ABC             A,B               1
   456              DEF             A,B,D             2

Requirement is to apply these rules on dataframe df in priority order, customers who have passed rule 1, should not be considered for rule 2 and in final dataframe add two more columns rule_id and rule_name, i have written below code to achieve it:

val rule_name = when(col("product").isin("A","B"), "ABC").otherwise(when(col("product").isin("A","B","D"), "DEF").otherwise(""))
val rule_id = when(col("product").isin("A","B"), "123").otherwise(when(col("product").isin("A","B","D"), "456").otherwise(""))
val df1 = df_customers.withColumn("rule_name" , rule_name).withColumn("rule_id" , rule_id)
df1.show()

Final output looks like below:

**customers**   **product**   **Val_id**  **rule_name**  **rule_id**
     1               A            1           ABC            123
     2               B            X           ABC            123
     3               C
     4               D            Z           DEF            456

Is there any better way to achieve it, adding both columns by just going though entire dataset once instead of going through entire dataset twice?

Body:
Question : Is there any better way to achieve it, adding both columns
  by just going though entire dataset once instead of going through
  entire dataset twice?

Answer : you  can have a Map return type in scala...

Limitation : This udf if you are using with With Column for example
  column name is ruleIDandRuleName then you can use a single fuction
  with Map data type or any acceptable data type of spark sql column.
  Other wise you cant use the below mentioned approach

shown in the below example snippet

      def ruleNameAndruleId = udf((product : String) => {
 if(Seq("A", "B").contains(product)) Map("ruleName"->"ABC","ruleId"->"123")
    else if(Seq("A", "B", "D").contains(product)) (Map("ruleName"->"DEF","ruleId"->"456")
    else (Map("ruleName"->"","ruleId"->"") })

caller will be

df.withColumn("ruleIDandRuleName",ruleNameAndruleId(product here) ) // ruleNameAndruleId  will return a map containing rulename and rule id


问:
python asyncio add_done_callback with async def
I have 2 functions: The first one, def_a, is an asynchronous function and the second one is def_b which is a regular function and called with the result of def_a as a callback with the add_done_callback function.

My code looks like this:

```<code>import asyncio

def def_b(result):
    next_number = result.result()
    # some work on the next_number
    print(next_number + 1)

async def def_a(number):
    await some_async_work(number)
    return number + 1

loop = asyncio.get_event_loop()
task = asyncio.ensure_future(def_a(1))
task.add_done_callback(def_b)
response = loop.run_until_complete(task)
loop.close()
</code>```

And it's work perfectly.

The problem began when also the second function, def_b, became asynchronous. Now it looks like this:

```<code>async def def_b(result):
    next_number = result.result()
    # some asynchronous work on the next_number
    print(next_number + 1)
</code>```

But now I can not provide it to the add_done_callback function, because it's not a regular function.

My question is- Is it possible and how can I provide def_b to the add_done_callback function if def_b is asynchronous?

答:
add_done_callback is considered a "low level" interface.  When working with coroutines, you can chain them in many ways, for example:

```<code>import asyncio

async def my_callback(result):
    print("my_callback got:", result)
    return "My return value is ignored"

async def coro(number):
    await asyncio.sleep(number)
    return number + 1

async def add_success_callback(fut, callback):
    result = await fut
    await callback(result)
    return result

loop = asyncio.get_event_loop()
task = asyncio.ensure_future(coro(1))
task = add_success_callback(task, my_callback)
response = loop.run_until_complete(task)
print("response:", response)
loop.close()
</code>```

Keep in mind add_done_callback will still call the callback if your future raises an exception (but calling result.result() will raise it).

Body:
I have 2 functions: The first one, def_a, is an asynchronous function and the second one is def_b which is a regular function and called with the result of def_a as a callback with the add_done_callback function.

My code looks like this:

import asyncio

def def_b(result):
    next_number = result.result()
    # some work on the next_number
    print(next_number + 1)

async def def_a(number):
    await some_async_work(number)
    return number + 1

loop = asyncio.get_event_loop()
task = asyncio.ensure_future(def_a(1))
task.add_done_callback(def_b)
response = loop.run_until_complete(task)
loop.close()

And it's work perfectly.

The problem began when also the second function, def_b, became asynchronous. Now it looks like this:

async def def_b(result):
    next_number = result.result()
    # some asynchronous work on the next_number
    print(next_number + 1)

But now I can not provide it to the add_done_callback function, because it's not a regular function.

My question is- Is it possible and how can I provide def_b to the add_done_callback function if def_b is asynchronous?

Body:
add_done_callback is considered a "low level" interface.  When working with coroutines, you can chain them in many ways, for example:

import asyncio

async def my_callback(result):
    print("my_callback got:", result)
    return "My return value is ignored"

async def coro(number):
    await asyncio.sleep(number)
    return number + 1

async def add_success_callback(fut, callback):
    result = await fut
    await callback(result)
    return result

loop = asyncio.get_event_loop()
task = asyncio.ensure_future(coro(1))
task = add_success_callback(task, my_callback)
response = loop.run_until_complete(task)
print("response:", response)
loop.close()

Keep in mind add_done_callback will still call the callback if your future raises an exception (but calling result.result() will raise it).

ContentLicense: CC BY-SA 4.0


问:
Change css background color with php
I'm having a little problem with css.
I have to create a page with a form on which you can set your background-color by means of radio-buttons and a submit button.
But how could I actually change the css background-color in php?</p>

```<code><?php
            if (isset($_POST['set'])) {
                $color = $_POST['color'];
            } else {
                $color = "";
            }
        ?>

        <form method="post" action="">
            <input type="radio" name="color" value="Red"
                <?php if($color == "Red") { echo "checked='checked'"; } ?>>Red
            <input type="radio" name="color" value="Green"
                <?php if($color == "Green") { echo "checked='checked'"; } ?>>Green
            <input type="radio" name="color" value="Blue"
                <?php if ($color == "Blue") { echo "checked='checked'"; } ?>>Blue
            <input type="radio" name="kleur" value="Pink"
                <?php if ($color == "Pink") { echo "checked='checked'"; } ?>>Pink

            <br>
            <br>

            <input type="submit" name="set" value="SET">
        </form>
</code>```

答:
Use style css for body tag

```<code> <?php
                if (isset($_POST['set'])) {
                    $color = $_POST['color'];
                } else {
                    $color = "";
                }
            ?>
         <html>
         <body <?php echo !empty($color) ? 'style="background:'.$color.'"' : ''; ?>>
            <form method="post" action="">
                <input type="radio" name="color" value="Red"
                    <?php if($color == "Red") { echo "checked='checked'"; } ?>>Red
                <input type="radio" name="color" value="Green"
                    <?php if($color == "Green") { echo "checked='checked'"; } ?>>Green
                <input type="radio" name="color" value="Blue"
                    <?php if ($color == "Blue") { echo "checked='checked'"; } ?>>Blue
                <input type="radio" name="kleur" value="Pink"
                    <?php if ($color == "Pink") { echo "checked='checked'"; } ?>>Pink

                <br>
                <br>

                <input type="submit" name="set" value="SET">
            </form>
           </body>
</code>```

Title: Change css background color with php

Body:
I'm having a little problem with css.
I have to create a page with a form on which you can set your background-color by means of radio-buttons and a submit button.
But how could I actually change the css background-color in php?

<?php
            if (isset($_POST['set'])) {
                $color = $_POST['color'];
            } else {
                $color = "";
            }
        ?>

        <form method="post" action="">
            <input type="radio" name="color" value="Red"
                <?php if($color == "Red") { echo "checked='checked'"; } ?>>Red
            <input type="radio" name="color" value="Green"
                <?php if($color == "Green") { echo "checked='checked'"; } ?>>Green
            <input type="radio" name="color" value="Blue"
                <?php if ($color == "Blue") { echo "checked='checked'"; } ?>>Blue
            <input type="radio" name="kleur" value="Pink"
                <?php if ($color == "Pink") { echo "checked='checked'"; } ?>>Pink

            <input type="submit" name="set" value="SET">
        </form>

Body:
Use style css for body tag

 <?php
                if (isset($_POST['set'])) {
                    $color = $_POST['color'];
                } else {
                    $color = "";
                }
            ?>
         <html>
         <body <?php echo !empty($color) ? 'style="background:'.$color.'"' : ''; ?>>
            <form method="post" action="">
                <input type="radio" name="color" value="Red"
                    <?php if($color == "Red") { echo "checked='checked'"; } ?>>Red
                <input type="radio" name="color" value="Green"
                    <?php if($color == "Green") { echo "checked='checked'"; } ?>>Green
                <input type="radio" name="color" value="Blue"
                    <?php if ($color == "Blue") { echo "checked='checked'"; } ?>>Blue
                <input type="radio" name="kleur" value="Pink"
                    <?php if ($color == "Pink") { echo "checked='checked'"; } ?>>Pink

                <br>
                <br>

                <input type="submit" name="set" value="SET">
            </form>
           </body>


问:
Integrate a function that returns a matrix numpy
I want to do something similar to this question.

```<code>Nm, Mm = np.meshgrid(range(3), range(2))
y = lambda x: x*Nm + x*Mm
</code>```

Then, y returns a 3x2 matrix. I want to integrate y from a to b, for instance we can choose a=0 and b=1. This means that the i, j component of the integrated matrix should be int from 0 to 1 of (x * i + x * j) dx. If I take into account one of the answers:

```<code>>>> a = [sin, cos]
>>> vectorize(quad)(a, 0, pi)
</code>```

Clearly a is a list of functions, but what I have is a function that returns an array, which is different. I get:

```<code>res = np.vectorize(integrate.quad)(y, 0, 1)

error: Supplied function does not return a valid float.
</code>```

How can I fix this? Thanks for your help

Edit:

The desired result is

```<code>res = np.empty((3,2))
for i in range(3):
    for j in range(2):
        res[i, j] = quad(lambda x: x*i + x*j, 0, 1)[0]
</code>```

答:
An alternative to passing the i,j via a lambda is to use the args parameter of quad:

```<code>In [39]: def foo(x,i,j):
    ...:     return x*i + x*j
In [40]: i,j=1,2
In [41]: integrate.quad(lambda x: x*i+x*j, 0,1)
Out[41]: (1.5, 1.6653345369377348e-14)
In [42]: integrate.quad(foo, 0, 1, args=(i,j))
Out[42]: (1.5, 1.6653345369377348e-14)
</code>```

This is still evaluating the function separately for each i,j pair.

You may be able to bury the i,j iteration in a np.vectorize function, but that doesn't improve speed.  I advocate it only if you need the broadcasting help.

A similar question comes up periodically.  People want to apply quad (or other scipy functions) for a range of functions or parameters.  But assuming you want to give quad full power over integration steps and such, there isn't a substitute for iteration.

Body:
I want to do something similar to this question.

Nm, Mm = np.meshgrid(range(3), range(2))
y = lambda x: x*Nm + x*Mm

Then, y returns a 3x2 matrix. I want to integrate y from a to b, for instance we can choose a=0 and b=1. This means that the i, j component of the integrated matrix should be int from 0 to 1 of (x * i + x * j) dx. If I take into account one of the answers:

>>> a = [sin, cos]
>>> vectorize(quad)(a, 0, pi)

Clearly a is a list of functions, but what I have is a function that returns an array, which is different. I get:

res = np.vectorize(integrate.quad)(y, 0, 1)

error: Supplied function does not return a valid float.

How can I fix this? Thanks for your help

Edit:

The desired result is

res = np.empty((3,2))
for i in range(3):
    for j in range(2):
        res[i, j] = quad(lambda x: x*i + x*j, 0, 1)[0]

Body:
An alternative to passing the i,j via a lambda is to use the args parameter of quad:

In [39]: def foo(x,i,j):
    ...:     return x*i + x*j
In [40]: i,j=1,2
In [41]: integrate.quad(lambda x: x*i+x*j, 0,1)
Out[41]: (1.5, 1.6653345369377348e-14)
In [42]: integrate.quad(foo, 0, 1, args=(i,j))
Out[42]: (1.5, 1.6653345369377348e-14)

This is still evaluating the function separately for each i,j pair.

You may be able to bury the i,j iteration in a np.vectorize function, but that doesn't improve speed.  I advocate it only if you need the broadcasting help.

A similar question comes up periodically.  People want to apply quad (or other scipy functions) for a range of functions or parameters.  But assuming you want to give quad full power over integration steps and such, there isn't a substitute for iteration.


问:
make dep: Nothing to be done for 'depend'
I have been trying to compile the PJSIP library for an iOS project which needs SIP. Following this tutorial, I have been able to run the configure-iphone script. The next step would to run the make dep for the dependencies, but sadly it fails bcs of some error, unknown to me. I have also tried to edit the makefile, so it points directly to the file, but I still get the error, so it can find the file.

```<code>/Applications/Xcode.app/Contents/Developer/usr/bin/make -f Samples.mak depend
make[2]: Nothing to be done for `depend'.
</code>```

is the error I get.

The make file:

```<code>include ../../build.mak
include $(PJDIR)/build/common.mak

export LIBDIR := ../lib
export BINDIR := ../bin

RULES_MAK := $(PJDIR)/build/rules.mak
SAMPLES_MAK := $(PJDIR)/pjsip-apps/build/Samples.mak

###############################################################################
# Gather all flags.
#
export _CFLAGS  := $(CC_CFLAGS) $(OS_CFLAGS) $(HOST_CFLAGS) $(M_CFLAGS) \
           $(PJ_CFLAGS) $(CFLAGS) $(CC_INC)../../pjsip/include \
           $(CC_INC)../../pjlib/include \
           $(CC_INC)../../pjlib-util/include \
           $(CC_INC)../../pjnath/include \
           $(CC_INC)../../pjmedia/include
export _CXXFLAGS:= $(_CFLAGS) $(CC_CXXFLAGS) $(OS_CXXFLAGS) $(M_CXXFLAGS) \
           $(HOST_CXXFLAGS) $(CXXFLAGS)
export _LDFLAGS := $(CC_LDFLAGS) $(OS_LDFLAGS) $(M_LDFLAGS) $(HOST_LDFLAGS) \
           $(APP_LDFLAGS) $(APP_LDLIBS) $(LDFLAGS)

###############################################################################
# Defines for building PJSUA
#
export PJSUA_SRCDIR = ../src/pjsua
export PJSUA_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            main.o pjsua_app.o pjsua_app_cli.o pjsua_app_common.o \
            pjsua_app_config.o pjsua_app_legacy.o
export PJSUA_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSUA_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSUA_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSUA_EXE:=pjsua-$(TARGET_NAME)$(HOST_EXE)

###############################################################################
# Defines for building pjsystest
#
export PJSYSTEST_SRCDIR = ../src/pjsystest
export PJSYSTEST_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            systest.o main_console.o
export PJSYSTEST_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSYSTEST_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSYSTEST_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSYSTEST_EXE:=pjsystest-$(TARGET_NAME)$(HOST_EXE)

export CC_OUT CC AR RANLIB HOST_MV HOST_RM HOST_RMDIR HOST_MKDIR OBJEXT LD LDOUT

TARGETS := $(PJSUA_EXE) $(PJSYSTEST_EXE) samples

all: $(TARGETS)

swig:
    $(MAKE) -C ../src/swig

doc:

dep: depend
distclean: realclean

.PHONY: all dep depend clean realclean distclean
.PHONY: $(TARGETS)
.PHONY: $(PJSUA_EXE) $(PJSYSTEST_EXE)

pjsua: $(PJSUA_EXE)
$(PJSUA_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(BINDIR)/$@)
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        if test -f $$F; then \
          tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
          ln -sf $$F ../src/pjsua/ios/$$tmp; \
        fi; \
      done; \
    fi;

pjsystest: $(PJSYSTEST_EXE)
$(PJSYSTEST_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $(subst /,$(HOST_PSEP),$(BINDIR)/$@)

samples:
    $(MAKE) -f $(SAMPLES_MAK)

.PHONY: pjsua.ko
pjsua.ko:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(LIBDIR)/$@)

clean depend realclean:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $@
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $@
    #Problem happens in the next row!
    $(MAKE) -f $(SAMPLES_MAK) $@
    @if test "$@" = "depend"; then \
      echo '$(BINDIR)/$(PJSUA_EXE): $(APP_LIB_FILES)' >> .pjsua-$(TARGET_NAME).depend; \
      echo '$(BINDIR)/$(PJSYSTEST_EXE): $(APP_LIB_FILES)' >> .pjsystest-$(TARGET_NAME).depend; \
    fi
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
        rm -f ../src/pjsua/ios/$$tmp; \
      done; \
    fi;
</code>```

Like I said, I added the SAMPLES_MAK variable, but sadly it didn't help. I also found out which line is giving me the error, it's close to the end of the file $(MAKE) -f $(SAMPLES_MAK) $@.

答: Use official documentation for building. It works 100% for all current architectures for iOS.</p>

Body:
I have been trying to compile the PJSIP library for an iOS project which needs SIP. Following this tutorial, I have been able to run the configure-iphone script. The next step would to run the make dep for the dependencies, but sadly it fails bcs of some error, unknown to me. I have also tried to edit the makefile, so it points directly to the file, but I still get the error, so it can find the file.

/Applications/Xcode.app/Contents/Developer/usr/bin/make -f Samples.mak depend
make[2]: Nothing to be done for `depend'.

is the error I get.

The make file:

include ../../build.mak
include $(PJDIR)/build/common.mak

export LIBDIR := ../lib
export BINDIR := ../bin

RULES_MAK := $(PJDIR)/build/rules.mak
SAMPLES_MAK := $(PJDIR)/pjsip-apps/build/Samples.mak

###############################################################################
# Gather all flags.
#
export _CFLAGS  := $(CC_CFLAGS) $(OS_CFLAGS) $(HOST_CFLAGS) $(M_CFLAGS) \
           $(PJ_CFLAGS) $(CFLAGS) $(CC_INC)../../pjsip/include \
           $(CC_INC)../../pjlib/include \
           $(CC_INC)../../pjlib-util/include \
           $(CC_INC)../../pjnath/include \
           $(CC_INC)../../pjmedia/include
export _CXXFLAGS:= $(_CFLAGS) $(CC_CXXFLAGS) $(OS_CXXFLAGS) $(M_CXXFLAGS) \
           $(HOST_CXXFLAGS) $(CXXFLAGS)
export _LDFLAGS := $(CC_LDFLAGS) $(OS_LDFLAGS) $(M_LDFLAGS) $(HOST_LDFLAGS) \
           $(APP_LDFLAGS) $(APP_LDLIBS) $(LDFLAGS)

###############################################################################
# Defines for building PJSUA
#
export PJSUA_SRCDIR = ../src/pjsua
export PJSUA_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            main.o pjsua_app.o pjsua_app_cli.o pjsua_app_common.o \
            pjsua_app_config.o pjsua_app_legacy.o
export PJSUA_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSUA_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSUA_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSUA_EXE:=pjsua-$(TARGET_NAME)$(HOST_EXE)

###############################################################################
# Defines for building pjsystest
#
export PJSYSTEST_SRCDIR = ../src/pjsystest
export PJSYSTEST_OBJS += $(OS_OBJS) $(M_OBJS) $(CC_OBJS) $(HOST_OBJS) \
            systest.o main_console.o
export PJSYSTEST_CFLAGS += $(PJ_CFLAGS) $(CFLAGS)
export PJSYSTEST_CXXFLAGS += $(PJ_CXXFLAGS) $(CFLAGS)
export PJSYSTEST_LDFLAGS += $(PJ_LDFLAGS) $(PJ_LDLIBS) $(LDFLAGS)
export PJSYSTEST_EXE:=pjsystest-$(TARGET_NAME)$(HOST_EXE)

export CC_OUT CC AR RANLIB HOST_MV HOST_RM HOST_RMDIR HOST_MKDIR OBJEXT LD LDOUT

TARGETS := $(PJSUA_EXE) $(PJSYSTEST_EXE) samples

all: $(TARGETS)

swig:
    $(MAKE) -C ../src/swig

doc:

dep: depend
distclean: realclean

.PHONY: all dep depend clean realclean distclean
.PHONY: $(TARGETS)
.PHONY: $(PJSUA_EXE) $(PJSYSTEST_EXE)

pjsua: $(PJSUA_EXE)
$(PJSUA_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(BINDIR)/$@)
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        if test -f $$F; then \
          tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
          ln -sf $$F ../src/pjsua/ios/$$tmp; \
        fi; \
      done; \
    fi;

pjsystest: $(PJSYSTEST_EXE)
$(PJSYSTEST_EXE):
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $(subst /,$(HOST_PSEP),$(BINDIR)/$@)

samples:
    $(MAKE) -f $(SAMPLES_MAK)

.PHONY: pjsua.ko
pjsua.ko:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $(subst /,$(HOST_PSEP),$(LIBDIR)/$@)

clean depend realclean:
    $(MAKE) -f $(RULES_MAK) APP=PJSUA app=pjsua $@
    $(MAKE) -f $(RULES_MAK) APP=PJSYSTEST app=pjsystest $@
    #Problem happens in the next row!
    $(MAKE) -f $(SAMPLES_MAK) $@
    @if test "$@" = "depend"; then \
      echo '$(BINDIR)/$(PJSUA_EXE): $(APP_LIB_FILES)' >> .pjsua-$(TARGET_NAME).depend; \
      echo '$(BINDIR)/$(PJSYSTEST_EXE): $(APP_LIB_FILES)' >> .pjsystest-$(TARGET_NAME).depend; \
    fi
    @if echo "$(TARGET_NAME)" | grep -q "apple-darwin_ios$$"; then \
      for F in $(filter %$(TARGET_NAME).a,$(PJ_LIBXX_FILES)); do \
        tmp=`echo $${F##*/} | sed -e "s/\-$(TARGET_NAME)\.a/.a/"`; \
        rm -f ../src/pjsua/ios/$$tmp; \
      done; \
    fi;

Like I said, I added the SAMPLES_MAK variable, but sadly it didn't help. I also found out which line is giving me the error, it's close to the end of the file $(MAKE) -f $(SAMPLES_MAK) $@.


问:
i want to link one page which is inside the folder to another page which is outside the folder
enter image description here

I really need your help here because this is confusing me now. i am in the customesignup.php inside the customer folder. Now i want to link this page to index.php which is outside the customer folder. And that page of index.php is not in any folder it is just hanging outside of the customer folder as you can see in the above picture. help please. .

答: ../ will bring you out of the folder costom ant thn wrtie your file name </p>


问:
Using a database to store configuration rather than a configuration file
Unfortunately searching for this kind of material produces a lot of noise for me so I was wondering if anyone here knew of a good resource for anyone wishing to learn how to use a database to store site configuration info rather than a file.

I guess some points I'm interested in are:
1) How to store the data. One array like e107? Separate row for each configurable?
2) How to get the configuration data. Global array?

答:
One row per, similar to EAV.

Sure, global array or object sounds fine.


问:
After Git clone all my PHP files text is in one line
I had to recover my dev server and cloned the git repo I was working on, however now all files have their text on 1 line only.

This means that all PHP files is useless as many of them have // for my personal info. It's a mess and I am not quite sure what to do.

I understand that Git automatically converts line endings. I am working in a Windows environment and might have had it converted to UNIX/or something else from when I set it up.

Anyway that's done, but is there any way I can fix this?

答:
It depends on your installation of git for Windows. Make sure to set it to clone Windows-Style-line-endings (\r\n, a.k.a. CRLF) and to push Unix-Style-line-endings (\n, a.k.a. LF). This to prevent your current problem from happening again.

To solve your problem now, open the file in a Notepad / IDE and
replace "\n" by "\r\n". Actually, modern editors should not have a problem
in displaying your text.


问:
Homebrew install of node 8 installs npm v4 instead of v5
From what I understand npm v5 should be included with node v8, like mentioned in the node release blog. However, after successfully installing node v8 via homebrew, the npm version is still 4.2.0.

I initially upgraded from node v7, but a clean install yields the same result. Running brew doctor didn't help and I can't find any open issues on either the node or homebrew projects.

Any suggestions would be appreciated.

答: The issue is resolved, brew install node now correctly installs npm v5 :)


问:
How can I extract information in the lines between two headers?
I am new to python and am attempting to use this currently nonfunctioning code to extract information between two headers from a text file.

```<code>with open('toysystem.txt','r') as f:
  start = '<Keywords>'
  end = '</Keywords>'
  i = 0
  lines = f.readlines()
  for line in lines:
   if line == start:
    keywords = lines[i+1]
 i += 1
</code>```

For reference, the text file looks like this:

```<code><Keywords>
GTO
</Keywords>
</code>```

Any ideas on what might be wrong with the code? Or perhaps a different way to approach this problem?

Thank you!

答:
Use Python re module insted and parse it using regex?!

```<code>import re
with open('toysystem.txt','r') as f:
    contents = f.read()
    # will find all the expressions in the file and return a list of values inside the (). You can extend the expression according to your need.
    keywords = re.findall(r'\<keywords\>\s*\n*\s*(.*?)\s*\n*\s*\<\/keywords\>')
    print(keywords)
</code>```

from your file it will print

```<code>['GTO']
</code>```

for more about regular expression and python check Tutorialspoint
, For python3 and Python2

Body:
I am new to python and am attempting to use this currently nonfunctioning code to extract information between two headers from a text file.

with open('toysystem.txt','r') as f:
  start = '<Keywords>'
  end = '</Keywords>'
  i = 0
  lines = f.readlines()
  for line in lines:
   if line == start:
    keywords = lines[i+1]
 i += 1

For reference, the text file looks like this:

<Keywords>
GTO
</Keywords>

Any ideas on what might be wrong with the code? Or perhaps a different way to approach this problem?

Thank you!

Body:
Use Python re module insted and parse it using regex?!

import re
with open('toysystem.txt','r') as f:
    contents = f.read()
    # will find all the expressions in the file and return a list of values inside the (). You can extend the expression according to your need.
    keywords = re.findall(r'\<keywords\>\s*\n*\s*(.*?)\s*\n*\s*\<\/keywords\>')
    print(keywords)

from your file it will print

['GTO']

for more about regular expression and python check Tutorialspoint
, For python3 and Python2


问:
Powershell: How to output List content as table?
I have an arraylist of objects, but I want to output them to the console in a tabular format like Get-Process does for processes.

How can I output a List as a Table?

Format-Table just throws an error

```<code>$bulidsList | Format-Table -Auto -InputObject $bulidsList
</code>```

"The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input"

答:
You mentioned in the question "An arraylist of objects".
Here is a simple test to show you how those used with Format-Table:

```<code>$a = @()
$a += [pscustomobject]@{a = 1; b = 2}
$a += [pscustomobject]@{a = 3; b = 4}
$a += [pscustomobject]@{a = 5; b = 6}

$a | Format-Table
</code>```

Here is the output:

```<code>a b
- -
1 2
3 4
5 6
</code>```

Body:
I have an arraylist of objects, but I want to output them to the console in a tabular format like Get-Process does for processes.

How can I output a List as a Table?

Format-Table just throws an error

$bulidsList | Format-Table -Auto -InputObject $bulidsList

"The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input"

Body:
You mentioned in the question "An arraylist of objects".
Here is a simple test to show you how those used with Format-Table:

$a = @()
$a += [pscustomobject]@{a = 1; b = 2}
$a += [pscustomobject]@{a = 3; b = 4}
$a += [pscustomobject]@{a = 5; b = 6}

$a | Format-Table

Here is the output:

a b
- -
1 2
3 4
5 6


问:
Flex 3 DateChooser Control - Date Selection Changes on MouseUp Event
If you have a DateChooser control next to a text control and you left click your mouse to select the text then continue holding down the mouse button and letting the mouse button up while over the datechooser control, the selectedDate value changes to the date you are hovering over.  I have users that are having issues with this and it happens unintentionally because of the proximity of the two controls.  I cannot find a way to stop this effect.  Basically I would want the selectedDate to only change if the user actually clicks the calendar control ie. mouseDown or click.  Calling functions in those events do not change this behavior.  I need a way to disable the control from changing the date on the mouseUpEvent (I think). </p>

答:
That's an irritating bug because you cannot cancel events on the DateChooser. Here is a possible solution:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600">
    <mx:Script>
        <![CDATA[
            private function preventDateChooserBug(e:MouseEvent):void {
                //set the mouseChildren property to false, not enabled because
                //that could cause an irritating flickering when clicking the
                //text input box for focus
                dtc.mouseChildren = false;

                //add the event listener to stage so we get the mouse up event even
                //outside of the text input control
                stage.addEventListener(MouseEvent.MOUSE_UP, function(e2:MouseEvent):void {
                    dtc.mouseChildren = true;
                });

            }
        ]]>
    </mx:Script>
    <mx:TextInput x="10" y="10" id="txt" mouseDown="preventDateChooserBug(event)" />
    <mx:DateChooser x="178" y="10" id="dtc" />
</mx:Application>
</code>```

Body:
That's an irritating bug because you cannot cancel events on the DateChooser. Here is a possible solution:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600">
    <mx:Script>
        <![CDATA[
            private function preventDateChooserBug(e:MouseEvent):void {
                //set the mouseChildren property to false, not enabled because
                //that could cause an irritating flickering when clicking the
                //text input box for focus
                dtc.mouseChildren = false;

                //add the event listener to stage so we get the mouse up event even
                //outside of the text input control
                stage.addEventListener(MouseEvent.MOUSE_UP, function(e2:MouseEvent):void {
                    dtc.mouseChildren = true;
                });

            }
        ]]>
    </mx:Script>
    <mx:TextInput x="10" y="10" id="txt" mouseDown="preventDateChooserBug(event)" />
    <mx:DateChooser x="178" y="10" id="dtc" />
</mx:Application>


问:
Handling date/time in java/android and daylight savings
I am making a diary application for Android and I want to allow the user to select the timezone they are in. Time has always been a area of confusion for me programatically.

I am going to create an enum for the available timezones.

I am going to save date/time entries to a sqlite in long UTC format, then handling offsets and DST programmatically in Java for display purposes.

I am actually aware of Java's limitations when it comes to date/time handling.

```<code>Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC")); //returns the current time in UTC format
Long utcLong = utc.getTimeInMillis(); //returns current utc time in long for database insertion
</code>```

Question 1: How would I apply an offset to it and account for when to apply any additional DST offsets? Because not all timezones observe DST and DST comes into effect at different dates for different timezones.

Question 2: Java's TimeZone class has something like ~800 ids, it would be annoying to the user to have to scroll through ~800 options to find the one that applys to them. Is there a short list available? I'm thinking there are around ~50 useful timezones.

答:
First of all, I recommend you to not use the Calendar class. It's outdated and has lots of bugs and design issues. This terrible API was replaced by much better ones:

for Java >= 8, use the new date-time API

for Java <= 7, use the ThreeTen Backport

for Android, you can also try ThreeTenABP

The code below works for all, the only difference is the package names (in Java 8 is java.time and in ThreeTen Backport is org.threeten.bp), but the classes and methods names are the same.

To get the UTC current date/time, the best choice is to use Instant class:

```<code>// current date/time in UTC - now() always returns the current instant in UTC
Instant instant = Instant.now();
System.out.println(instant); // 2017-06-03T18:03:55.976Z

// equivalent to calendar.getTimeInMillis(), it returns a long
System.out.println(instant.toEpochMilli()); // 1496513035976
</code>```

To convert this instant to a timezone, you can use the ZoneId with a ZonedDateTime:

```<code>// ZoneId accepts the same IDs used by TimeZone
ZoneId zone = ZoneId.of("America/Sao_Paulo");
// convert instant to timezone
ZonedDateTime z = instant.atZone(zone);
System.out.println(z); // 2017-06-03T15:03:55.976-03:00[America/Sao_Paulo]

// converts back to UTC (returns an Instant)
System.out.println(z.toInstant()); // 2017-06-03T18:03:55.976Z
</code>```

The code above already takes care of DST changes, so the conversion from and to UTC is straightforward.

Timezone list

You say that you have a list of ~50 "useful" timezones. I don't know what criteria you used to define that list, but what happens if an user is in a timezone that's not in the list?

There are some ideas of timezone-picking user interfaces in this link and here. You can choose one and adapt to your app.

I also suggest to not use (if possible) the 3-letter timezone abbreviations (like CST or PST) because they are ambiguous and not standard. It's better to use the full names (like America/Sao_Paulo or Europe/London) as they are the ones used by Java's APIs (you can get the full list with ZoneId.getAvailableZoneIds()) and they are configured with all DST changes for each zone.

Body:
I am making a diary application for Android and I want to allow the user to select the timezone they are in. Time has always been a area of confusion for me programatically.

I am going to create an enum for the available timezones.

I am going to save date/time entries to a sqlite in long UTC format, then handling offsets and DST programmatically in Java for display purposes.

I am actually aware of Java's limitations when it comes to date/time handling.

Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC")); //returns the current time in UTC format
Long utcLong = utc.getTimeInMillis(); //returns current utc time in long for database insertion

Question 1: How would I apply an offset to it and account for when to apply any additional DST offsets? Because not all timezones observe DST and DST comes into effect at different dates for different timezones.

Question 2: Java's TimeZone class has something like ~800 ids, it would be annoying to the user to have to scroll through ~800 options to find the one that applys to them. Is there a short list available? I'm thinking there are around ~50 useful timezones.

Body:
First of all, I recommend you to not use the Calendar class. It's outdated and has lots of bugs and design issues. This terrible API was replaced by much better ones:

for Java >= 8, use the new date-time API

for Java <= 7, use the ThreeTen Backport

for Android, you can also try ThreeTenABP

The code below works for all, the only difference is the package names (in Java 8 is java.time and in ThreeTen Backport is org.threeten.bp), but the classes and methods names are the same.

To get the UTC current date/time, the best choice is to use Instant class:

// current date/time in UTC - now() always returns the current instant in UTC
Instant instant = Instant.now();
System.out.println(instant); // 2017-06-03T18:03:55.976Z

// equivalent to calendar.getTimeInMillis(), it returns a long
System.out.println(instant.toEpochMilli()); // 1496513035976

To convert this instant to a timezone, you can use the ZoneId with a ZonedDateTime:

// ZoneId accepts the same IDs used by TimeZone
ZoneId zone = ZoneId.of("America/Sao_Paulo");
// convert instant to timezone
ZonedDateTime z = instant.atZone(zone);
System.out.println(z); // 2017-06-03T15:03:55.976-03:00[America/Sao_Paulo]

// converts back to UTC (returns an Instant)
System.out.println(z.toInstant()); // 2017-06-03T18:03:55.976Z

The code above already takes care of DST changes, so the conversion from and to UTC is straightforward.

Timezone list

You say that you have a list of ~50 "useful" timezones. I don't know what criteria you used to define that list, but what happens if an user is in a timezone that's not in the list?

There are some ideas of timezone-picking user interfaces in this link and here. You can choose one and adapt to your app.

I also suggest to not use (if possible) the 3-letter timezone abbreviations (like CST or PST) because they are ambiguous and not standard. It's better to use the full names (like America/Sao_Paulo or Europe/London) as they are the ones used by Java's APIs (you can get the full list with ZoneId.getAvailableZoneIds()) and they are configured with all DST changes for each zone.


问:
Html - Get value from database
So I want to get the titlefor that image in the database. How do I do it? It's showing Describe your post... for all images instead of the actual title of the image in the database

https://i.gyazo.com/17828889116a77983f70fd8c8a4c2ebf.png

View:

```<code>    @foreach (var image in Model.Images)
{
    <h2>@Html.LabelFor(m => m.title)</h2>
    <div class="row">
        <div class="col-md-8 portfolio-item">
            <img class="portrait" src="@Url.Content(image)" alt="Hejsan" />
        </div>
    </div>

}
</code>```

Model

```<code> [Table("MemeImages")]
public class UploadFileModel
{
    [Key]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    public string location { get; set; }

    public IEnumerable<string> Images { get; set; }

    public int contentLength { get; set; }
    public string contentType { get; set; }

    public string userID { get; set; }

    [Required]
    [Display(Name = "Describe your post...")]
    public string title { get; set; }

    public void SavetoDatabase(UploadFileModel file)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        db.uploadedFiles.Add(file);
        db.SaveChanges();
    }
}
</code>```

答:
Instead of label use directly
m => m.title

Title: Html - Get value from database

Body:
So I want to get the titlefor that image in the database. How do I do it? It's showing Describe your post... for all images instead of the actual title of the image in the database

https://i.gyazo.com/17828889116a77983f70fd8c8a4c2ebf.png

View:

    @foreach (var image in Model.Images)
{

@Html.LabelFor(m => m.title)

}

Model

 [Table("MemeImages")]
public class UploadFileModel
{
    [Key]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    public string location { get; set; }

    public IEnumerable<string> Images { get; set; }

    public int contentLength { get; set; }
    public string contentType { get; set; }

    public string userID { get; set; }

    [Required]
    [Display(Name = "Describe your post...")]
    public string title { get; set; }

    public void SavetoDatabase(UploadFileModel file)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        db.uploadedFiles.Add(file);
        db.SaveChanges();
    }
}

Body: Instead of label use directly <h2>m => m.title</h2>