问:
Can I format Quandl request?
Ok, so what I need is just CVS file with basic stocks data with additional sector column for each company. Getting sectors and tickers from wikipedia works fine.

But Google/Yahoo data doesn't want to work anymore, so I've tried to use Quandl.I've recently made a few technical indicators based on it so I thought it would be great.But there is following error.

I am still in doubt if I can format my request like that so I assume that there is a problem but I can't figure a way to make it work.

Thank you for any advice and sorry for misspelings.

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd
import lxml
import quandl as qdl

def get_ticker_and_sector(url='https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'):
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, 'lxml')
table = soup.find('table')

sp500 = {}

for tr in table.find_all('tr')[1:]:
    tds = tr.find_all('td')
    ticker = tds[0].text
    sector = tds[3].text
    sp500[ticker] = sector
    return sp500

if __name__ == '__main__':
    sp500 = get_ticker_and_sector()
    for i, (ticker, sector) in enumerate(sp500.items()):
        stock_df = qdl.get('WIKI/%s', start_date="2010-12-11", end_date="2011-12-31")%(ticker)
        stock_df['Name'] = ticker
        stock_df['Sector'] = sector
        if i == 0:
            all_df = stock_df
        else:
            all_df = all_df.append(stock_df)
all_df.to_csv('all_sp500_data_2.csv')
</code>```

Error.

```<code>Traceback (most recent call last):
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 55, in parse
    return response.json()
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/requests/models.py", line 886, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/tomek/PycharmProjects/untitled4/get_file.py", line 30, in <module>
    stock_df = qdl.get('WIKI/%s', start_date="2010-12-11", end_date="2011-12-31")%('ticker')
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/get.py", line 48, in get
    data = Dataset(dataset_args['code']).data(params=kwargs, handle_column_not_found=True)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/model/dataset.py", line 47, in data
    return Data.all(**updated_options)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/operations/list.py", line 14, in all
    r = Connection.request('get', path, **options)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 36, in request
    return cls.execute_request(http_verb, abs_url, **options)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 44, in execute_request
    cls.handle_api_error(response)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 61, in handle_api_error
    error_body = cls.parse(resp)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 57, in parse
    raise QuandlError(http_status=response.status_code, http_body=response.text)
quandl.errors.quandl_error.QuandlError: (Status 400) Something went wrong. Please try again. If you continue to have problems, please contact us at connect@quandl.com.
</code>```

答:
The traceback is giving you an 400 status code which means something is wrong with the request to the API.

More specifically, Quandl's documentation says the following regarding a 400 status code:

We could not recognize your API key. Please check your API key and try again. You can find your API key under your account settings.

As a good starting point, have you entered your API key after installing the Quandl module? Steps are here for more information on how to do it.

Please note, I only glanced at the rest of your code, and didn't test it out fully to see if there are other errors!

Title: Can I format Quandl request?

Body:
Ok, so what I need is just CVS file with basic stocks data with additional sector column for each company. Getting sectors and tickers from wikipedia works fine.

But Google/Yahoo data doesn't want to work anymore, so I've tried to use Quandl.I've recently made a few technical indicators based on it so I thought it would be great.But there is following error.

I am still in doubt if I can format my request like that so I assume that there is a problem but I can't figure a way to make it work.

Thank you for any advice and sorry for misspelings.

from bs4 import BeautifulSoup
import requests
import pandas as pd
import lxml
import quandl as qdl

def get_ticker_and_sector(url='https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'):
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, 'lxml')
table = soup.find('table')

sp500 = {}

for tr in table.find_all('tr')[1:]:
    tds = tr.find_all('td')
    ticker = tds[0].text
    sector = tds[3].text
    sp500[ticker] = sector
    return sp500

if __name__ == '__main__':
    sp500 = get_ticker_and_sector()
    for i, (ticker, sector) in enumerate(sp500.items()):
        stock_df = qdl.get('WIKI/%s', start_date="2010-12-11", end_date="2011-12-31")%(ticker)
        stock_df['Name'] = ticker
        stock_df['Sector'] = sector
        if i == 0:
            all_df = stock_df
        else:
            all_df = all_df.append(stock_df)
all_df.to_csv('all_sp500_data_2.csv')

Error.

Traceback (most recent call last):
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 55, in parse
    return response.json()
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/requests/models.py", line 886, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/tomek/PycharmProjects/untitled4/get_file.py", line 30, in <module>
    stock_df = qdl.get('WIKI/%s', start_date="2010-12-11", end_date="2011-12-31")%('ticker')
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/get.py", line 48, in get
    data = Dataset(dataset_args['code']).data(params=kwargs, handle_column_not_found=True)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/model/dataset.py", line 47, in data
    return Data.all(**updated_options)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/operations/list.py", line 14, in all
    r = Connection.request('get', path, **options)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 36, in request
    return cls.execute_request(http_verb, abs_url, **options)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 44, in execute_request
    cls.handle_api_error(response)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 61, in handle_api_error
    error_body = cls.parse(resp)
  File "/home/tomek/tomek-workspace/pythons/udemy/lib/python3.5/site-packages/quandl/connection.py", line 57, in parse
    raise QuandlError(http_status=response.status_code, http_body=response.text)
quandl.errors.quandl_error.QuandlError: (Status 400) Something went wrong. Please try again. If you continue to have problems, please contact us at connect@quandl.com.


来源: stackexchange

问:
Why won't my PHP return a MySQL stored procedure?
Well I have this MySQL stored procedure that I wrote and if I run the following in phpMyAdmin things return properly:

```<code>SELECT game_name,urlfriendly(game_name) AS game_name2 FROM games
</code>```

However if I try to run the following code I get the error "Warning: Invalid argument supplied for foreach() in /filepath.php on line #"

```<code>foreach ($this->database->query("SELECT game_name,urlfriendly(game_name) AS game_name2 FROM games") as $games)
{
    echo $games["game_name"] . " " . $games["game_name2"];
}
</code>```

However if I run this it all goes fine:

```<code>foreach ($this->database->query("SELECT game_name FROM games") as $games)
{
    echo $games["game_name"];
}
</code>```

Meaning the stored proc won't return to PHP.

Any ideas?

EDIT Here's the stored proc (but I doubt it is the issue as phpMyAdmin is pulling values back from it just fine)

DELIMITER //

```<code>DROP FUNCTION urlfriendly
//
CREATE FUNCTION urlfriendly (unsafe TEXT) RETURNS TEXT

DETERMINISTIC

BEGIN

DECLARE safe TEXT;

SET safe = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LOWER(unsafe),' ','-'),'&','and'),'`',''),'~',''),'!',''),'@',''),'#',''),'$',''),'%',''),'^',''),'*',''),'(',''),')',''),'_',''),'+',''),'=',''),'[',''),'{',''),']',''),'}',''),'|',''),'\\',''),"'",""),'"',''),':',''),';',''),'<',''),',',''),'>',''),'.',''),'/',''),'?','');

RETURN safe;

