

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dropboxlike &#8211; Max的程式語言筆記</title>
	<atom:link href="https://stackoverflow.max-everyday.com/tag/dropboxlike/feed/" rel="self" type="application/rss+xml" />
	<link>https://stackoverflow.max-everyday.com</link>
	<description>我要當一個豬頭，快樂過每一天</description>
	<lastBuildDate>Wed, 24 Feb 2021 17:22:44 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://stackoverflow.max-everyday.com/wp-content/uploads/2017/02/max-stackoverflow-256.png</url>
	<title>Dropboxlike &#8211; Max的程式語言筆記</title>
	<link>https://stackoverflow.max-everyday.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Mysql備份與還原資料庫</title>
		<link>https://stackoverflow.max-everyday.com/2017/04/mysql-dump-restore/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/04/mysql-dump-restore/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Mon, 03 Apr 2017 04:01:21 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<category><![CDATA[mysql]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=402</guid>

					<description><![CDATA[原來 mysql 的備份還有還原這麼簡單 @_@...]]></description>
										<content:encoded><![CDATA[
<p>原來 mysql 的備份還有還原這麼簡單 @_@；</p>



<h2 class="wp-block-heading">備份：</h2>



<p>&#8212; 備份某個資料庫</p>



<pre class="wp-block-preformatted">mysqldump -u root -p db_name &gt; backup.sql;</pre>



<p>&#8212; 備份所有資料庫</p>



<pre class="wp-block-preformatted">mysqldump -u root -p --all-databases &gt; backup.sql;</pre>



<p>附註：備所有資料庫，遇到 database 版本不同時，會有問題，例如 mysql 5.6 到 5.7 會造成系統預設的欄位長度不符的錯誤。</p>



<p>備份用的 shell script:</p>



<pre class="wp-block-preformatted">#!/bin/sh 
pw='your-password'
mysqldump --all-databases --add-drop-table -h 127.0.0.1 -u root -p$pw &gt; your-backup-file.sql
bzip2 -f your-backup-file.sql</pre>



<hr class="wp-block-separator"/>



<p>bz2 壓縮：</p>



<p>bzip2 -z FileName</p>



<p>bz2 解壓縮：<br>bzip2 -d FileName.bz2</p>



<hr class="wp-block-separator"/>



<h2 class="wp-block-heading">還原：</h2>



<pre class="wp-block-preformatted">mysql -u root -p &lt; backup.sql</pre>



<p>如果出現 no database selected 是因為 backup.sql 裡沒有包括了 create database 的指令，只有去 drop table. 所以要在一還原的地方指定好要被貼回來的 database name:</p>



<pre class="wp-block-preformatted">mysql DATABASE_NAME -u root -p &lt; backup.sql</pre>



<p>進階一點的備份：</p>



<p>MySQL 自動備份 Shell Script<br><a href="https://stackoverflow.max-everyday.com/2018/01/mysql-shell-script/">https://stackoverflow.max-everyday.com/2018/01/mysql-shell-script/</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/04/mysql-dump-restore/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Stream a file with tornado</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/stream-a-file-with-tornado/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/stream-a-file-with-tornado/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Tue, 28 Mar 2017 01:32:14 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=397</guid>

					<description><![CDATA[現在手機上的空間往往不夠，所以影片最好就是直接連...]]></description>
										<content:encoded><![CDATA[<p>現在手機上的空間往往不夠，所以影片最好就是直接連到server 上透過串流回來看就好了，在tornado 上串流的 demo:</p>
<p><a href="https://github.com/tornadoweb/tornado/issues/1046">https://github.com/tornadoweb/tornado/issues/1046</a></p>
<p>完整版Source code:<br />
<a href="http://tornado-doc-chs.readthedocs.io/en/latest/_modules/tornado/web.html">http://tornado-doc-chs.readthedocs.io/en/latest/_modules/tornado/web.html</a></p>
<p><span class="k">class</span> <span class="nc">StaticFileHandler</span><span class="p">(</span><span class="n">RequestHandler</span><span class="p">):</span></p>
<hr />
<p>Alright this time I found the actual solution:</p>
<div class="highlight highlight-source-python">
<pre>            <span class="pl-c"># Note: only return HTTP 206 if less than the entire range has been</span>
            <span class="pl-c"># requested. Not only is this semantically correct, but Chrome</span>
            <span class="pl-c"># refuses to play audio if it gets an HTTP 206 in response to</span>
            <span class="pl-c"># ``Range: bytes=0-``.</span></pre>
</div>
<p>This note applies to audio only, chrome will play video that begins be returning a 206.</p>
<div class="highlight highlight-source-python">
<pre>    <span class="pl-en">@asynchronous</span>
    <span class="pl-en">@gen.coroutine</span>
    <span class="pl-k">def</span> <span class="pl-en">get</span>(<span class="pl-smi">self</span>, <span class="pl-smi">path</span>, <span class="pl-smi">include_body</span><span class="pl-k">=</span><span class="pl-c1">True</span>):
        <span class="pl-c">#Assume that path is correct, validation will be handeled elsewhere</span>
        <span class="pl-c1">self</span>.absolute_path <span class="pl-k">=</span> os.path.abspath(path)
        <span class="pl-c1">self</span>.path <span class="pl-k">=</span> <span class="pl-c1">self</span>.absolute_path
        <span class="pl-k">if</span> <span class="pl-c1">self</span>.absolute_path <span class="pl-k">is</span> <span class="pl-c1">None</span>:
            <span class="pl-k">return</span>

        <span class="pl-c1">self</span>.modified <span class="pl-k">=</span> <span class="pl-c1">self</span>.get_modified_time()
        <span class="pl-c1">self</span>.set_headers()

        <span class="pl-k">if</span> <span class="pl-c1">self</span>.should_return_304():
            <span class="pl-c1">self</span>.set_status(<span class="pl-c1">304</span>)
            <span class="pl-k">return</span>

        request_range <span class="pl-k">=</span> <span class="pl-c1">None</span>
        range_header <span class="pl-k">=</span> <span class="pl-c1">self</span>.request.headers.get(<span class="pl-s"><span class="pl-pds">"</span>Range<span class="pl-pds">"</span></span>)
        <span class="pl-k">if</span> range_header:
            <span class="pl-c"># As per RFC 2616 14.16, if an invalid Range header is specified,</span>
            <span class="pl-c"># the request will be treated as if the header didn't exist.</span>
            request_range <span class="pl-k">=</span> httputil._parse_request_range(range_header)

        <span class="pl-k">if</span> request_range:
            start, end <span class="pl-k">=</span> request_range
            size <span class="pl-k">=</span> <span class="pl-c1">self</span>.get_content_size()
            <span class="pl-k">if</span> (start <span class="pl-k">is</span> <span class="pl-k">not</span> <span class="pl-c1">None</span> <span class="pl-k">and</span> start <span class="pl-k">&gt;=</span> size) <span class="pl-k">or</span> end <span class="pl-k">==</span> <span class="pl-c1">0</span>:
                <span class="pl-c"># As per RFC 2616 14.35.1, a range is not satisfiable only: if</span>
                <span class="pl-c"># the first requested byte is equal to or greater than the</span>
                <span class="pl-c"># content, or when a suffix with length 0 is specified</span>
                <span class="pl-c1">self</span>.set_status(<span class="pl-c1">416</span>)  <span class="pl-c"># Range Not Satisfiable</span>
                <span class="pl-c1">self</span>.set_header(<span class="pl-s"><span class="pl-pds">"</span>Content-Type<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>text/plain<span class="pl-pds">"</span></span>)
                <span class="pl-c1">self</span>.set_header(<span class="pl-s"><span class="pl-pds">"</span>Content-Range<span class="pl-pds">"</span></span>, <span class="pl-s"><span class="pl-pds">"</span>bytes */<span class="pl-c1">%s</span><span class="pl-pds">"</span></span> <span class="pl-k">%</span> (size, ))
                <span class="pl-k">return</span>
            <span class="pl-k">if</span> start <span class="pl-k">is</span> <span class="pl-k">not</span> <span class="pl-c1">None</span> <span class="pl-k">and</span> start <span class="pl-k">&lt;</span> <span class="pl-c1">0</span>:
                start <span class="pl-k">+=</span> size
            <span class="pl-k">if</span> end <span class="pl-k">is</span> <span class="pl-k">not</span> <span class="pl-c1">None</span> <span class="pl-k">and</span> end <span class="pl-k">&gt;</span> size:
                <span class="pl-c"># Clients sometimes blindly use a large range to limit their</span>
                <span class="pl-c"># download size; cap the endpoint at the actual file size.</span>
                end <span class="pl-k">=</span> size

            <span class="pl-c1">self</span>.set_status(<span class="pl-c1">206</span>)  <span class="pl-c"># Partial Content</span>
            <span class="pl-c1">self</span>.set_header(<span class="pl-s"><span class="pl-pds">"</span>Content-Range<span class="pl-pds">"</span></span>,
                            httputil._get_content_range(start, end, size))
        <span class="pl-k">else</span>:
            start <span class="pl-k">=</span> end <span class="pl-k">=</span> <span class="pl-c1">None</span>

        content <span class="pl-k">=</span> <span class="pl-c1">self</span>.get_content(<span class="pl-c1">self</span>.absolute_path, start, end)

        <span class="pl-k">for</span> chunk <span class="pl-k">in</span> content:
            <span class="pl-c1">self</span>.write(chunk)
            <span class="pl-k">yield</span> gen.Task(<span class="pl-c1">self</span>.flush)
        <span class="pl-c1">self</span>.finish()
</pre>
</div>
<hr />
<p>related:<br />
HTTP STATUS: 206 PARTIAL CONTENT AND RANGE REQUESTS<br />
<a href="https://benramsey.com/blog/2008/05/206-partial-content-and-range-requests/">https://benramsey.com/blog/2008/05/206-partial-content-and-range-requests/</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/stream-a-file-with-tornado/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ImportError: MemoryLoadLibrary failed loading netifaces.pyd</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/importerror-memoryloadlibrary-failed-loading-netifaces-pyd/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/importerror-memoryloadlibrary-failed-loading-netifaces-pyd/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Sun, 26 Mar 2017 18:24:34 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=394</guid>

					<description><![CDATA[netifaces 在 py2exe 打包情況下...]]></description>
										<content:encoded><![CDATA[<p>netifaces 在 py2exe 打包情況下會出錯：</p>
<p>File &#8220;zipextimporter.pyc&#8221;, line 98, in load_module<br />
ImportError: MemoryLoadLibrary failed loading netifaces.pyd</p>
<p>錯誤畫面載圖：</p>
<p><img fetchpriority="high" decoding="async" class="alignnone size-full wp-image-395" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2017/03/Screenshot-2017-03-27-01.08.39.png" alt="" width="1022" height="360" /></p>
<p>&nbsp;</p>
<p>發生的原因是 py2exe 無法透過 data_files 參數，或 includes 或 packages 這些參數把 netifaces.pyd 打包進去。</p>
<p>由於 py2exe for python 2.7 已經沒有在維護，不建議繼續使用，所以改用python 3 + py2exe 新版，或 pyinstaller + python 2.7.</p>
<p>全部改寫成 python 3 太累，太多 code 要重測，所以切換到 pyinstaller 比較快。</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/importerror-memoryloadlibrary-failed-loading-netifaces-pyd/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to close an ActionMode menu programmatically?</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/how-to-close-an-actionmode-menu-programmatically/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/how-to-close-an-actionmode-menu-programmatically/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 23 Mar 2017 18:36:47 +0000</pubDate>
				<category><![CDATA[Android筆記]]></category>
		<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<category><![CDATA[UI]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=390</guid>

					<description><![CDATA[這個 ActionMode 用起來滿神奇的，他幾...]]></description>
										<content:encoded><![CDATA[<p>這個 ActionMode 用起來滿神奇的，他幾乎算是一個特定區塊的dialog，但是和 dialog 不同的是會和上一個 activity overlap 在一起，並可以存取 parent fragment 或 activity 裡的變數內容，更像是 toolbar 的概念。</p>
<p>要開始／結束 ActionMode 是用：</p>
<p>Whenever you are creating/starting ActionMode Create by</p>
<pre class="default prettyprint prettyprinted"><code><span class="pln">mMode </span><span class="pun">=</span><span class="pln"> startActionMode</span><span class="pun">(....);</span></code></pre>
<p>To Dismiss it use following Syntax</p>
<pre class="default prettyprint prettyprinted"><code><span class="kwd">if</span> <span class="pun">(</span><span class="pln">mMode </span><span class="pun">!=</span> <span class="kwd">null</span><span class="pun">)</span> 
 <span class="pun">{</span><span class="pln">
     mMode</span><span class="pun">.</span><span class="pln">finish</span><span class="pun">();</span>
 <span class="pun">}

</span></code></pre>
<p>from:<br />
<a href="http://stackoverflow.com/questions/11158957/how-to-close-an-actionmode-menu-programmatically-on-honeycomb">http://stackoverflow.com/questions/11158957/how-to-close-an-actionmode-menu-programmatically-on-honeycomb</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/how-to-close-an-actionmode-menu-programmatically/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python tornado multi task</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/python-tornado-multi-task/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/python-tornado-multi-task/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 16 Mar 2017 13:37:54 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[tornado]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=370</guid>

					<description><![CDATA[透過 IOLoop 的add_callback ...]]></description>
										<content:encoded><![CDATA[<p>透過 IOLoop 的add_callback + self.finish() 可以讓 tornado 繼續在背景工作，但有一個問題是前一個工作太忙，會造成整個伺服器無法接受新的 request.</p>
<p>這要寫的有效率，似乎滿難的。</p>
<p>發現把某一個 function 加入 @gen.coroutine，主程式遇到這一個 function 自動變成 muti-thread .. @_@;</p>
<p>&nbsp;</p>
<h4>相關文章：</h4>
<p>Tornado &#8211; getting return value from IOLoop.add_callback()<br />
<a href="http://stackoverflow.com/questions/33742023/tornado-getting-return-value-from-ioloop-add-callback">http://stackoverflow.com/questions/33742023/tornado-getting-return-value-from-ioloop-add-callback</a></p>
<p>I&#8217;m not sure what the difference is between the following two functions:</p>
<pre><code> IOLoop.add_callback(callback, *args, **kwargs) 
</code></pre>
<p>AND</p>
<pre><code>IOLoop.spawn_callback(callback, *args, **kwargs)</code></pre>
<hr />
<p>You can&#8217;t get a return value, at least not in the way you&#8217;re thinking of. Your callback can&#8217;t even run until the function that called <code>spawn_callback</code> (i.e. <code>on_message</code>) returns. Just do whatever you want to do when that callback finishes in the callback itself (or pass it another callback to invoke with its result).</p>
<p><code>stack_context</code> is an error-handling mechanism for callback-oriented code. It doesn&#8217;t let you handle exceptions in the calling function, but it does let you establish an error handler in the calling function that will &#8220;follow&#8221; the code even through a chain of multiple <code>add_callback</code> calls. This turned out to be confusing as often as it helped, so now that coroutines are available I recommend using coroutines as much as possible and when you do need to fall back to raw callbacks, use <code>spawn_callback</code> instead of <code>add_callback</code> and put your try/except handler in the callback itself.</p>
<hr />
<p><a href="https://huangxiaohen2738.gitbooks.io/tornado-tcp-program/content/chapter2-2.html">https://huangxiaohen2738.gitbooks.io/tornado-tcp-program/content/chapter2-2.html</a></p>
<h2 id="22-ioloop的回调函数">2.2 ioloop的回调函数</h2>
<h5 id="1ioloopaddcallbackcallback-args-kwargs">1.IOLoop.add_callback(callback, <em>args, *</em>kwargs)</h5>
<p class="comments-section">这个函数是最简单的，在ioloop开启后执行的回调函数callback，<em>args和*</em>kwargs都是这个回调函数的参数。一般我们的server都是单进程单线程的，即使是多线程，那么这个函数也是安全的。</p>
<h5 id="8ioloopspawncallbackcallback-args-kwargs">8.IOLoop.spawn_callback(callback, <em>args, *</em>kwargs)</h5>
<p class="comments-section">这个函数也是去执行一个回调函数，但是和上面说过的其他callback不同，它和回调者的栈上下文没有关联，因此呢，他比较时候去做一些独立的功能回调。</p>
<hr />
<p>Tornado Execution Order Spawn callback<br />
<a href="http://stackoverflow.com/questions/38696131/tornado-execution-order-spawn-callback">http://stackoverflow.com/questions/38696131/tornado-execution-order-spawn-callback</a></p>
<p>No, in fact you&#8217;re guaranteed that all the functions are spawned before any of them starts running, because <code>first</code> does not <code>yield</code> between spawning <code>func</code> and spawning <code>func2</code>. You can verify this yourself by testing your code:</p>
<pre><code>from tornado import gen, ioloop

@gen.coroutine
def func():
    print('func started')
    yield gen.moment
    print('func done')


@gen.coroutine
def func2():
    print('func2 started')
    yield gen.moment
    print('func2 done')


@gen.coroutine
def first():
    for i in range(2):
        ioloop.IOLoop.current().spawn_callback(func)

    ioloop.IOLoop.current().spawn_callback(func2)
    yield gen.sleep(1)

ioloop.IOLoop.current().run_sync(first)
</code></pre>
<p>It prints:</p>
<pre><code>func started
func started
func2 started
func done
func done
func2 done
</code></pre>
<p>See, <code>func2</code> begins before the coroutines running <code>func</code> complete.</p>
<p>To accomplish what you want:</p>
<pre><code>@gen.coroutine
def first():
    yield [func() for i in range(2)]
    ioloop.IOLoop.current().spawn_callback(func2)
</code></pre>
<p>This prints:</p>
<pre><code>func started
func started
func done
func done
func2 started
func2 done
</code></pre>
<p>If you want <code>first</code> to wait for <code>func2</code> to finish before it exits, then:</p>
<pre><code>@gen.coroutine
def first():
    yield [func() for i in range(2)]
    yield func2()
</code></pre>
<p>For more info on calling coroutines from coroutines, see my <a href="https://emptysqua.re/blog/refactoring-tornado-coroutines/" rel="nofollow">Refactoring Tornado Coroutines</a>.</p>
<hr />
<p>官方文件：</p>
<p><a href="http://www.tornadoweb.org/en/stable/ioloop.html">http://www.tornadoweb.org/en/stable/ioloop.html</a></p>
<p>&nbsp;</p>
<h3>Running in the background</h3>
<p><a class="reference internal" title="tornado.ioloop.PeriodicCallback" href="http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.PeriodicCallback"><code class="xref py py-obj docutils literal"><span class="pre">PeriodicCallback</span></code></a> is not normally used with coroutines. Instead, a coroutine can contain a <code class="docutils literal"><span class="pre">while</span> <span class="pre">True:</span></code> loop and use <a class="reference internal" title="tornado.gen.sleep" href="http://www.tornadoweb.org/en/stable/gen.html#tornado.gen.sleep"><code class="xref py py-obj docutils literal"><span class="pre">tornado.gen.sleep</span></code></a>:</p>
<div class="highlight-python">
<div class="highlight">
<pre><span class="nd">@gen.coroutine</span>
<span class="k">def</span> <span class="nf">minute_loop</span><span class="p">():</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">do_something</span><span class="p">()</span>
        <span class="k">yield</span> <span class="n">gen</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>

<span class="c1"># Coroutines that loop forever are generally started with</span>
<span class="c1"># spawn_callback().</span>
<span class="n">IOLoop</span><span class="o">.</span><span class="n">current</span><span class="p">()</span><span class="o">.</span><span class="n">spawn_callback</span><span class="p">(</span><span class="n">minute_loop</span><span class="p">)</span>
</pre>
</div>
</div>
<p>Sometimes a more complicated loop may be desirable. For example, the previous loop runs every <code class="docutils literal"><span class="pre">60+N</span></code> seconds, where <code class="docutils literal"><span class="pre">N</span></code> is the running time of <code class="docutils literal"><span class="pre">do_something()</span></code>. To run exactly every 60 seconds, use the interleaving pattern from above:</p>
<div class="highlight-python">
<div class="highlight">
<pre><span class="nd">@gen.coroutine</span>
<span class="k">def</span> <span class="nf">minute_loop2</span><span class="p">():</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="n">nxt</span> <span class="o">=</span> <span class="n">gen</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>   <span class="c1"># Start the clock.</span>
        <span class="k">yield</span> <span class="n">do_something</span><span class="p">()</span>  <span class="c1"># Run while the clock is ticking.</span>
        <span class="k">yield</span> <span class="n">nxt</span>             <span class="c1"># Wait for the timer to run out.</span></pre>
</div>
</div>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/python-tornado-multi-task/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python SQLite &#8211; How to manually BEGIN and END transactions?</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/python-sqlite-how-to-manually-begin-and-end-transactions/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/python-sqlite-how-to-manually-begin-and-end-transactions/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 15 Mar 2017 11:19:31 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=362</guid>

					<description><![CDATA[程式愈寫愈複雜，怕資料不一致，所以 connec...]]></description>
										<content:encoded><![CDATA[<p>程式愈寫愈複雜，怕資料不一致，所以 connection 的 isolation_level 設到 None = auto commit mode.</p>
<p>雖然，沒有下 commit() 不會寫到 database 裡，但由於為了效能，我偷偷的把 connection 放在記憶體裡重覆使用，connection 沒有被 close() 掉，所以還在這一個 request 的這一個 begin trans 裡，這一個 request 裡的垃圾，會被queue  在 memory 裡，等下一個 request 的 會把沒有被 commit 的 trans commit 進 database 裡，解法是使用預設的 isolation 遇到 error 就要多執行一次 rollback() 把 queue 在 memory 裡的垃圾清掉。</p>
<p>但，這還是會遇到一個問題，就是其他關於Database 的 Object 被包裝起來，這些 Object 為確保table 一定存在，所以會先執行 create table if. 遇到 create table connect 就被 commit 了。 @_@;</p>
<hr />
<p>I am trying to figure out how to properly override the auto-transaction when using SQLite in Python. When I try and run</p>
<pre class="default prettyprint prettyprinted"><code><span class="pln">cursor</span><span class="pun">.</span><span class="pln">execute</span><span class="pun">(</span><span class="str">"BEGIN;"</span><span class="pun">)</span>
<span class="pun">.....</span><span class="pln">an assortment of insert statements</span><span class="pun">...</span><span class="pln">
cursor</span><span class="pun">.</span><span class="pln">execute</span><span class="pun">(</span><span class="str">"END;"</span><span class="pun">)</span></code></pre>
<p>I get the following error:</p>
<pre class="default prettyprint prettyprinted"><code><span class="typ">OperationalError</span><span class="pun">:</span><span class="pln"> cannot commit </span><span class="pun">-</span> <span class="kwd">no</span><span class="pln"> transaction </span><span class="kwd">is</span><span class="pln"> active</span></code></pre>
<hr />
<p>you have to set isolation level to <code>None</code>. Code example:</p>
<pre class="default prettyprint prettyprinted"><code><span class="pln">s </span><span class="pun">=</span><span class="pln"> sqlite3</span><span class="pun">.</span><span class="pln">connect</span><span class="pun">(</span><span class="str">"./data.db"</span><span class="pun">)</span><span class="pln">
s</span><span class="pun">.</span><span class="pln">isolation_level </span><span class="pun">=</span> <span class="kwd">None</span>

<span class="kwd">try</span><span class="pun">:</span><span class="pln">
    c </span><span class="pun">=</span><span class="pln"> s</span><span class="pun">.</span><span class="pln">cursor</span><span class="pun">()</span><span class="pln">
    c</span><span class="pun">.</span><span class="pln">execute</span><span class="pun">(</span><span class="str">"begin"</span><span class="pun">)</span>
    <span class="pun">...</span><span class="pln">
    c</span><span class="pun">.</span><span class="pln">execute</span><span class="pun">(</span><span class="str">"commit"</span><span class="pun">)</span>
<span class="kwd">except</span><span class="pun">:</span><span class="pln">
    c</span><span class="pun">.</span><span class="pln">execute</span><span class="pun">(</span><span class="str">"rollback"</span><span class="pun">)</span></code></pre>
<hr />
<div class="post-text">
<p>The <a href="https://docs.python.org/2/library/sqlite3.html#controlling-transactions" rel="nofollow">documentaton</a> says:</p>
<blockquote><p>You can control which kind of <code>BEGIN</code> statements sqlite3 implicitly executes (or none at all) via the <em>isolation_level</em> parameter to the connect() call, or via the <em>isolation_level</em> property of connections.</p>
<p>If you want autocommit mode, then set <em>isolation_level</em> to <code>None</code>.</p></blockquote>
</div>
<hr />
<h2>11.13.6. Controlling Transactions<a class="headerlink" title="Permalink to this headline" href="https://docs.python.org/2/library/sqlite3.html#controlling-transactions">¶</a></h2>
<p>By default, the <a class="reference internal" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x." href="https://docs.python.org/2/library/sqlite3.html#module-sqlite3"><code class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></code></a> module opens transactions implicitly before a Data Modification Language (DML) statement (i.e. <code class="docutils literal"><span class="pre">INSERT</span></code>/<code class="docutils literal"><span class="pre">UPDATE</span></code>/<code class="docutils literal"><span class="pre">DELETE</span></code>/<code class="docutils literal"><span class="pre">REPLACE</span></code>), and commits transactions implicitly before a non-DML, non-query statement (i. e. anything other than <code class="docutils literal"><span class="pre">SELECT</span></code> or the aforementioned).</p>
<p>So if you are within a transaction and issue a command like <code class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span> <span class="pre">...</span></code>, <code class="docutils literal"><span class="pre">VACUUM</span></code>, <code class="docutils literal"><span class="pre">PRAGMA</span></code>, the <a class="reference internal" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x." href="https://docs.python.org/2/library/sqlite3.html#module-sqlite3"><code class="xref py py-mod docutils literal"><span class="pre">sqlite3</span></code></a> module will commit implicitly before executing that command. There are two reasons for doing that. The first is that some of these commands don’t work within transactions. The other reason is that sqlite3 needs to keep track of the transaction state (if a transaction is active or not).</p>
<p>You can control which kind of <code class="docutils literal"><span class="pre">BEGIN</span></code> statements sqlite3 implicitly executes (or none at all) via the <em>isolation_level</em> parameter to the <a class="reference internal" title="sqlite3.connect" href="https://docs.python.org/2/library/sqlite3.html#sqlite3.connect"><code class="xref py py-func docutils literal"><span class="pre">connect()</span></code></a> call, or via the <code class="xref py py-attr docutils literal"><span class="pre">isolation_level</span></code> property of connections.</p>
<p>If you want <strong>autocommit mode</strong>, then set <code class="xref py py-attr docutils literal"><span class="pre">isolation_level</span></code> to <code class="docutils literal"><span class="pre">None</span></code>.</p>
<p>Otherwise leave it at its default, which will result in a plain “BEGIN” statement, or set it to one of SQLite’s supported isolation levels: “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”.</p>
<hr />
<p><code class="descname">isolation_level</code></p>
<p>Get or set the current isolation level. <a class="reference internal" title="None" href="https://docs.python.org/2/library/constants.html#None"><code class="xref py py-const docutils literal"><span class="pre">None</span></code></a> for autocommit mode or one of “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”. See section <a class="reference internal" href="https://docs.python.org/2/library/sqlite3.html#sqlite3-controlling-transactions">Controlling Transactions</a> for a more detailed explanation.</p>
<hr />
<dl class="method">
<dt id="sqlite3.Connection.commit"><code class="descname">commit</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd>This method commits the current transaction. If you don’t call this method, anything you did since the last call to <code class="docutils literal"><span class="pre">commit()</span></code> is not visible from other database connections. If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.</dd>
</dl>
<dl class="method">
<dt id="sqlite3.Connection.rollback"><code class="descname">rollback</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd>This method rolls back any changes to the database since the last call to <a class="reference internal" title="sqlite3.Connection.commit" href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.commit"><code class="xref py py-meth docutils literal"><span class="pre">commit()</span></code></a>.</dd>
</dl>
<dl class="method">
<dt id="sqlite3.Connection.close"><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd>This closes the database connection. Note that this does not automatically call <a class="reference internal" title="sqlite3.Connection.commit" href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.commit"><code class="xref py py-meth docutils literal"><span class="pre">commit()</span></code></a>. If you just close your database connection without calling <a class="reference internal" title="sqlite3.Connection.commit" href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.commit"><code class="xref py py-meth docutils literal"><span class="pre">commit()</span></code></a> first, your changes will be lost!</dd>
</dl>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/python-sqlite-how-to-manually-begin-and-end-transactions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Owner delete a folder that contains shared folder</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/owner-delete-a-folder-that-contains-shared-folder/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/owner-delete-a-folder-that-contains-shared-folder/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Tue, 14 Mar 2017 10:16:58 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=359</guid>

					<description><![CDATA[有 shared folder 的父目錄可以被刪...]]></description>
										<content:encoded><![CDATA[<p>有 shared folder 的父目錄可以被刪除嗎？ Dropbox 允許 owner 可以直接刪。刪完之後，別人連進去會看這一個畫面。</p>
<p>在被刪除的路徑上面，建立了一樣的路徑，發現還是連不進去。</p>
<p>把垃圾桶裡的 shared folder restore 回來之後，還是無法透過之前的 hyperlink 連進去 shared folder, 但是 folder 上的圖示顯示還是在 share 狀態。</p>
<p>再去取得該 shared folder 的hyperlink 發現會產生成新的 URL, 這點滿特別的。之前同一個 folder 第1次產生出來的url, 在重新設定 share folder 的屬性後，重新產生 URL, 會取得相目的 URL.</p>
<p>&nbsp;</p>
<p><img decoding="async" class="alignnone size-full wp-image-360" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2017/03/delete_parent_shared_folder.jpg" alt="" width="960" height="1706" /></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/owner-delete-a-folder-that-contains-shared-folder/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python 裡中文目錄與os.path.join問題</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/os-path-join-utf-8/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/os-path-join-utf-8/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Mon, 06 Mar 2017 13:14:06 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=319</guid>

					<description><![CDATA[編碼的問題在 Python 2.x 似乎是有可能...]]></description>
										<content:encoded><![CDATA[<p>編碼的問題在 Python 2.x 似乎是有可能會遇到，在Python 3.x 中，所有字串都以unicode統一處理，而Python 2.x 中用str表示的中文則被稱為bytestream。也就是中文的二進制編碼，相同的檔案名稱在不同的平台可能有不同的表示，具體表示方法由sys.getfilesystemencoding()取得。在 Mac/Linux 應該都是 utf-8, 在 Windows 可能 utf-8 或 ANSI.</p>
<hr />
<pre>os.path.join(path, filename)</pre>
<p>If path and filename are unicodes then everthing will work as expected. But what will happen if filename is an UTF-8 encoded string which contains &#8220;öäü.jpg&#8221;?</p>
<p>Python always uses unicodes to join a string with an unicode. Therefore Python will decode the string with it&#8217;s default encoding (ascii).</p>
<pre>os.path.join(path, filename.decode('ascii'))</pre>
<p>Due to the missing öäü within the ASCII codepage you&#8217;ll get an unicode exception! That&#8217;s the reason why you must explicitly convert the string to unicode!</p>
<pre>os.path.join(path, filename.decode('utf-8'))</pre>
<hr />
<p>Here&#8217;s some interesting stuff from the <a href="http://docs.python.org/library/sys.html#sys.getfilesystemencoding" rel="nofollow">documentation</a>:</p>
<blockquote><p>sys.getfilesystemencoding()</p>
<p>Return the name of the encoding used to convert Unicode filenames into system file names, or None if the system default encoding is used. The result value depends on the operating system: On Mac OS X, the encoding is &#8216;utf-8&#8217;. On Unix, the encoding is the user’s preference according to the result of nl_langinfo(CODESET), or None if the nl_langinfo(CODESET) failed. On Windows NT+, file names are Unicode natively, so no conversion is performed. getfilesystemencoding() still returns &#8216;mbcs&#8217;, as this is the encoding that applications should use when they explicitly want to convert Unicode strings to byte strings that are equivalent when used as file names. On Windows 9x, the encoding is &#8216;mbcs&#8217;.</p>
<p>New in version 2.3.</p></blockquote>
<p>If I understand this correctly, you should pass the file name as unicode:</p>
<pre class="lang-py prettyprint prettyprinted"><code><span class="pln">f </span><span class="pun">=</span><span class="pln"> open</span><span class="pun">(</span><span class="pln">unicode</span><span class="pun">(</span><span class="pln">path</span><span class="pun">,</span><span class="pln"> encoding</span><span class="pun">))</span></code></pre>
<hr />
<p>Python 編碼問題整理<br />
幾個概念性的東西<br />
ANSCII:<br />
標準的 ANSCII 編碼只使用7個比特來表示一個字符，因此最多編碼128個字符。擴充的 ANSCII 使用8個比特來表示一個字符，最多也只能<br />
編碼 256 個字符。<br />
UNICODE:<br />
使用2個甚至4個字節來編碼一個字符，因此可以將世界上所有的字符進行統一編碼。<br />
UTF:<br />
UNICODE編碼轉換格式，就是用來指導如何將 unicode 編碼成適合文件存儲和網絡傳輸的字節序列的形式 (unicode -&gt;<br />
str)。像其他的一些編碼方式 gb2312, gb18030, big5 和 UTF 的作用是一樣的，只是編碼方式不同。<br />
Python 裡面有兩種數據模型來支持字符串這種數據類型，一種是 str，另外一種是 unicode ，它們都是 sequence 的派生類<br />
型，這個可以參考 Python Language Ref 中的描述：</p>
<p>Strings</p>
<blockquote><p>The items of a string are characters. There is no separate<br />
character type; a character is represented by a string of one item.<br />
Characters represent (at least) 8-bit bytes. The built-in functions<br />
chr() and ord() convert between characters and nonnegative integers<br />
representing the byte values. Bytes with the values 0-127 usually<br />
represent the corresponding ASCII values, but the interpretation of<br />
values is up to the program. The string data type is also used to<br />
represent arrays of bytes, e.g., to hold data read from a file.<br />
(On systems whose native character set is not ASCII, strings<br />
may use EBCDIC in their internal representation, provided the<br />
functions chr() and ord() implement a mapping between ASCII and<br />
EBCDIC, and string comparison preserves the ASCII order. Or perhaps<br />
someone can propose a better rule?)</p></blockquote>
<p>Unicode</p>
<blockquote><p>The items of a Unicode object are Unicode code units. A<br />
Unicode code unit is represented by a Unicode object of one item and<br />
can hold either a 16-bit or 32-bit value representing a Unicode<br />
ordinal (the maximum value for the ordinal is given in sys.maxunicode,<br />
and depends on how Python is configured at compile time). Surrogate<br />
pairs may be present in the Unicode object, and will be reported as<br />
two separate items. The built-in functions unichr() and ord() convert<br />
between code units and nonnegative integers representing the Unicode<br />
ordinals as defined in the Unicode Standard 3.0. Conversion from and<br />
to other encodings are possible through the Unicode method encode()<br />
and the built-in function unicode().</p></blockquote>
<pre>這裡面是這麼幾句：
 "The items of a string are characters", "The items of a Unicode object
 are Unicode code units", "The string data type is also used to
 represent arrays of bytes, e.g., to hold data read from a file."
 一二句說明 str 和 unicode 的組成單元(item)是什麼（因為它們同是 sequence ) 。sequence 默認的
 __len__ 函數的返回值正是該序列組成單元的個數。這樣的話，len('abcd') == 4 和 len(u'我是中文') == 4 就很
 容易理解了。
 第三句告訴我們像從文件輸入輸出的時候是用 str 來表示數據的數組。不止是文件操作，我想在網絡傳輸的時候應該也是這樣的。這就是為什麼一個
 unicode 字符串在寫入文件或者在網絡上傳輸的時候要進行編碼的原因了。
 Python 裡面的編碼和解碼也就是 unicode 和 str 這兩種形式的相互轉化。編碼是 unicode -&gt; str，相反的，解碼就
 是 str -&gt; unicode。
 下面剩下的問題就是確定何時需要進行編碼或者解碼了，像一些庫是 unicode 版的，這樣我們在將這些庫函數的返回值進行傳輸或者寫入文件的時候就
 要考慮將它編碼成合適的類型。
 關於文件開頭的"編碼指示"，也就是 # -*- coding: -*- 這個語句。Python 默認腳本文件都是 ANSCII 編碼的，當文件
 中有非 ANSCII 編碼範圍內的字符的時候就要使用"編碼指示"來修正。
 關於 sys.defaultencoding，這個在解碼沒有明確指明解碼方式的時候使用。比如我有如下代碼：
 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 s = '中文' # 注意這裡的 str 是 str 類型的，而不是 unicode
 s.encode('gb18030')
 這句代碼將 s 重新編碼為 gb18030 的格式，即進行 unicode -&gt; str 的轉換。因為 s 本身就是 str 類型的，因此
 Python 會自動的先將 s 解碼為 unicode ，然後再編碼成 gb18030。因為解碼是python自動進行的，我們沒有指明解碼方
 式，python 就會使用 sys.defaultencoding 指明的方式來解碼。很多情況下 sys.defaultencoding 是
 ANSCII，如果 s 不是這個類型就會出錯。
 拿上面的情況來說，我的 sys.defaultencoding 是 anscii，而 s 的編碼方式和文件的編碼方式一致，是 utf8 的，所
 以出錯了:
 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position
 0: ordinal not in range(128)
 對於這種情況，我們有兩種方法來改正錯誤：
 一是明確的指示出 s 的編碼方式
 #! /usr/bin/env python
 # -*- coding: utf-8 -*-
 s = '中文'
 s.decode('utf-8').encode('gb18030')</pre>
<hr />
<p>python 2中是將字串分作 str及Unicode兩種物件，&#8221;中文&#8221;這個字串實例建立時是處在 UTF-8編碼的狀態。若想要得到&#8221;中文&#8221;二字的 Unicode，你可以透過 .decode()來實現。另外，你也可以在字串前面加上一個英文字母 u，如u&#8221;中文&#8221;，來直接建立一個 unicode物件的實例。</p>
<h3>input ###</h3>
<pre>print type("中文")
print type("中文".decode("utf-8"))
print type(u"中文")</pre>
<h3>output ###</h3>
<pre>type 'str'
type 'unicode'
type 'unicode'</pre>
<p>當你想要從 UTF-8編碼狀態轉換成 Big5編碼狀態時，你必需要將編碼狀態的字串先解碼成 Unicode後，再重新編碼成 Big5的編碼狀態才能成功。</p>
<pre>print "中文" # encoded in utf-8
print "中文".decode("utf-8").encode("big5") # encoded in big5</pre>
<p>編碼不同除了造成亂碼之外，也會造成文本分析的錯誤，最明顯的例子就是計算字數的問題。當你用 len()這個內建的函式(built-in function)來計算&#8221;中文&#8221;這個字串有幾個字時，你會發現結果並不是預期的 2而是 6。</p>
<h3>input ###</h3>
<pre>print len("中文")
print len("中文".decode("utf-8"))
print len(u"中文")</pre>
<h3>output ###</h3>
<pre>6
2
2</pre>
<p>這跟 len()這個函式演算法的設計有關，當字串是編碼狀態時就會無法得到正確的字數。若要修正這個問題，請記得一定要以 unicode去計算才會得到正確的結果。這也是為什麼許多中文處理套件的第一步總是先將字串轉換成 unicode的原因。</p>
<hr />
<p>python 3中是將字串分作 str及 byte兩種物件，分別對應到 Unicode以及編碼狀態。你發現差異了嗎？這就表示說，當你建立一個字串實例如&#8221;中文&#8221;時，這個字串就會是 Unicode的文字了。以 Unicode優先的這種設計避掉了許多因編碼不同而挖的坑，像是前面舉例使用 len()計算字數的問題。</p>
<h3>input ###</h3>
<pre>print(type("中文"))
print(type("中文".encode("utf-8")))
print(type(u"中文"))
print(len("中文"))</pre>
<h3>output ###</h3>
<pre>class 'str'
class 'bytes'
class 'str'
2</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h4>資料來源：</h4>
<p>Python not able to open file with non-english characters in path<br />
<a href="http://stackoverflow.com/questions/2004137/unicodeencodeerror-on-joining-file-name">http://stackoverflow.com/questions/2004137/unicodeencodeerror-on-joining-file-name</a></p>
<p>python os.walk filename ‘ascii’ codec can’t decode<br />
<a href="https://stackoverflow.max-everyday.com/2017/03/os-walk-filename-ascii-codec-cant-decode/">https://stackoverflow.max-everyday.com/2017/03/os-walk-filename-ascii-codec-cant-decode/</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/os-path-join-utf-8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>FasterXML/jackson</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/fasterxml-jackson/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/fasterxml-jackson/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Mon, 06 Mar 2017 02:51:59 +0000</pubDate>
				<category><![CDATA[Android筆記]]></category>
		<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=322</guid>

					<description><![CDATA[想要 在Android 裡使用編碼過的json。...]]></description>
										<content:encoded><![CDATA[<p>想要 在Android 裡使用編碼過的json。由於 JSONObject  的 toString() 是沒編碼過的，直接放到 URL 或 header 裡，送到 server side 不知道為什麼解不開來, 只好先在 json 裡encode 成 ascii.</p>
<p>官方網站：<br />
<a href="https://github.com/FasterXML/jackson-databind">https://github.com/FasterXML/jackson-databind</a></p>
<p>使用範例：<br />
<a href="http://stackoverflow.com/questions/23121765/write-objectnode-to-json-string-with-utf-8-characters-to-escaped-ascii">http://stackoverflow.com/questions/23121765/write-objectnode-to-json-string-with-utf-8-characters-to-escaped-ascii</a></p>
<p>You should enable the JsonGenerator feature which controls the escaping of the non-ASCII characters. Here is an example:</p>
<pre class="lang-java prettyprint prettyprinted"><code>    <span class="typ">ObjectMapper</span><span class="pln"> mapper </span><span class="pun">=</span> <span class="kwd">new</span> <span class="typ">ObjectMapper</span><span class="pun">();</span><span class="pln">
    mapper</span><span class="pun">.</span><span class="pln">getFactory</span><span class="pun">().</span><span class="pln">configure</span><span class="pun">(</span><span class="typ">JsonGenerator</span><span class="pun">.</span><span class="typ">Feature</span><span class="pun">.</span><span class="pln">ESCAPE_NON_ASCII</span><span class="pun">,</span> <span class="kwd">true</span><span class="pun">);</span>
    <span class="typ">ObjectNode</span><span class="pln"> node </span><span class="pun">=</span><span class="pln"> mapper</span><span class="pun">.</span><span class="pln">getNodeFactory</span><span class="pun">().</span><span class="pln">objectNode</span><span class="pun">();</span><span class="pln">
    node</span><span class="pun">.</span><span class="pln">put</span><span class="pun">(</span><span class="str">"field1"</span><span class="pun">,</span> <span class="str">"Maël Hörz"</span><span class="pun">);</span>
    <span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="pln">mapper</span><span class="pun">.</span><span class="pln">writeValueAsString</span><span class="pun">(</span><span class="pln">node</span><span class="pun">));</span></code></pre>
<p>The output is:</p>
<pre class="lang-java prettyprint prettyprinted"><code><span class="pun">{</span><span class="str">"field1"</span><span class="pun">:</span><span class="str">"Ma\u00EBl H\u00F6rz"</span><span class="pun">}</span></code></pre>
<hr />
<p>arg build-in:{&#8220;path&#8221;:&#8221;\<span style="color: #ff0000;"><strong>/中文字\/abc\/IMG_20170224_211551.jpg</strong></span>&#8220;,&#8221;client_modified&#8221;:1487942151,&#8221;platform&#8221;:&#8221;android&#8221;,&#8221;device_id&#8221;:&#8221;b131f953c8fa34c3&#8243;,&#8221;device_name&#8221;:&#8221;MI 3W&#8221;,&#8221;client_version&#8221;:&#8221;1.0&#8243;,&#8221;platform_version&#8221;:&#8221;6.0.1&#8243;,&#8221;language&#8221;:&#8221;en_US&#8221;}</p>
<p>arg jackson:{&#8220;path&#8221;:&#8221;<span style="color: #ff0000;"><strong>/\u4E2D\u6587\u5B57/abc/IMG_20170224_211551.jpg</strong></span>&#8220;,&#8221;client_modified&#8221;:1487942151}</p>
<p><img decoding="async" class="alignnone size-full wp-image-323" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2017/03/Screenshot-2017-03-06-10.50.37.png" alt="" width="1230" height="244" /></p>
<hr />
<p>加入到 Android Stuiod：</p>
<pre class="default prettyprint prettyprinted"><code><span class="pln">compile </span><span class="str">'com.fasterxml.jackson.core:jackson-core:2.7.3'</span><span class="pln">
compile </span><span class="str">'com.fasterxml.jackson.core:jackson-annotations:2.7.3'</span><span class="pln">
compile </span><span class="str">'com.fasterxml.jackson.core:jackson-databind:2.7.3'</span></code></pre>
<p>Following android studio conventions. You can find the up to date version at: <a href="http://search.maven.org/#search%7Cga%7C1%7Ccom.fasterxml.jackson.core">Maven Central Repository</a>.</p>
<hr />
<p>Build 起來會遇到 Error:</p>
<p>“Duplicate files copied in APK META-INF/*”</p>
<p>解法：</p>
<p>Add following into respective build.gradle file</p>
<pre class="lang-java prettyprint prettyprinted"><code><span class="pln">packagingOptions </span><span class="pun">{</span><span class="pln">
        exclude </span><span class="str">'META-INF/ASL2.0'</span><span class="pln">
        exclude </span><span class="str">'META-INF/LICENSE'</span><span class="pln">
        exclude </span><span class="str">'META-INF/NOTICE'</span><span class="pln">
        exclude </span><span class="str">'META-INF/NOTICE.txt'</span><span class="pln">
        exclude </span><span class="str">'META-INF/LICENSE.txt'</span><span class="pln">
        exclude </span><span class="str">'META-INF/MANIFEST.MF'</span>
    <span class="pun">}</span></code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/fasterxml-jackson/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>nginx 無法 proxy_pass header 301 302</title>
		<link>https://stackoverflow.max-everyday.com/2017/03/nginx-proxy_pass-301-302/</link>
					<comments>https://stackoverflow.max-everyday.com/2017/03/nginx-proxy_pass-301-302/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 03 Mar 2017 02:50:05 +0000</pubDate>
				<category><![CDATA[Dropboxlike開發筆記]]></category>
		<category><![CDATA[電腦相關應用]]></category>
		<category><![CDATA[DigitalOcean]]></category>
		<category><![CDATA[Dropboxlike]]></category>
		<guid isPermaLink="false">http://stackoverflow.max-everyday.com/?p=310</guid>

					<description><![CDATA[官方說明文件： https://www.ngin...]]></description>
										<content:encoded><![CDATA[<p>官方說明文件：<br />
<a href="https://www.nginx.com/blog/creating-nginx-rewrite-rules/">https://www.nginx.com/blog/creating-nginx-rewrite-rules/</a></p>
<p>&nbsp;</p>
<p>解法：</p>
<p>This is not ideal and it would be far better to have a clean workflow instead of doing this. But for curiosity, this could be informative to people that would wonder if it&#8217;s possible.</p>
<p><strong>Yes it is</strong>, using a combination of <code>error_page</code>, <code>rewrite</code>, <code>map</code>, <code>proxy_intercept_errors</code> and <code>proxy_redirect</code> directives and <code>$upstream_http</code> var pattern.</p>
<p>Keep in mind that it&#8217;s going far off the path nginx is designed to be driven on.</p>
<pre><code>map $upstream_http_location $redirect_uri {
    "~http://[^/]+/(?&lt;location_uri&gt;.*)$" "$location_uri";
}

upstream origin {
    server origin1.com;
}

server {

    listen 80;
    server_name nginx-front.com;

    proxy_set_header Host "origin1.com";
    proxy_redirect http://origin1.com/ /;

    location ~ ^/hls/(\w+)\.mp4\.m3u8$ {
        proxy_pass http://origin/m3ugen/segsrc/$1.mp4;
        proxy_intercept_errors on;
        error_page 301 302 = @handler;    
    }

    location @handler {
        rewrite ^ /$redirect_uri break;
        proxy_pass http://origin;
    }

}</code></pre>
<hr />
<div class="post-text">
<p>It is possible for <code>nginx</code> to intercept the 302 response code and process internally. I set up a test scenario which worked using this:</p>
<pre><code>location /some/uri/ {
    error_page 302 = @fallback;
    proxy_intercept_errors on;
    proxy_pass ...;
}
location @fallback {
    rewrite ^ /some/other/uri last;
}
</code></pre>
<p>This would of course be a blanket intercept without regard for the value of the response headers, but that may be adequate for your requirement. See <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page" rel="nofollow noreferrer">this</a> and <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors" rel="nofollow noreferrer">this</a> for more.</p>
<hr />
</div>
<p>I succeeded in solving a more generic case when a redirect location can be any external URL.</p>
<pre><code>server {
    ...

    location / {
        proxy_pass http://backend;
        # You may need to uncomment the following line if your redirects are relative, e.g. /foo/bar
        #proxy_redirect / /;
        proxy_intercept_errors on;
        error_page 301 302 307 = @handle_redirects;
    }

    location @handle_redirects {
        set $saved_redirect_location '$upstream_http_location';
        proxy_pass $saved_redirect_location;
    }
}
</code></pre>
<p>Alternative approach, which is closer to what you describe, is covered in ServerFault answer to this question: <a href="http://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally">http://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally</a></p>
<p>&nbsp;</p>
<p>修改 sample:<br />
<a href="https://gist.github.com/sirsquidness/710bc76d7bbc734c7a3ff69c6b8ff591">https://gist.github.com/sirsquidness/710bc76d7bbc734c7a3ff69c6b8ff591</a></p>
<p>&nbsp;</p>
<p>資料來源：<br />
<a href="http://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally">http://serverfault.com/questions/641070/nginx-302-redirect-resolve-internally</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2017/03/nginx-proxy_pass-301-302/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