END
//
</code>```

EDIT2 Here is the error returned from MySQL

```<code>execute command denied to user 'username'@'localhost' for routine 'databasename.urlfriendly' )
</code>```

答:
Can you get the errorInfo?

Can you run:

```<code>GRANT EXECUTE ON `database`.* TO 'username'@'localhost'
</code>```

From phpMyAdmin?

OwnerDisplayName: Andrew G. Johnson

ContentLicense: CC BY-SA 2.5

Body:
Well I have this MySQL stored procedure that I wrote and if I run the following in phpMyAdmin things return properly:

SELECT game_name,urlfriendly(game_name) AS game_name2 FROM games

However if I try to run the following code I get the error "Warning: Invalid argument supplied for foreach() in /filepath.php on line #"

foreach ($this->database->query("SELECT game_name,urlfriendly(game_name) AS game_name2 FROM games") as $games)
{
    echo $games["game_name"] . " " . $games["game_name2"];
}

However if I run this it all goes fine:

foreach ($this->database->query("SELECT game_name FROM games") as $games)
{
    echo $games["game_name"];
}

Meaning the stored proc won't return to PHP.

Any ideas?

EDIT Here's the stored proc (but I doubt it is the issue as phpMyAdmin is pulling values back from it just fine)

DELIMITER //

DROP FUNCTION urlfriendly
//
CREATE FUNCTION urlfriendly (unsafe TEXT) RETURNS TEXT

DETERMINISTIC

BEGIN

DECLARE safe TEXT;

SET safe = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(LOWER(unsafe),' ','-'),'&','and'),'`',''),'~',''),'!',''),'@',''),'#',''),'$',''),'%',''),'^',''),'*',''),'(',''),')',''),'_',''),'+',''),'=',''),'[',''),'{',''),']',''),'}',''),'|',''),'\\',''),"'",""),'"',''),':',''),';',''),'<',''),',',''),'>',''),'.',''),'/',''),'?','');

RETURN safe;

END
//

EDIT2 Here is the error returned from MySQL

execute command denied to user 'username'@'localhost' for routine 'databasename.urlfriendly' )

LastEditorDisplayName: Andrew G. Johnson

Body:
Can you get the errorInfo?

Can you run:

GRANT EXECUTE ON `database`.* TO 'username'@'localhost'

From phpMyAdmin?

OwnerDisplayName: Paolo Bergantino

LastEditorDisplayName: Paolo Bergantino


问:
Why do I get 'No -renderInContext: method found' warning?
I get a compiler warning at the -renderInContext:

```<code>- (UIImage *) imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
</code>```

I have QuartzCore in the project frameworks, and the code works.
How do I fix the code so it stops giving me the warning?

The exact warning I get is

```<code>warning: no '-renderInContext:' method found
warning: (Messages without a matching method signature
warning: will be assumed to return 'id' and accept
warning: '...' as arguments.)
</code>```

答: Do you have QuartzCore.framework in your project?</p>

Body:
I get a compiler warning at the -renderInContext:

- (UIImage *) imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

I have QuartzCore in the project frameworks, and the code works.
How do I fix the code so it stops giving me the warning?

The exact warning I get is

warning: no '-renderInContext:' method found
warning: (Messages without a matching method signature
warning: will be assumed to return 'id' and accept
warning: '...' as arguments.)


问:
ffmpeg - merge mp3 and mp4 (duration difference)
I'm trying to merge mp4 and mp3 files with ffmpeg.
mp4 duration - 9.800 sec, mp3 - 58.540 sec. So i using -shortest key.
Code:

```<code>ffmpeg -i video.mp4 -i audio.mp3 -c:v libx264 -c:a aac -strict experimental -shortest output.mp4
</code>```

After that i got output.mp4 with duration 9.846. Where is my error? Why output video longer than source? (9.846 sec and 9.800 sec).

Source mp4 MediaInfo:

```<code>General
Complete name                  : F:\video test\video.mp4
Format                         : MPEG-4
Format profile                 : Base Media
Codec ID                       : iso5 (iso5/dash)
File size                      : 3.19 MiB
Duration                       : 9 s 800 ms
Overall bit rate               : 2 732 kb/s
Encoded date                   : UTC 2017-11-24 20:53:53
Tagged date                    : UTC 2017-11-24 20:53:53

Video
ID                             : 1
Format                         : AVC
Format/Info                    : Advanced Video Codec
Format profile                 : High@L3.1
Format settings                : CABAC / 4 Ref Frames
Format settings, CABAC         : Yes
Format settings, ReFrames      : 4 frames
Codec ID                       : avc1
Codec ID/Info                  : Advanced Video Coding
Duration                       : 9 s 800 ms
Bit rate                       : 2 729 kb/s
Maximum bit rate               : 3 766 kb/s
Width                          : 1 280 pixels
Height                         : 720 pixels
Display aspect ratio           : 16:9
Frame rate mode                : Constant
Frame rate                     : 25.000 FPS
Color space                    : YUV
Chroma subsampling             : 4:2:0
Bit depth                      : 8 bits
Scan type                      : Progressive
Bits/(Pixel*Frame)             : 0.118
Stream size                    : 3.19 MiB (100%)
Writing library                : x264 core 146
Encoding settings              : cabac=1 / ref=3 / deblock=1:0:0 / analyse=0x3:0x113 / me=hex / subme=7 / psy=1 / psy_rd=1.00:0.00 / mixed_ref=1 / me_range=16 / chroma_me=1 / trellis=1 / 8x8dct=1 / cqm=0 / deadzone=21,11 / fast_pskip=1 / chroma_qp_offset=-2 / threads=12 / lookahead_threads=2 / sliced_threads=0 / nr=0 / decimate=1 / interlaced=0 / bluray_compat=0 / constrained_intra=0 / bframes=3 / b_pyramid=2 / b_adapt=1 / b_bias=0 / direct=1 / weightb=1 / open_gop=0 / weightp=2 / keyint=250 / keyint_min=25 / scenecut=40 / intra_refresh=0 / rc_lookahead=40 / rc=crf / mbtree=1 / crf=23.0 / qcomp=0.60 / qpmin=0 / qpmax=69 / qpstep=4 / ip_ratio=1.40 / aq=1:1.00
Tagged date                    : UTC 2017-11-24 20:53:53
</code>```

Source mp3 Mediainfo:

```<code>General
Complete name                  : F:\video test\audio.mp3
Format                         : MPEG Audio
File size                      : 1.19 MiB
Duration                       : 58 s 540 ms
Overall bit rate mode          : Variable
Overall bit rate               : 170 kb/s
Writing library                : LAME3.99r

Audio
Format                         : MPEG Audio
Format version                 : Version 1
Format profile                 : Layer 3
Format settings                : Joint stereo / MS Stereo
Duration                       : 58 s 540 ms
Bit rate mode                  : Variable
Bit rate                       : 170 kb/s
Minimum bit rate               : 32.0 kb/s
Channel(s)                     : 2 channels
Sampling rate                  : 44.1 kHz
Frame rate                     : 38.281 FPS (1152 SPF)
Compression mode               : Lossy
Stream size                    : 1.19 MiB (100%)
Writing library                : LAME3.99r
Encoding settings              : -m j -V 2 -q 0 -lowpass 18.5 --vbr-new -b 32
</code>```

Console output:

```<code>ffmpeg version 3.4 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 7.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-cuda --enable-cuvid --enable-d3d11va --enable-nvenc --enable-dxva2 --enable-avisynth --enable-libmfx
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':
  Metadata:
    major_brand     : iso5
    minor_version   : 1
    compatible_brands: iso5dash
    creation_time   : 2017-11-24T20:53:53.000000Z
  Duration: 00:00:09.80, start: 0.000000, bitrate: 2732 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 2259 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
Input #1, mp3, from 'audio.mp3':
  Duration: 00:00:58.54, start: 0.025057, bitrate: 170 kb/s
    Stream #1:0: Audio: mp3, 44100 Hz, stereo, s16p, 170 kb/s
    Metadata:
      encoder         : LAME3.99r
    Side data:
      replaygain: track gain - -2.200000, track peak - unknown, album gain - unknown, album peak - unknown,
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #1:0 -> #0:1 (mp3 (native) -> aac (native))
Press [q] to stop, [?] for help
[libx264 @ 00000000005ab440] using SAR=1/1
[libx264 @ 00000000005ab440] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 00000000005ab440] profile High, level 3.1
[libx264 @ 00000000005ab440] 264 - core 152 r2851 ba24899 - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'output.mp4':
  Metadata:
    major_brand     : iso5
    minor_version   : 1
    compatible_brands: iso5dash
    encoder         : Lavf57.83.100
    Stream #0:0(und): Video: h264 (libx264) (avc1 / 0x31637661), yuv420p(progressive), 1280x720 [SAR 1:1 DAR 16:9], q=-1--1, 25 fps, 12800 tbn, 25 tbc (default)
    Metadata:
      handler_name    : VideoHandler
      encoder         : Lavc57.107.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: -1
    Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s
    Metadata:
      encoder         : Lavc57.107.100 aac
    Side data:
      replaygain: track gain - -2.200000, track peak - unknown, album gain - unknown, album peak - unknown,
frame=   54 fps=0.0 q=28.0 size=       0kB time=00:00:00.04 bitrate=   8.3kbits/s speed=0.0927x
frame=   80 fps= 80 q=28.0 size=       0kB time=00:00:01.09 bitrate=   0.4kbits/s speed=1.09x
frame=   98 fps= 65 q=28.0 size=     256kB time=00:00:01.83 bitrate=1143.5kbits/s speed=1.21x
frame=  119 fps= 59 q=28.0 size=     512kB time=00:00:02.67 bitrate=1570.9kbits/s speed=1.32x
frame=  144 fps= 56 q=28.0 size=     768kB time=00:00:03.66 bitrate=1715.0kbits/s speed=1.42x
frame=  167 fps= 52 q=28.0 size=    1024kB time=00:00:04.57 bitrate=1833.9kbits/s speed=1.44x
frame=  190 fps= 51 q=28.0 size=    1280kB time=00:00:05.50 bitrate=1905.5kbits/s speed=1.47x
frame=  218 fps= 51 q=28.0 size=    1792kB time=00:00:06.64 bitrate=2210.6kbits/s speed=1.56x
frame=  242 fps= 50 q=28.0 size=    2048kB time=00:00:07.56 bitrate=2216.4kbits/s speed=1.58x
frame=  245 fps= 41 q=-1.0 Lsize=    3045kB time=00:00:09.82 bitrate=2539.6kbits/s speed=1.65x
video:2880kB audio:156kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.298058%
[libx264 @ 00000000005ab440] frame I:14    Avg QP:20.01  size: 39750
[libx264 @ 00000000005ab440] frame P:106   Avg QP:23.85  size: 14578
[libx264 @ 00000000005ab440] frame B:125   Avg QP:24.63  size:  6770
[libx264 @ 00000000005ab440] consecutive B-frames: 22.9% 22.0% 15.9% 39.2%
[libx264 @ 00000000005ab440] mb I  I16..4: 16.7% 80.3%  3.0%
[libx264 @ 00000000005ab440] mb P  I16..4: 10.2% 36.2%  1.1%  P16..4: 25.0%  7.9%  2.5%  0.0%  0.0%    skip:17.1%
[libx264 @ 00000000005ab440] mb B  I16..4:  2.3%  5.8%  0.2%  B16..8: 31.4%  6.5%  0.9%  direct: 3.7%  skip:49.2%  L0:51.8% L1:44.5% BI: 3.7%
[libx264 @ 00000000005ab440] 8x8 transform intra:76.1% inter:86.3%
[libx264 @ 00000000005ab440] coded y,uvDC,uvAC intra: 38.3% 52.1% 9.0% inter: 12.3% 20.1% 0.2%
[libx264 @ 00000000005ab440] i16 v,h,dc,p: 30% 28%  9% 33%
[libx264 @ 00000000005ab440] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 36% 23% 19%  3%  3%  4%  4%  4%  4%
[libx264 @ 00000000005ab440] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 33% 21% 14%  5%  7%  7%  6%  5%  3%
[libx264 @ 00000000005ab440] i8c dc,h,v,p: 45% 24% 25%  6%
[libx264 @ 00000000005ab440] Weighted P-Frames: Y:13.2% UV:6.6%
[libx264 @ 00000000005ab440] ref P L0: 71.7% 12.5% 12.9%  2.7%  0.2%
[libx264 @ 00000000005ab440] ref B L0: 92.8%  6.3%  0.9%
[libx264 @ 00000000005ab440] ref B L1: 98.3%  1.7%
[libx264 @ 00000000005ab440] kb/s:2406.56
[aac @ 00000000005adde0] Qavg: 511.420
</code>```

ffprobe -show_packets output too big, so I loaded to pastebin
https://pastebin.com/TYSMdceS

答:
A quick answer to your question is that FFmpeg / libaac encodes an extra aac priming packet at the beginning, starting at -0.0213 s. That adds to your duration.
I will try to give a detailed answered later if that would help.
You can try ffprobe -show_packets output.mp4.

I looked into the packets dump you shared.
You video packets looks like

```<code>dts: -0.08 | pts: 0.0
dts: -0.04 | pts: 0.12
dts:  0.0  | pts: 0.04
dts:  0.04 | pts: 0.08
dts:  0.08 | pts: 0.24
...
dts:  9.64 | pts: 9.76
dts:  9.68 | pts: 9.72
</code>```

The back and forth pts values are possibly because u have B frames with I B B P order.
Your video stream is 25 fps, which makes 1 frame duration = 0.04 s.
That makes your video 9.76 + 0.04(frame duration) = 9.8 s.

You original audio is larger than the video, so it would be truncated to have the last packet up to 9.80 s or later.
Your audio packets look like

```<code>pts: -0.023220 (AAC priming data)
pts:  0.0
pts:  0.023220
...
pts:  9.775601 | duration: 0.023220
pts:  9.798821 | duration: 0.023175
</code>```

You last audio packet has to end at 9.80 or after. That's why the packet at 9.79 is accepted.
So your duration of audio muxed into the AV stream is
0.02322 (primiing pkt) + 9.798821 + 0.023175 (dur) = 9.845216

I am not sure where the extra 0.001 s comes from. Someone else should be able to comment. There's skip data I see at the beginning.

```<code>[SIDE_DATA]
side_data_type=Skip Samples
skip_samples=1024
discard_padding=0
skip_reason=0
discard_reason=0
[/SIDE_DATA]
</code>```

I hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to merge mp4 and mp3 files with ffmpeg.
mp4 duration - 9.800 sec, mp3 - 58.540 sec. So i using -shortest key.
Code:

ffmpeg -i video.mp4 -i audio.mp3 -c:v libx264 -c:a aac -strict experimental -shortest output.mp4

After that i got output.mp4 with duration 9.846. Where is my error? Why output video longer than source? (9.846 sec and 9.800 sec).

Source mp4 MediaInfo:

General
Complete name                  : F:\video test\video.mp4
Format                         : MPEG-4
Format profile                 : Base Media
Codec ID                       : iso5 (iso5/dash)
File size                      : 3.19 MiB
Duration                       : 9 s 800 ms
Overall bit rate               : 2 732 kb/s
Encoded date                   : UTC 2017-11-24 20:53:53
Tagged date                    : UTC 2017-11-24 20:53:53

Video
ID                             : 1
Format                         : AVC
Format/Info                    : Advanced Video Codec
Format profile                 : High@L3.1
Format settings                : CABAC / 4 Ref Frames
Format settings, CABAC         : Yes
Format settings, ReFrames      : 4 frames
Codec ID                       : avc1
Codec ID/Info                  : Advanced Video Coding
Duration                       : 9 s 800 ms
Bit rate                       : 2 729 kb/s
Maximum bit rate               : 3 766 kb/s
Width                          : 1 280 pixels
Height                         : 720 pixels
Display aspect ratio           : 16:9
Frame rate mode                : Constant
Frame rate                     : 25.000 FPS
Color space                    : YUV
Chroma subsampling             : 4:2:0
Bit depth                      : 8 bits
Scan type                      : Progressive
Bits/(Pixel*Frame)             : 0.118
Stream size                    : 3.19 MiB (100%)
Writing library                : x264 core 146
Encoding settings              : cabac=1 / ref=3 / deblock=1:0:0 / analyse=0x3:0x113 / me=hex / subme=7 / psy=1 / psy_rd=1.00:0.00 / mixed_ref=1 / me_range=16 / chroma_me=1 / trellis=1 / 8x8dct=1 / cqm=0 / deadzone=21,11 / fast_pskip=1 / chroma_qp_offset=-2 / threads=12 / lookahead_threads=2 / sliced_threads=0 / nr=0 / decimate=1 / interlaced=0 / bluray_compat=0 / constrained_intra=0 / bframes=3 / b_pyramid=2 / b_adapt=1 / b_bias=0 / direct=1 / weightb=1 / open_gop=0 / weightp=2 / keyint=250 / keyint_min=25 / scenecut=40 / intra_refresh=0 / rc_lookahead=40 / rc=crf / mbtree=1 / crf=23.0 / qcomp=0.60 / qpmin=0 / qpmax=69 / qpstep=4 / ip_ratio=1.40 / aq=1:1.00
Tagged date                    : UTC 2017-11-24 20:53:53

Source mp3 Mediainfo:

General
Complete name                  : F:\video test\audio.mp3
Format                         : MPEG Audio
File size                      : 1.19 MiB
Duration                       : 58 s 540 ms
Overall bit rate mode          : Variable
Overall bit rate               : 170 kb/s
Writing library                : LAME3.99r

Audio
Format                         : MPEG Audio
Format version                 : Version 1
Format profile                 : Layer 3
Format settings                : Joint stereo / MS Stereo
Duration                       : 58 s 540 ms
Bit rate mode                  : Variable
Bit rate                       : 170 kb/s
Minimum bit rate               : 32.0 kb/s
Channel(s)                     : 2 channels
Sampling rate                  : 44.1 kHz
Frame rate                     : 38.281 FPS (1152 SPF)
Compression mode               : Lossy
Stream size                    : 1.19 MiB (100%)
Writing library                : LAME3.99r
Encoding settings              : -m j -V 2 -q 0 -lowpass 18.5 --vbr-new -b 32

Console output:

ffmpeg version 3.4 Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 7.2.0 (GCC)
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-cuda --enable-cuvid --enable-d3d11va --enable-nvenc --enable-dxva2 --enable-avisynth --enable-libmfx
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'video.mp4':
  Metadata:
    major_brand     : iso5
    minor_version   : 1
    compatible_brands: iso5dash
    creation_time   : 2017-11-24T20:53:53.000000Z
  Duration: 00:00:09.80, start: 0.000000, bitrate: 2732 kb/s
    Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 2259 kb/s, 25 fps, 25 tbr, 12800 tbn, 50 tbc (default)
    Metadata:
      handler_name    : VideoHandler
Input #1, mp3, from 'audio.mp3':
  Duration: 00:00:58.54, start: 0.025057, bitrate: 170 kb/s
    Stream #1:0: Audio: mp3, 44100 Hz, stereo, s16p, 170 kb/s
    Metadata:
      encoder         : LAME3.99r
    Side data:
      replaygain: track gain - -2.200000, track peak - unknown, album gain - unknown, album peak - unknown,
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> h264 (libx264))
  Stream #1:0 -> #0:1 (mp3 (native) -> aac (native))
Press [q] to stop, [?] for help
[libx264 @ 00000000005ab440] using SAR=1/1
[libx264 @ 00000000005ab440] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX
[libx264 @ 00000000005ab440] profile High, level 3.1
[libx264 @ 00000000005ab440] 264 - core 152 r2851 ba24899 - H.264/MPEG-4 AVC codec - Copyleft 2003-2017 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=-2 threads=6 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00
Output #0, mp4, to 'output.mp4':
  Metadata:
    major_brand     : iso5
    minor_version   : 1
    compatible_brands: iso5dash
    encoder         : Lavf57.83.100
    Stream #0:0(und): Video: h264 (libx264) (avc1 / 0x31637661), yuv420p(progressive), 1280x720 [SAR 1:1 DAR 16:9], q=-1--1, 25 fps, 12800 tbn, 25 tbc (default)
    Metadata:
      handler_name    : VideoHandler
      encoder         : Lavc57.107.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: -1
    Stream #0:1: Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s
    Metadata:
      encoder         : Lavc57.107.100 aac
    Side data:
      replaygain: track gain - -2.200000, track peak - unknown, album gain - unknown, album peak - unknown,
frame=   54 fps=0.0 q=28.0 size=       0kB time=00:00:00.04 bitrate=   8.3kbits/s speed=0.0927x
frame=   80 fps= 80 q=28.0 size=       0kB time=00:00:01.09 bitrate=   0.4kbits/s speed=1.09x
frame=   98 fps= 65 q=28.0 size=     256kB time=00:00:01.83 bitrate=1143.5kbits/s speed=1.21x
frame=  119 fps= 59 q=28.0 size=     512kB time=00:00:02.67 bitrate=1570.9kbits/s speed=1.32x
frame=  144 fps= 56 q=28.0 size=     768kB time=00:00:03.66 bitrate=1715.0kbits/s speed=1.42x
frame=  167 fps= 52 q=28.0 size=    1024kB time=00:00:04.57 bitrate=1833.9kbits/s speed=1.44x
frame=  190 fps= 51 q=28.0 size=    1280kB time=00:00:05.50 bitrate=1905.5kbits/s speed=1.47x
frame=  218 fps= 51 q=28.0 size=    1792kB time=00:00:06.64 bitrate=2210.6kbits/s speed=1.56x
frame=  242 fps= 50 q=28.0 size=    2048kB time=00:00:07.56 bitrate=2216.4kbits/s speed=1.58x
frame=  245 fps= 41 q=-1.0 Lsize=    3045kB time=00:00:09.82 bitrate=2539.6kbits/s speed=1.65x
video:2880kB audio:156kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.298058%
[libx264 @ 00000000005ab440] frame I:14    Avg QP:20.01  size: 39750
[libx264 @ 00000000005ab440] frame P:106   Avg QP:23.85  size: 14578
[libx264 @ 00000000005ab440] frame B:125   Avg QP:24.63  size:  6770
[libx264 @ 00000000005ab440] consecutive B-frames: 22.9% 22.0% 15.9% 39.2%
[libx264 @ 00000000005ab440] mb I  I16..4: 16.7% 80.3%  3.0%
[libx264 @ 00000000005ab440] mb P  I16..4: 10.2% 36.2%  1.1%  P16..4: 25.0%  7.9%  2.5%  0.0%  0.0%    skip:17.1%
[libx264 @ 00000000005ab440] mb B  I16..4:  2.3%  5.8%  0.2%  B16..8: 31.4%  6.5%  0.9%  direct: 3.7%  skip:49.2%  L0:51.8% L1:44.5% BI: 3.7%
[libx264 @ 00000000005ab440] 8x8 transform intra:76.1% inter:86.3%
[libx264 @ 00000000005ab440] coded y,uvDC,uvAC intra: 38.3% 52.1% 9.0% inter: 12.3% 20.1% 0.2%
[libx264 @ 00000000005ab440] i16 v,h,dc,p: 30% 28%  9% 33%
[libx264 @ 00000000005ab440] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 36% 23% 19%  3%  3%  4%  4%  4%  4%
[libx264 @ 00000000005ab440] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 33% 21% 14%  5%  7%  7%  6%  5%  3%
[libx264 @ 00000000005ab440] i8c dc,h,v,p: 45% 24% 25%  6%
[libx264 @ 00000000005ab440] Weighted P-Frames: Y:13.2% UV:6.6%
[libx264 @ 00000000005ab440] ref P L0: 71.7% 12.5% 12.9%  2.7%  0.2%
[libx264 @ 00000000005ab440] ref B L0: 92.8%  6.3%  0.9%
[libx264 @ 00000000005ab440] ref B L1: 98.3%  1.7%
[libx264 @ 00000000005ab440] kb/s:2406.56
[aac @ 00000000005adde0] Qavg: 511.420

ffprobe -show_packets output too big, so I loaded to pastebin
https://pastebin.com/TYSMdceS

Body:
A quick answer to your question is that FFmpeg / libaac encodes an extra aac priming packet at the beginning, starting at -0.0213 s. That adds to your duration.
I will try to give a detailed answered later if that would help.
You can try ffprobe -show_packets output.mp4.

I looked into the packets dump you shared.
You video packets looks like

dts: -0.08 | pts: 0.0
dts: -0.04 | pts: 0.12
dts:  0.0  | pts: 0.04
dts:  0.04 | pts: 0.08
dts:  0.08 | pts: 0.24
...
dts:  9.64 | pts: 9.76
dts:  9.68 | pts: 9.72

The back and forth pts values are possibly because u have B frames with I B B P order.
Your video stream is 25 fps, which makes 1 frame duration = 0.04 s.
That makes your video 9.76 + 0.04(frame duration) = 9.8 s.

You original audio is larger than the video, so it would be truncated to have the last packet up to 9.80 s or later.
Your audio packets look like

pts: -0.023220 (AAC priming data)
pts:  0.0
pts:  0.023220
...
pts:  9.775601 | duration: 0.023220
pts:  9.798821 | duration: 0.023175

You last audio packet has to end at 9.80 or after. That's why the packet at 9.79 is accepted.
So your duration of audio muxed into the AV stream is
0.02322 (primiing pkt) + 9.798821 + 0.023175 (dur) = 9.845216

I am not sure where the extra 0.001 s comes from. Someone else should be able to comment. There's skip data I see at the beginning.

[SIDE_DATA]
side_data_type=Skip Samples
skip_samples=1024
discard_padding=0
skip_reason=0
discard_reason=0
[/SIDE_DATA]

I hope this helps.


问:
ASP.NET Boilerplate - How to add Timezone to user profile
The user profile page doesn't appear to allow the user to specify their timezone. How should we add this feature so the user can select and save their timezone and then have the web pages display the localised date?

Times are displaying in my browser according to the location of the server, so I edit a record at 7am local time, and it appears as if I edited it 4 hours in the future :)

Best solution for me is to allow the user to specify their timezone on their profile and then have this setting reflected in times displayed in the UI.

答:
You need to set the Clock.Provider to the UTC clock on the server.  The documentation tells you that you need to set it but doesn't really tell you where.  You just need to set this during the startup process.  Here is a link to the docs that touch on it briefly.

Timing Documentation

Hope that helps.


问:
Android phone and bluetooth device communication error
I am modifying an Android bluetooth sample program to realise the communication between my android phone and an ELM327 module through Bluetooth.

The application is build from the program using Android studio. The application works very well between two android phones.

However, when I run it in one of my android phone and try to communicate with ELM327 module, the input messages coming from ELM327 are broken and some time has very serious delay. Could you please explain why the different apperances happen? If you can help to rectify the program, it will be really appreciated.

Below is part of the sample code for this application:

BluetoothChat.java: Handler

```<code>            private final Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case MESSAGE_WRITE:
                                byte[] writeBuf = (byte[]) msg.obj;

                                // construct a string from the buffer
                                String writeMessage = new String(writeBuf);
                                Log.d("ELM327", "message is send:" + writeMessage +"; length is:" + writeMessage.length());
                                mAdapter.notifyDataSetChanged();
                                messageList.add(new androidRecyclerView.Message(counter++, writeMessage, "Me"));
                                break;
                            case MESSAGE_READ:
                                byte[] readBuf = (byte[]) msg.obj;
                                //Log.d("ELM327", "message is received:" + readBuf + "; length is:" + readBuf.length);
                                // construct a string from the valid bytes in the buffer
                                String readMessage = new String(readBuf, 0, msg.arg1);
                                Log.d("ELM327", "message is received:" + readMessage +"; length is:" + readMessage.length());
                                mAdapter.notifyDataSetChanged();
                                messageList.add(new androidRecyclerView.Message(counter++, readMessage, mConnectedDeviceName));
                                break;
                            case MESSAGE_DEVICE_NAME:
                                // save the connected device's name
                                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                                Toast.makeText(getApplicationContext(), "Connected to "
                                        + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                                break;
                            case MESSAGE_TOAST:
                                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                };
</code>```

BluetoothChatService.java: run function for Reading input messages

```<code>            private class ConnectedThread extends Thread {
                private final BluetoothSocket mmSocket;
                private final InputStream mmInStream;
                private final OutputStream mmOutStream;

                public ConnectedThread(BluetoothSocket socket) {
                    mmSocket = socket;
                    InputStream tmpIn = null;
                    OutputStream tmpOut = null;
                    // Get the BluetoothSocket input and output streams
                    try {
                        tmpIn = socket.getInputStream();
                        tmpOut = socket.getOutputStream();
                    } catch (IOException e) {
                    }
                    mmInStream = tmpIn;
                    mmOutStream = tmpOut;
                }

                public void run() {
                    byte[] buffer = new byte[1024];
                    int bytes;
                    // Keep listening to the InputStream while connected
                    while (true) {
                        try {
                            // Read from the InputStream
                            bytes = mmInStream.read(buffer);
                            // Send the obtained bytes to the UI Activity
                            mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                                    .sendToTarget();
                        } catch (IOException e) {
                            connectionLost();
                            break;
                        }
                    }
                }
</code>```

答:
I missed adding "\r" at the end of each command message that I send from phone app to ELM327.

After adding "\r", I can receive correct feedback from ELM327.

Body:
I am modifying an Android bluetooth sample program to realise the communication between my android phone and an ELM327 module through Bluetooth.

The application is build from the program using Android studio. The application works very well between two android phones.

However, when I run it in one of my android phone and try to communicate with ELM327 module, the input messages coming from ELM327 are broken and some time has very serious delay. Could you please explain why the different apperances happen? If you can help to rectify the program, it will be really appreciated.

Below is part of the sample code for this application:

BluetoothChat.java: Handler

            private final Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case MESSAGE_WRITE:
                                byte[] writeBuf = (byte[]) msg.obj;

                                // construct a string from the buffer
                                String writeMessage = new String(writeBuf);
                                Log.d("ELM327", "message is send:" + writeMessage +"; length is:" + writeMessage.length());
                                mAdapter.notifyDataSetChanged();
                                messageList.add(new androidRecyclerView.Message(counter++, writeMessage, "Me"));
                                break;
                            case MESSAGE_READ:
                                byte[] readBuf = (byte[]) msg.obj;
                                //Log.d("ELM327", "message is received:" + readBuf + "; length is:" + readBuf.length);
                                // construct a string from the valid bytes in the buffer
                                String readMessage = new String(readBuf, 0, msg.arg1);
                                Log.d("ELM327", "message is received:" + readMessage +"; length is:" + readMessage.length());
                                mAdapter.notifyDataSetChanged();
                                messageList.add(new androidRecyclerView.Message(counter++, readMessage, mConnectedDeviceName));
                                break;
                            case MESSAGE_DEVICE_NAME:
                                // save the connected device's name
                                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                                Toast.makeText(getApplicationContext(), "Connected to "
                                        + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                                break;
                            case MESSAGE_TOAST:
                                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                                        Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                };

BluetoothChatService.java: run function for Reading input messages

            private class ConnectedThread extends Thread {
                private final BluetoothSocket mmSocket;
                private final InputStream mmInStream;
                private final OutputStream mmOutStream;

                public ConnectedThread(BluetoothSocket socket) {
                    mmSocket = socket;
                    InputStream tmpIn = null;
                    OutputStream tmpOut = null;
                    // Get the BluetoothSocket input and output streams
                    try {
                        tmpIn = socket.getInputStream();
                        tmpOut = socket.getOutputStream();
                    } catch (IOException e) {
                    }
                    mmInStream = tmpIn;
                    mmOutStream = tmpOut;
                }

                public void run() {
                    byte[] buffer = new byte[1024];
                    int bytes;
                    // Keep listening to the InputStream while connected
                    while (true) {
                        try {
                            // Read from the InputStream
                            bytes = mmInStream.read(buffer);
                            // Send the obtained bytes to the UI Activity
                            mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                                    .sendToTarget();
                        } catch (IOException e) {
                            connectionLost();
                            break;
                        }
                    }
                }


问:
How to get current location in MAPBOX in android
As I am using MAPBOX in my application. I don't know how to get current lat and long. I used this way to get the current location.But its showing null object reference.Please help me to solve my problem

mapView = (MapView)view.findViewById(R.id.mapView);
mapView.setStyleUrl(Style.MAPBOX_STREETS);
mapView.onCreate(savedInstanceState);

//Add a mapBoxMap
mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(MapboxMap mapboxMap) {
        mapboxMap.setMyLocationEnabled(true);
        // Set the origin waypoint to the devices location
        Position origin = Position.fromCoordinates(
            mapboxMap.getMyLocation().getLongitude(),
            mapboxMap.getMyLocation().getLatitude()
        );

        Log.i("RR","mapboxMap.getMyLocation();"+origin);
        // Log.i("RR","mapboxMap.getMyLocation();"+mapboxMap.getMyLocation().getLongitude());
        mapboxMap.getUiSettings().setZoomControlsEnabled(true);
        mapboxMap.getUiSettings().setZoomGesturesEnabled(true);
        mapboxMap.getUiSettings().setScrollGesturesEnabled(true);
        mapboxMap.getUiSettings().setAllGesturesEnabled(true);
    }
});
```

答:
mapboxMap.setMyLocationEnabled(true); has been deprecated.

You need to use locationEngine to get lat and long like this

```<code>    locationEngine = new LostLocationEngine(MainActivity.this);
    locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
    locationEngine.setInterval(5000);
    locationEngine.activate();
    Location lastLocation = locationEngine.getLastLocation();
</code>```

use lastLocation.getLatitude(), lastLocation.getLongitude()

ContentLicense: CC BY-SA 4.0

Body:
mapboxMap.setMyLocationEnabled(true); has been deprecated.

You need to use locationEngine to get lat and long like this

    locationEngine = new LostLocationEngine(MainActivity.this);
    locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
    locationEngine.setInterval(5000);
    locationEngine.activate();
    Location lastLocation = locationEngine.getLastLocation();

use lastLocation.getLatitude(), lastLocation.getLongitude()


问:
How to initialize a EditText when the Fragment's method is called from activity?
i work on a NotePad application, because i wanted to try SQLite and i don't have a correct NotePad app on my smartphone.

Screenshot of the app

So my app is composed of a Activity which contains a Viewpager and a menu for save the Note, create a new Note or delete the current note, and a Fragment where is a simple EditText.

I create a custom object Note which is compose of a String title, a String content and a Integer id for save the data on SQLite.

So my problem is for the functionnality of saving the Note on my database.

Its start with the menu in the Action Bar of the Activity, so when i click on the button for Saving (the second which look like a SD card), i called a method from my Fragment for edit the Note on the database like this :

```<code>private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}
</code>```

The arraylist contains the title of every note (i use him for create the TabLayout) and i pass him for get the title of the note.

So there is the code of my Fragment :

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = (ViewGroup) inflater.inflate(R.layout.fragment_tab, container, false);
    editText1 = rootview.findViewById(R.id.editText1);

    manager = new NoteManager(getActivity());
    manager.open();

    Bundle args = getArguments();
    position = args.getInt("0");
    arrayListContent = args.getStringArrayList("1");

    editText1.setText(arrayListContent.get(position));
    return rootview;
}

public void editNote(ArrayList<String> arrayListTitle) {
    title_edit = arrayListTitle.get(position);
    content_edit = editText1.getText().toString();
    Note note = manager.getNote(position + 1);

    note.setTitle(title_edit);
    note.setContent(content_edit);
    manager.modNote(note);
}
</code>```

When i go in the editNote method i receive the error :

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: fr.pensebete, PID: 24165
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                  at fr.pensebete.TabFragment.editNote(TabFragment.java:50)
                  at fr.pensebete.MainActivity.save(MainActivity.java:130)
                  at fr.pensebete.MainActivity.onOptionsItemSelected(MainActivity.java:101)
                  at android.app.Activity.onMenuItemSelected(Activity.java:3369)
                  at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
                  at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:65)
                  at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:202)
                  at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
                  at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                  at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
                  at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
                  at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
                  at android.view.View.performClick(View.java:6213)
                  at android.widget.TextView.performClick(TextView.java:11074)
                  at android.view.View$PerformClick.run(View.java:23645)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6692)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
</code>```

I know its because the EditText is not initialize because i called the editNote() method only and the OnCreateView is not called.

How can i call the EditNote() method from the Activity and make the EditText and the variable position initialize correctly (like in the OnCreateView method)? Can you help me because i search since 3 hours without a solution to make it works.

Thanks for your time and your help, and sorry for my bad english.

Edit : During i write this question i realize its maybe because i do a new TabFragment in my Activity's method :

```<code>private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}
</code>```

Maybe i must receive or find the current fragment already created, but i don't know how to do that. HELP !

答:
Try this:

```<code>private void save() {
    TabFragment fragment = getFragmentManager().findFragmentByTag("Tag");
    fragment.editNote(arrayListTitle);
}
</code>```

Be sure that when you create your fragment t you set the tag like so:

```<code>getFragmentManager().beginTransaction().replace(R.id.frame, new TabFragment(), "Tag").commit();
</code>```

Body:
i work on a NotePad application, because i wanted to try SQLite and i don't have a correct NotePad app on my smartphone.

Screenshot of the app

So my app is composed of a Activity which contains a Viewpager and a menu for save the Note, create a new Note or delete the current note, and a Fragment where is a simple EditText.

I create a custom object Note which is compose of a String title, a String content and a Integer id for save the data on SQLite.

So my problem is for the functionnality of saving the Note on my database.

Its start with the menu in the Action Bar of the Activity, so when i click on the button for Saving (the second which look like a SD card), i called a method from my Fragment for edit the Note on the database like this :

private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}

The arraylist contains the title of every note (i use him for create the TabLayout) and i pass him for get the title of the note.

So there is the code of my Fragment :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootview = (ViewGroup) inflater.inflate(R.layout.fragment_tab, container, false);
    editText1 = rootview.findViewById(R.id.editText1);

    manager = new NoteManager(getActivity());
    manager.open();

    Bundle args = getArguments();
    position = args.getInt("0");
    arrayListContent = args.getStringArrayList("1");

    editText1.setText(arrayListContent.get(position));
    return rootview;
}

public void editNote(ArrayList<String> arrayListTitle) {
    title_edit = arrayListTitle.get(position);
    content_edit = editText1.getText().toString();
    Note note = manager.getNote(position + 1);

    note.setTitle(title_edit);
    note.setContent(content_edit);
    manager.modNote(note);
}

When i go in the editNote method i receive the error :

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: fr.pensebete, PID: 24165
              java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
                  at fr.pensebete.TabFragment.editNote(TabFragment.java:50)
                  at fr.pensebete.MainActivity.save(MainActivity.java:130)
                  at fr.pensebete.MainActivity.onOptionsItemSelected(MainActivity.java:101)
                  at android.app.Activity.onMenuItemSelected(Activity.java:3369)
                  at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:368)
                  at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:108)
                  at android.support.v7.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:65)
                  at android.support.v7.widget.Toolbar$1.onMenuItemClick(Toolbar.java:202)
                  at android.support.v7.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:780)
                  at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                  at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
                  at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:963)
                  at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:624)
                  at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:150)
                  at android.view.View.performClick(View.java:6213)
                  at android.widget.TextView.performClick(TextView.java:11074)
                  at android.view.View$PerformClick.run(View.java:23645)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6692)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

I know its because the EditText is not initialize because i called the editNote() method only and the OnCreateView is not called.

How can i call the EditNote() method from the Activity and make the EditText and the variable position initialize correctly (like in the OnCreateView method)? Can you help me because i search since 3 hours without a solution to make it works.

Thanks for your time and your help, and sorry for my bad english.

Edit : During i write this question i realize its maybe because i do a new TabFragment in my Activity's method :

private void save() {
    TabFragment fragment = new TabFragment();
    fragment.editNote(arrayListTitle);
}

Maybe i must receive or find the current fragment already created, but i don't know how to do that. HELP !

Body:
Try this:

private void save() {
    TabFragment fragment = getFragmentManager().findFragmentByTag("Tag");
    fragment.editNote(arrayListTitle);
}

Be sure that when you create your fragment t you set the tag like so:

getFragmentManager().beginTransaction().replace(R.id.frame, new TabFragment(), "Tag").commit();


问:
Android - displaying UTF-8 (russian) on device
I'm debugging application on my android device (Motorola Defy, 2.1), the application gets Russian HTML page from network, but can't display it. It displays as link text.
HTML page is in UTF-8 (100% sure). Source code:

```<code>HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://m.rasp.yandex.ru/direction?direction=" + direction);
        httpget.setHeader("charset", "utf-8");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String html = httpclient.execute(httpget, responseHandler);
</code>```

What am I need for normal displaying of Russian text? Sorry for bad English knowledge.

答:
I suppose that you should decode String html from CP-1251 or smth like that to UTF-8 (html.setHeader() - migth be ignored).

My suggestion would be to copy returned text (let say from LogCat) and place it into ArtLebedev's decoder. So you will know  original coding of HTML returned back from Yandex.

Body:
I'm debugging application on my android device (Motorola Defy, 2.1), the application gets Russian HTML page from network, but can't display it. It displays as link text.
HTML page is in UTF-8 (100% sure). Source code:

HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://m.rasp.yandex.ru/direction?direction=" + direction);
        httpget.setHeader("charset", "utf-8");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String html = httpclient.execute(httpget, responseHandler);

What am I need for normal displaying of Russian text? Sorry for bad English knowledge.


问:
Find the first record according to a chain of JOIN rules in SQL
I need to find a "best fit" record by using a multi-field relation.
I need to JOIN based on 3 fields, if this fails use 2 fileds, and if this fails use 1-filed condition, etc.
Such chain can be long, fields can vary, etc.
How to achieve this.

Below I present some ideas but somehow feel this could be done better.

First way (I don't like the UNION because I guess the engine will execute them all regardless of the LIMIT 1 clause which could work as "stop on first found":

```<code>SELECT A1, A2, A3, B4 FROM A
LEFT OUTER JOIN (SELECT B4 FROM
      ((SELECT B4, 1 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
      UNION ALL
      (SELECT B4, 2 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2)
      UNION ALL
      (SELECT B4, 3 AS ORD FROM B
            WHERE B.B1 = A.A1)) ORDER BY ORD ASC LIMIT 1);
</code>```

Second way (here I don't like the repeated SELECT IN WHEN and again in THEN section, also it is only good when a single field is returned

```<code>SELECT A1, A2, A3,
    CASE
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1)
            THEN (SELECT B4 FROM B WHERE B.B1 = A.A1 LIMIT 1)
        ELSE NULL
    END AS B4
FROM A;
</code>```

I use postgreSQL 9.6 but the questions should be treated as standard SQL question.

Code to test:

```<code>CREATE TABLE A (A1 INT, A2 INT, A3 INT);
CREATE TABLE B (B1 INT, B2 INT, B3 INT, B4 VARCHAR(2));

INSERT INTO A VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO B VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');

/*
EXPECTED RESULT
10, 20, 30, A1
11, 21, 31, B
12, 22, 32, C
*/
</code>```

答:
You can use left join.  Here is one way:

```<code>select a.A1, a.A2, a.A3, coalesce(b1.B4, b2.b4, b3.b4) as b4
from A left join
     b b1
     on b1.b1 = a.a1 and b1.b2 = a.b2 and b1.b3 = a.b3 left join
     b b2
     on b1.b1 = a.a1 and b1.b2 = a.b2 and b1.a1 is null left join
     b b3
     on b1.b1 = a.a1 and b2.b1 is null and b1.b1 is null;
</code>```

The above could return multiple rows.  If you only want one row, then you can try:

```<code>select a.*,
       (select b.b4
        from b
        where b.b1 = a.a1
        order by (b.b2 = a.a2 and b.b3 = a.a3)::int desc,
                 (b.b2 = a.a2)::int desc
        limit 1
       ) as b4
from a;
</code>```

This is not as efficient.  And, the query can be phrased as a lateral join -- particularly useful if you want to return more than one value.

Body:
I need to find a "best fit" record by using a multi-field relation.
I need to JOIN based on 3 fields, if this fails use 2 fileds, and if this fails use 1-filed condition, etc.
Such chain can be long, fields can vary, etc.
How to achieve this.

Below I present some ideas but somehow feel this could be done better.

First way (I don't like the UNION because I guess the engine will execute them all regardless of the LIMIT 1 clause which could work as "stop on first found":

SELECT A1, A2, A3, B4 FROM A
LEFT OUTER JOIN (SELECT B4 FROM
      ((SELECT B4, 1 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
      UNION ALL
      (SELECT B4, 2 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2)
      UNION ALL
      (SELECT B4, 3 AS ORD FROM B
            WHERE B.B1 = A.A1)) ORDER BY ORD ASC LIMIT 1);

Second way (here I don't like the repeated SELECT IN WHEN and again in THEN section, also it is only good when a single field is returned

SELECT A1, A2, A3,
    CASE
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1)
            THEN (SELECT B4 FROM B WHERE B.B1 = A.A1 LIMIT 1)
        ELSE NULL
    END AS B4
FROM A;

I use postgreSQL 9.6 but the questions should be treated as standard SQL question.

Code to test:

CREATE TABLE A (A1 INT, A2 INT, A3 INT);
CREATE TABLE B (B1 INT, B2 INT, B3 INT, B4 VARCHAR(2));

INSERT INTO A VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO B VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');

/*
EXPECTED RESULT
10, 20, 30, A1
11, 21, 31, B
12, 22, 32, C
*/

Body:
You can use left join.  Here is one way:

select a.A1, a.A2, a.A3, coalesce(b1.B4, b2.b4, b3.b4) as b4
from A left join
     b b1
     on b1.b1 = a.a1 and b1.b2 = a.b2 and b1.b3 = a.b3 left join
     b b2
     on b1.b1 = a.a1 and b1.b2 = a.b2 and b1.a1 is null left join
     b b3
     on b1.b1 = a.a1 and b2.b1 is null and b1.b1 is null;

The above could return multiple rows.  If you only want one row, then you can try:

select a.*,
       (select b.b4
        from b
        where b.b1 = a.a1
        order by (b.b2 = a.a2 and b.b3 = a.a3)::int desc,
                 (b.b2 = a.a2)::int desc
        limit 1
       ) as b4
from a;

This is not as efficient.  And, the query can be phrased as a lateral join -- particularly useful if you want to return more than one value.


问:
all possible combinations of a set in Matlab
I'm trying to find all possible combinations of a set but the order of the elements are also important for my problem.

For example for the set set={A, B, C}, the possible subsets are subsets={A},{B},{C},{A,B},{A,C},{B,A},{B,C},{C,A},{C,B},{A,B,C},{A,C,B},{B,A,C},{B,C,A},{C,A,B},{C,B,A}.

Are there any Matlab function to find that?

Thanks in advance.

答:
```<code>a = {'A' 'B' 'C'};
a_len = numel(a);

res_len = 0;

for i = 1:a_len
    res_len = res_len + (factorial(a_len) / factorial(a_len - i));
end

res = cell(res_len,a_len);
res_off = 1;

for i = 1:a_len
    bin = nchoosek(a,i);

    for j = 1:size(bin,1)
        bin_j = bin(j,:);

        per = perms(bin_j);
        per_hei = size(per,1);

        res_ran = res_off + per_hei - 1;
        res(res_off:res_ran,:) = [per repmat({''},size(per,1),a_len - i)];
        res_off = res_off + per_hei;
    end
end
</code>```

Alternatively, if you don't want results organized into equally sized columns, but rather inserted into a single vector with variable length:

```<code>a = {'A' 'B' 'C'};
a_len = numel(a);

res_len = 0;

for i = 1:a_len
    res_len = res_len + (factorial(a_len) / factorial(a_len - i));
end

res = cell(res_len,1);
res_off = 1;

for i = 1:numel(a)
    bin = nchoosek(a,i);

    for j = 1:size(bin,1)
        bin_j = bin(j,:);
        per = perms(bin_j);

        for y = 1:size(per,1)
            res{res_off,1} = {per{y,:}};
            res_off = res_off + 1;
        end
    end
end
</code>```

Body:
a = {'A' 'B' 'C'};
a_len = numel(a);

res_len = 0;

for i = 1:a_len
    res_len = res_len + (factorial(a_len) / factorial(a_len - i));
end

res = cell(res_len,a_len);
res_off = 1;

for i = 1:a_len
    bin = nchoosek(a,i);

    for j = 1:size(bin,1)
        bin_j = bin(j,:);

        per = perms(bin_j);
        per_hei = size(per,1);

        res_ran = res_off + per_hei - 1;
        res(res_off:res_ran,:) = [per repmat({''},size(per,1),a_len - i)];
        res_off = res_off + per_hei;
    end
end

Alternatively, if you don't want results organized into equally sized columns, but rather inserted into a single vector with variable length:

a = {'A' 'B' 'C'};
a_len = numel(a);

res_len = 0;

for i = 1:a_len
    res_len = res_len + (factorial(a_len) / factorial(a_len - i));
end

res = cell(res_len,1);
res_off = 1;

for i = 1:numel(a)
    bin = nchoosek(a,i);

    for j = 1:size(bin,1)
        bin_j = bin(j,:);
        per = perms(bin_j);

        for y = 1:size(per,1)
            res{res_off,1} = {per{y,:}};
            res_off = res_off + 1;
        end
    end
end


问:
mkvirtualenv in current directory (windows)
I am working on a Windows (10) environment using command prompt.  I created a project directory here c:\users\myproject.  In command prompt, I type

```<code>C:\users\myproject>mkvirtualenv myenv .
     virtuanenv "." already exists
</code>```

If I leave out the "." at the end of the command, it creates a virtual environment in C:\users\Envs\ directory.

How do I create a virtual environment in my project directory itself?

答:
You have to set the WORKON_HOME environment variable name and value.

The name is simply: WORKON_HOME

The value is the path where you want your virtual env directory to be created when you type mkvirtualenv venv

"venv" above is nothing special; it's just a name you choose. If you don't specify the WORKON_HOME variable, when you run mkvirtualenv venv on Windows, a directory named %USERPROFILE%\Envs where %USERPROFILE% translates to C:\Users\your.name.

See my more verbose, step-by-step answer here.

Body:
I am working on a Windows (10) environment using command prompt.  I created a project directory here c:\users\myproject.  In command prompt, I type

C:\users\myproject>mkvirtualenv myenv .
     virtuanenv "." already exists

If I leave out the "." at the end of the command, it creates a virtual environment in C:\users\Envs\ directory.

How do I create a virtual environment in my project directory itself?


问:
Access public static variable from another script Unity
I am trying to access and change of the value of a variable from another script, I have watched various different tutorial on youtube but cannot seems to do it. It always come up with an error as following:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GlobalValues : MonoBehaviour
{

    public static bool c2u;

}
</code>```

And the other script

```<code>public class Choosing : MonoBehaviour {
private void Start()
{
    GlobalValues.c2u = false;
}
}
</code>```

In the "Choosing" script, the GlobalValues always shows "'GlobalValues' does not exist in this current context". What can i do to fix this problem

答: That code should work fine. The only way I could see it not working is if you haven't saved one of the scripts.</p>

Body:
I am trying to access and change of the value of a variable from another script, I have watched various different tutorial on youtube but cannot seems to do it. It always come up with an error as following:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GlobalValues : MonoBehaviour
{

    public static bool c2u;

}

And the other script

public class Choosing : MonoBehaviour {
private void Start()
{
    GlobalValues.c2u = false;
}
}

In the "Choosing" script, the GlobalValues always shows "'GlobalValues' does not exist in this current context". What can i do to fix this problem


问:
Get caret (cursor) position in contentEditable area containing HTML content
I have contentEditable element (can be p, div, ...) and I would like to get caret (cursor) position in it. I can normally achieve it with this piece of code:

```<code>var position = window.getSelection().getRangeAt(0).startOffset;
</code>```

This works fine while the element contains just text. But when the element contains some HTML formatting, the returned position is relative to caret position within included HTML element.

Let's assume contents of contentEditable element is this:

```<code>AB<b>CD</b>EF
</code>```

If caret is inside , let's say between C and D, the returned position with above code is 1 instead of 3 (counted from the begining of the contentEditable element's content)

Can anybody come up with solution to this ?

答:
UPDATE

I've written a simpler version of this that also works in IE < 9:

https://stackoverflow.com/a/4812022/96100

Old Answer

This is actually a more useful result than a character offset within the text of the whole document: the startOffset property of a DOM Range (which is what window.getSelection().getRangeAt() returns) is an offset relative to its startContainer property (which isn't necessarily always a text node, by the way). However, if you really want a character offset, here's a function that will do it.

Here's a live example: http://jsfiddle.net/timdown/2YcaX/

Here's the function:

```<code>function getCharacterOffsetWithin(range, node) {
    var treeWalker = document.createTreeWalker(
        node,
        NodeFilter.SHOW_TEXT,
        function(node) {
            var nodeRange = document.createRange();
            nodeRange.selectNode(node);
            return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
                NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
        },
        false
    );

    var charCount = 0;
    while (treeWalker.nextNode()) {
        charCount += treeWalker.currentNode.length;
    }
    if (range.startContainer.nodeType == 3) {
        charCount += range.startOffset;
    }
    return charCount;
}
</code>```

Body:
I have contentEditable element (can be p, div, ...) and I would like to get caret (cursor) position in it. I can normally achieve it with this piece of code:

var position = window.getSelection().getRangeAt(0).startOffset;

This works fine while the element contains just text. But when the element contains some HTML formatting, the returned position is relative to caret position within included HTML element.

Let's assume contents of contentEditable element is this:

ABCDEF

If caret is inside , let's say between C and D, the returned position with above code is 1 instead of 3 (counted from the begining of the contentEditable element's content)

Can anybody come up with solution to this ?

Body:
UPDATE

I've written a simpler version of this that also works in IE < 9:

https://stackoverflow.com/a/4812022/96100

Old Answer

This is actually a more useful result than a character offset within the text of the whole document: the startOffset property of a DOM Range (which is what window.getSelection().getRangeAt() returns) is an offset relative to its startContainer property (which isn't necessarily always a text node, by the way). However, if you really want a character offset, here's a function that will do it.

Here's a live example: http://jsfiddle.net/timdown/2YcaX/

Here's the function:

function getCharacterOffsetWithin(range, node) {
    var treeWalker = document.createTreeWalker(
        node,
        NodeFilter.SHOW_TEXT,
        function(node) {
            var nodeRange = document.createRange();
            nodeRange.selectNode(node);
            return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
                NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
        },
        false
    );

    var charCount = 0;
    while (treeWalker.nextNode()) {
        charCount += treeWalker.currentNode.length;
    }
    if (range.startContainer.nodeType == 3) {
        charCount += range.startOffset;
    }
    return charCount;
}