id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34,570,452 | node.js stdout clearline() and cursorTo() functions | <p>From a node.js tutorial, I see those two process.stdout functions : </p>
<pre><code>process.stdout.clearLine();
process.stdout.cursorTo(0);
</code></pre>
<p>But I'm using a more recent node.js version (4.2.4), and those functions do not exist. I get <code>process.stdout.clearLine is not a function</code> and <code>process.stdout.cursorTo is not a function</code>.</p>
<p>What is the equivalent of clearLine and cursorTo on node.js version 4.2.4 ?</p>
<p>EDIT : </p>
<p>Those are not working either : </p>
<pre><code>process.readline.clearLine();
process.readline.cursorTo(0);
function writeWaitingPercent(p) {
process.readline.clearLine();
process.readline.cursorTo(0);
process.stdout.write(`waiting ... ${p}%`);
}
</code></pre>
<p>I get <code>Cannot read property 'clearLine' of undefined</code></p> | 34,570,694 | 5 | 0 | null | 2016-01-02 20:33:23.943 UTC | 8 | 2020-11-24 10:46:07.973 UTC | 2016-01-02 20:55:16.65 UTC | null | 1,904,386 | null | 1,904,386 | null | 1 | 42 | node.js | 34,335 | <p>This is the solution : </p>
<p>First, require readline : </p>
<pre><code>var readline = require('readline');
</code></pre>
<p>Then, use cursorTo like this : </p>
<pre><code>function writeWaitingPercent(p) {
//readline.clearLine(process.stdout);
readline.cursorTo(process.stdout, 0);
process.stdout.write(`waiting ... ${p}%`);
}
</code></pre>
<p>I've commented clearLine, since it's useless in my case (cursorTo move back the cursor to the start)</p> |
34,522,053 | What is the maximum message length for a MQTT broker? | <p>I am using the node.js mosca MQTT broker for some internet of things (iot) application.</p>
<p><a href="https://github.com/mcollina/mosca" rel="noreferrer">https://github.com/mcollina/mosca</a></p>
<p>What is the maximum message length that a topic can receive for the mosca broker? What are the factors that constrain the message length? </p>
<p>If I want to increase the message length, is there a configuration parameter I can modify or which part of the code can I change?</p> | 34,525,013 | 1 | 0 | null | 2015-12-30 02:17:35.307 UTC | 7 | 2016-07-01 13:12:27.167 UTC | null | null | null | null | 1,709,088 | null | 1 | 31 | node.js|mqtt|iot | 42,351 | <p>It's not entirely clear what you're asking here, so I'll answer both possibilities.</p>
<p>The length of the actual topic string is at most 65536 bytes. This is a limit imposed by the mqtt spec, you can't change it. It is also worth noting that the topic is encoded with utf-8, so you may have less than 65536 characters available.</p>
<p>The payload of the message is limited to 268,435,456 bytes. Again, this is defined by the spec.</p>
<p>If you are routinely approaching either of these limits you should be thinking about whether what you are doing is sensible.</p> |
44,493,815 | Angular2 - Only Allow Alpha Characters TO Be Entered In An Input | <p>I am very new to <code>Angular2</code> and cant seem to find my answer anywhere. I have an <code>input</code> (as show below) but I only want it to allow the following:</p>
<ul>
<li>A-Z</li>
<li>a-z</li>
<li>'</li>
<li>-</li>
<li>[SPACE]</li>
</ul>
<p>I have no idea on how to do this. I have tried <code>ng-pattern="/^[a-zA-Z\s]*$/"</code>, <code>pattern="/^[a-zA-Z\s]*$/"</code> and <code>ng-pattern-restrict="/^[a-zA-Z\s]*$/"</code>.</p>
<p><strong>HTML</strong></p>
<pre><code><td>
<md-input-container>
<input mdInput [(ngModel)]="details.firstName" placeholder="First name(s)" ng-pattern="/^[a-zA-Z\s]*$/">
</md-input-container>
</td>
</code></pre>
<p>Ideally if a user enters a numeric character, I'd ether like it to be removed by itself or just not be allowed (not displayed) in the field</p> | 44,514,455 | 5 | 0 | null | 2017-06-12 07:37:25.637 UTC | null | 2020-03-26 13:31:05.287 UTC | 2017-06-12 09:26:39.397 UTC | null | 4,450,893 | null | 3,194,213 | null | 1 | 8 | angular|angular2-forms|angular2-directives | 58,740 | <p>My fix was to do it in my component</p>
<pre><code>firstName: ['', Validators.pattern('^[a-zA-Z \-\']+')],
</code></pre> |
26,981,907 | Using ansible to manage disk space | <p>Simple ask: I want to delete some files if partition utilization goes over a certain percentage.</p>
<p>I have access to "size_total" and "size_available" via "ansible_mounts". i.e.:</p>
<pre><code>ansible myhost -m setup -a 'filter=ansible_mounts'
myhost | success >> {
"ansible_facts": {
"ansible_mounts": [
{
"device": "/dev/mapper/RootVolGroup00-lv_root",
"fstype": "ext4",
"mount": "/",
"options": "rw",
"size_available": 5033046016,
"size_total": 8455118848
},
</code></pre>
<p>How do I access those values, and how would I perform actions conditionally based on them using Ansible?</p> | 31,153,324 | 4 | 0 | null | 2014-11-17 21:02:13.897 UTC | 4 | 2017-04-12 22:55:28.247 UTC | null | null | null | null | 69,152 | null | 1 | 12 | ansible | 40,545 | <p>Slava's answer definitely was on the right track, here is what I used:</p>
<pre><code>- name: test for available disk space
assert:
that:
- not {{ item.mount == '/' and ( item.size_available < item.size_total - ( item.size_total|float * 0.8 ) ) }}
- not {{ item.mount == '/var' and ( item.size_available < item.size_total - ( item.size_total|float * 0.8 ) ) }}
with_items: ansible_mounts
ignore_errors: yes
register: disk_free
- name: free disk space
command: "/some/command/that/fixes/it"
when: disk_free|failed
</code></pre>
<p>The assert task simply tests for a condition, by setting ignore_errors, and registering the result of the test to a new variable we can perform a conditional task later in the play instead of just failing when the result of the assert fails.</p>
<p>The tests themselves could probably be written more efficiently, but at the cost of readability. So I didn't use a multiple-list loop in the example. In this case the task loops over each item in the list of mounted filesystems (an ansible-created fact, called ansible_mounts.)</p>
<p>By negating the test we avoid failing on file system mounts not in our list, then simple math handles the rest. The part that tripped me up was that the size_available and size_total variables were strings, so a jinja filter converts them to a float before calculating the percentage.</p> |
38,795,103 | Encrypt String in .NET Core | <p>I would like to encrypt a string in .NET Core using a key. I have a client / server scenario and would like to encrypt a string on the client, send it to the server and decrypt it. </p>
<p>As .NET Core is still in a early stage (e.g. Rijndael is not yet available), what are my options? </p> | 38,797,581 | 7 | 2 | null | 2016-08-05 17:46:24.237 UTC | 11 | 2022-01-17 15:26:39.663 UTC | null | null | null | null | 479,659 | null | 1 | 39 | c#|encryption|.net-core | 86,733 | <p>You really shouldn't ever use Rijndael/RijndaelManaged in .NET. If you're using it with a BlockSize value of 128 (which is the default) then you're using AES, as I <a href="https://stackoverflow.com/a/38399658/6535399">explained in a similar question</a>.</p>
<p>The symmetric encryption options available in .NET Core are:</p>
<ul>
<li>AES (System.Security.Cryptography.Aes.Create())</li>
<li>3DES (System.Security.Cryptography.TripleDES.Create())</li>
</ul>
<p>And for asymmetric encryption</p>
<ul>
<li>RSA (System.Security.Cryptography.RSA.Create())</li>
</ul>
<p>Especially on .NET Core the factories are the best way to go, because they will give back an object which works on the currently executing operating system. For example, RSACng is a public type but only works on Windows; and RSAOpenSsl is a public type but is only supported on Linux and macOS.</p> |
41,965,720 | Git clone a branch, not master | <p>I use Git Bash for bitbucket. I have created a brunch and I pushed some commits, other people pushed commits in master.
Now I am on a different machine. I want to clone or download the solution of the latest commit of my branch and not the master? How can I do that?</p> | 41,965,807 | 3 | 0 | null | 2017-01-31 19:16:21.317 UTC | 8 | 2021-12-21 13:26:19.807 UTC | 2021-12-21 13:26:19.807 UTC | null | 1,279,459 | null | 3,703,803 | null | 1 | 16 | git|branch|bitbucket|git-bash|git-clone | 75,366 | <p>I think you are looking for the <code>--branch</code> option to <code>git clone</code>, which allows you to specify which branch is initially checked out in the cloned repository.</p>
<pre><code>git clone --branch mybranch $URL/foo
</code></pre>
<p>is roughly equivalent to </p>
<pre><code>git clone $URL/foo
cd foo
git checkout mybranch
cd ..
</code></pre> |
6,083,183 | jQuery find $.find('selector') versus $('selector') difference | <p>I've got a question why these two code snippets are different.</p>
<pre><code>$('#ctl00_DDMenu1_HyperLink1')
//jQuery(a#ctl00_DDMenu1_HyperLink1 Default.aspx) Console output
$('#ctl00_DDMenu1_HyperLink1').text()
</code></pre>
<p>The code above returns : <code>Some link text</code></p>
<p>But</p>
<pre><code>$.find('#ctl00_DDMenu1_HyperLink1')
//[a#ctl00_DDMenu1_HyperLink1 Default.aspx] Consolee output
$.find('#ctl00_DDMenu1_HyperLink1').text()
</code></pre>
<p>Returns</p>
<blockquote>
<p>TypeError: <code>$.find("#ctl00_DDMenu1_HyperLink1").text</code> is not a function</p>
</blockquote>
<p>Does this mean that <strong><code>$.find</code></strong> return Array object <code>[]</code> and jQuery functions are not accessible?</p>
<h2>//EDIT</h2>
<p>I've used jQuery 1.4.2 & used Firebug Console.</p>
<h2>//Answer found by practise</h2>
<p>This code will return <strong>jQuery object reference</strong> and all jQuery function are accessible.</p>
<p><code>$('any_selector')<br>
//jQuery(item1),jQuery(item2),...,jQuery(item-N) Console output
$('any_selector').text()</code></p>
<p>This code return <strong>JavaScript Array object</strong> so any function of jQuery cannot be applied to resultset. Even when resultset seems to be identical.</p>
<p><code>$.find('any_selector')<br>
//[item1,item2,...,item-N] Consolee output<br>
$.find('any_selector').text()</code></p>
<p>But we can do trick (weird trick) to wrapp js Array into jQuery selector:</p>
<p><code>$($.find('any_selector_as_inner_select')).val()</code></p>
<p><strong>//Thanks for help guys!</strong></p> | 6,083,231 | 1 | 2 | null | 2011-05-21 16:59:59.057 UTC | 3 | 2011-05-21 17:54:41.897 UTC | 2011-05-21 17:54:41.897 UTC | null | 532,205 | null | 532,205 | null | 1 | 16 | jquery|find|css-selectors | 49,042 | <p>The reason this does not work is because <code>find()</code> lets you filter on a set of elements based on a selection you've already made.For example if you wanted to select all of the inputs within a particular form, you could write:</p>
<pre><code>$('#aParticularForm').find('input')
</code></pre>
<p>It cannot be called on its own.</p> |
5,863,162 | Entity Framework Mapping SQL Server tinyint to Int16 | <p>My Entity Data Model is giving me this error:</p>
<blockquote>
<p>Error 2019: Member Mapping specified
is not valid. The type
'Edm.Int16[Nullable=True,DefaultValue=]'
of ... is not compatible with
'SqlServer.tinyint[Nullable=True,DefaultValue=]'
of ...</p>
</blockquote>
<p>I've tried deleting and recreating the property. I don't know what I've done wrong.</p> | 5,863,182 | 1 | 0 | null | 2011-05-02 22:28:07.28 UTC | 4 | 2017-04-10 18:12:03.497 UTC | null | null | null | null | 83 | null | 1 | 37 | sql-server|entity-framework|types | 26,180 | <p>A <code>tinyint</code> should get mapped to a .NET <code>byte</code>; <code>Int16</code> should be the corresponding type for a <code>smallint</code> in SQL.</p> |
2,471,980 | concatenating string in classic asp | <p>I am trying to concatenate image url (string) with img tag but i am not sure how to put " after src=. Please help to concatenate this.</p>
<pre><code>response.write("<img src=" & '"' & rs("ProductImage") & '"' &" /><br/>")
</code></pre> | 2,471,994 | 3 | 0 | null | 2010-03-18 17:23:27.45 UTC | null | 2016-05-16 16:20:42.627 UTC | null | null | null | null | 146,603 | null | 1 | 7 | asp-classic | 38,323 | <p>You have to double up the quotes:</p>
<pre><code>Response.Write("<img src=""" & rs("ProductImage") & """ /><br/>")
</code></pre> |
38,958,876 | Can OpenCV for Android leverage the standard C++ Support to get native build support on Android Studio 2.2 for Windows? | <p>There are many questions and answers surrounding getting native opencv for android building properly. Some use gradle, others use external tools. These numerous, complicated, and often conflicting descriptions for native OpenCV builds might be simplified with a consistent starting point; when creating an Android Studio 2.2 Beta project, there is an way to include C++ support:
<a href="https://i.stack.imgur.com/omtsa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/omtsa.png" alt="Include C++ Support"></a><a href="https://i.stack.imgur.com/iMZ4e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iMZ4e.png" alt="enter image description here"></a></p>
<p>This feature was added around June of 2016. See <a href="http://tools.android.com/tech-docs/external-c-builds" rel="noreferrer">Android tools technical docs</a> for more information.</p>
<blockquote>
<p>Using Android Studio 2.2 or higher with the Android plugin for Gradle version 2.2.0 or higher, you can add C and C++ code to your app by compiling it into a native library that Gradle can package with your APK. Your Java code can then call functions in your native library through the Java Native Interface (JNI). If you want to learn more about using the JNI framework, read JNI tips for Android. </p>
</blockquote>
<p>Checking the <code>Include C++ Support</code> generates an external build file called <code>CMakeLists.txt</code>.</p>
<pre><code># Sets the minimum version of CMake required to build the native
# library. You should either keep the default value or only pass a
# value of 3.4.0 or lower.
cmake_minimum_required(VERSION 3.4.1)
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds it for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
native-lib
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file(s).
# Associated headers in the same location as their source
# file are automatically included.
src/main/cpp/native-lib.cpp )
# Searches for a specified prebuilt library and stores the path as a
# variable. Because system libraries are included in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log )
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in the
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
native-lib
# Links the target library to the log library
# included in the NDK.
$\{log-lib} )
</code></pre>
<p>To recognize an Android project that uses native (C++) OpenCV code, the project will typically include a <code>*.cpp</code> file containing <code>JNIEXPORT</code> entries along with implementations that use <code>#include <opencv...hpp></code> functionality. This, as opposed to importing the OpenCV module and copying the libs folder into jniLibs, which only allows calling OpenCV functionality from Java.</p>
<p>Is it possible to use this starting point to configure a OpenCV native 'hello world' app, proving the build is working?</p>
<p><strong>ADDITIONAL INFORMATION 8/22</strong><br>
Since this puzzle is about <code>CMake</code> and less about OpenCV, I thought I'd give out a project starting point for those not interested in OpenCV. You could get the starting point project going reasonably quickly using the information in <a href="https://stackoverflow.com/questions/27406303/opencv-in-android-studio">OpenCV in Android Studio</a>.</p>
<p>Here is a <a href="https://www.youtube.com/watch?v=Vp20EdU5qjU" rel="noreferrer"><strong>youtube video</strong></a> that shows the creation of a new Android Studio project, importing OpenCV, configuring the native C++ build, resulting in the OpenCV "hello world" application that's equal to the one in gitHub.</p>
<p><strong>ADDITIONAL INFORMATION 8/27</strong><br>
The version committed today, based on the answer from Bruno Alexandre Krinski <strong>does compile</strong> native OpenCV calls: <a href="https://github.com/sengsational/HelloCv" rel="noreferrer">https://github.com/sengsational/HelloCv</a> . There is a separate problem concerning the "Installation Blocked" message, where, upon installation, Android warns the user "This app contains code that attempts to bypass Android's security protections." Since I am unsure that this is an issue with the build technique, I will not expand this question to include that issue (but if someone has input on that problem, please advise).</p>
<pre><code>#Added 2 path definitions to support 20160825 additions
set(pathToProject C:/Users/Owner/AndroidStudioProjects/HelloCv)
set(pathToOpenCv C:/Users/Owner/OpenCV-3.1.0-android-sdk)
#Added by the IDE on project create
cmake_minimum_required(VERSION 3.4.1)
#Two sets suggested by Bruno Alexandre Krinski 20160825
set(CMAKE_VERBOSE_MAKEFILE on)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
#Addition suggested by Bruno Alexandre Krinski 20160825
include_directories(${pathToOpenCv}/sdk/native/jni/include)
#Added by IDE on project create
add_library( native-lib SHARED src/main/cpp/native-lib.cpp )
#Addition suggested by Bruno Alexandre Krinski 20160825
add_library( lib_opencv SHARED IMPORTED )
#Addition suggested by Bruno Alexandre Krinski 20160825
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION ${pathToProject}/app/src/main/jniLibs/${ANDROID_ABI}/libopencv_java3.so)
#Added by IDE on project create
find_library( log-lib log )
#Added by IDE on project create, Removed and replace with additional parameter suggested by Bruno Alexandre Krinski 20160825
#target_link_libraries( native-lib $\{log-lib} )
target_link_libraries( native-lib $\{log-lib} lib_opencv)
</code></pre> | 39,008,816 | 4 | 7 | null | 2016-08-15 16:18:14.98 UTC | 14 | 2022-09-05 17:28:06.013 UTC | 2022-09-05 17:28:06.013 UTC | null | 6,885,902 | null | 897,007 | null | 1 | 28 | android|windows|opencv|cmake|java-native-interface | 12,061 | <p>It seems you already have imported the opencv module, now, open your CMakeList.txt and add the follow lines:</p>
<pre><code>set(CMAKE_VERBOSE_MAKEFILE on)
add_library(lib_opencv SHARED IMPORTED)
set_target_properties(lib_opencv PROPERTIES IMPORTED_LOCATION
path-to-your-project/MyApplication/app/src/main/jniLibs/${ANDROID_ABI}/libopencv_java3.so)
include_directories(path-to-opencv-directory/OpenCV-android-sdk/sdk/native/jni/include)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")
</code></pre>
<p>and edit the:</p>
<pre><code>target_link_libraries( # Specifies the target library.
native-lib
lib_opencv
# Links the target library to the log library
# included in the NDK.
$\{log-lib} )
</code></pre>
<p>to include your lib_opencv that you have created. To finish, you add the follow line: </p>
<pre><code>abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'mips', 'mips64'
</code></pre>
<p>in your module app, like this:</p>
<pre><code>externalNativeBuild {
cmake {
cppFlags "-std=c++11 -frtti -fexceptions"
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'mips', 'mips64'
}
}
</code></pre>
<p>and below of buildTypes you add:</p>
<pre><code>sourceSets {
main {
jniLibs.srcDirs = ['path to your application /MyApplication/app/src/main/jniLibs/']
}
}
</code></pre>
<p>For more details, you can see this: <a href="https://github.com/googlesamples/android-ndk/tree/master/cmake/hello-libs" rel="noreferrer">https://github.com/googlesamples/android-ndk/tree/master/cmake/hello-libs</a></p> |
26,317,679 | How to add hamburger menu in bootstrap | <p>I need some help with bootstrap nav. I want it to be toggled via a hamburger icon on mobile. </p>
<p>Here it is on codepen: <s><a href="http://codepen.io/sadman/pen/hfGwv" rel="noreferrer">http://codepen.io/sadman/pen/hfGwv</a></s> (link invalid)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar,
.navbar-inverse {
border-radius: 0;
border: none;
margin-bottom: 0;
min-height: 80px;
}
.nav li {
display: inline;
color: white;
}
.navbar-inverse .navbar-nav>li>a {
color: #ffffff;
font-family: Lato;
font-size: 1.7em;
font-weight: 300;
padding: 30px 25px 33px 25px;
}
.navbar-inverse .navbar-nav li a:hover {
background-color: #444444;
transition: 0.7s all linear;
height: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="container">
<ul class="nav navbar-nav">
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#">Blog</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>
</div>
</nav></code></pre>
</div>
</div>
</p> | 26,320,007 | 3 | 0 | null | 2014-10-11 18:08:38.14 UTC | 18 | 2020-04-15 18:09:46.1 UTC | 2018-05-12 20:03:16.703 UTC | null | 11,683 | null | 4,041,858 | null | 1 | 63 | html|twitter-bootstrap|navigation|hamburger-menu | 260,044 | <p>All you have to do is read the code on getbootstrap.com:</p>
<p><a href="http://codepen.io/macsupport/pen/bKFzD" rel="noreferrer">Codepen</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<nav class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#">Blog</a></li>
<li><a href="contact.php">Contact</a></li>
</ul>
</div>
</div>
</nav></code></pre>
</div>
</div>
</p> |
22,615,475 | flask application with background threads | <p>I am creating a flask application, for one request I need to run some long running job which is not required to wait on the UI. I will create a thread and send a message to UI. The thread will calculate and update the database. But, UI will see a message upon submit.
Below is my implementation, but it is running the thread and then sending the output to UI which is not I prefer. How can I run this thread in the background?</p>
<pre><code>@app.route('/someJob')
def index():
t1 = threading.Thread(target=long_running_job)
t1.start()
return 'Scheduled a job'
def long_running_job
#some long running processing here
</code></pre>
<p>How can I make thread t1 to run the background and immediately send message in return?</p> | 22,617,121 | 6 | 0 | null | 2014-03-24 16:44:21.707 UTC | 26 | 2021-07-13 18:36:20.947 UTC | 2020-03-25 17:42:57.897 UTC | null | 3,407,256 | null | 1,672,111 | null | 1 | 41 | python|multithreading|flask | 39,337 | <p>The best thing to do for stuff like this is use a message broker. There is some excellent software in the python world meant for doing just this:</p>
<ul>
<li>Celery (<a href="http://www.celeryproject.org/" rel="noreferrer">http://www.celeryproject.org/</a>), and</li>
<li>RQ (<a href="http://python-rq.org/" rel="noreferrer">http://python-rq.org/</a>).</li>
</ul>
<p>Both are excellent choices.</p>
<p>It's almost never a good idea to spawn a thread the way you're doing it, as this can cause issues processing incoming requests, among other things.</p>
<p>If you take a look at the celery or RQ getting started guides, they'll walk you through doing this the proper way!</p> |
2,394,848 | How to quote values using group_concat | <p>I need to use group_concat to build a list of comma separated values but I need the values to be quoted. How do I do this?</p>
<p>This:</p>
<pre><code>425,254,431,53,513,13,1,13
</code></pre>
<p>Should be converted to:</p>
<pre><code>'425','254','431','53','513','13','1','13'
</code></pre> | 2,394,871 | 3 | 0 | null | 2010-03-07 01:46:27.59 UTC | 11 | 2013-07-08 00:07:33.417 UTC | 2010-03-07 01:57:59.897 UTC | null | 135,152 | null | 288,021 | null | 1 | 36 | sql|mysql|database | 20,547 | <p>Use:</p>
<pre><code>GROUP_CONCAT(CONCAT('''', your_column, '''' ))
</code></pre> |
2,615,042 | How do I use Logging in the Django Debug Toolbar? | <p>I would like to output debug messages in my django app at different points in a view function. The docs for the <a href="http://github.com/robhudson/django-debug-toolbar" rel="noreferrer">django-debug-toolbar</a> say it uses the build in python logging but I can't find any more information then that. I don't really want to log to a file but to the info pane on the toolbar. How does this work?</p> | 2,615,120 | 3 | 0 | null | 2010-04-10 21:24:29.88 UTC | 7 | 2018-01-17 00:24:07.283 UTC | null | null | null | null | 339 | null | 1 | 43 | python|django|debugging|django-views | 10,833 | <p>You just use the <a href="http://docs.python.org/library/logging.html" rel="noreferrer">logging module</a> methods and DjDT will intercept and display them in the Logging Panel.</p>
<pre><code>import logging
logging.debug('Debug Message')
if some_error:
logging.error('Error Message')
</code></pre> |
2,918,353 | Obtaining command line arguments in a Qt application | <p>The following snippet is from a little app I wrote using the Qt framework. The idea is that the app can be run in batch mode (i.e. called by a script) or can be run interactively. </p>
<p>It is important therefore, that I am able to parse command line arguments in order to know which mode in which to run etc.</p>
<p><strong>[Edit]</strong></p>
<p>I am debugging using Qt Creator 1.3.1 on Ubuntu Karmic. The arguments are passed in the normal way (i.e. by adding them via the 'Project' settings in the Qt Creator IDE). </p>
<p>When I run the app, it appears that the arguments are not being passed to the application. The code below, is a snippet of my main() function. </p>
<pre><code>int main(int argc, char *argv[])
{
//Q_INIT_RESOURCE(application);
try {
QApplication the_app(argc, argv);
//trying to get the arguments into a list
QStringList cmdline_args = QCoreApplication::arguments();
// Code continues ...
}
catch (const MyCustomException &e) { return 1; }
return 0;
}
</code></pre>
<p><strong>[Update]</strong></p>
<p>I have identified the problem - for some reason, although argc is correct, the elements of argv are empty strings.</p>
<p>I put this little code snippet to print out the argv items - and was horrified to see that they were all empty.</p>
<pre><code>for (int i=0; i< argc; i++){
std::string s(argv[i]); //required so I can see the damn variable in the debugger
std::cout << s << std::endl;
}
</code></pre>
<p>Does anyone know how I can retrieve the command line args in my application?</p> | 2,918,470 | 4 | 2 | null | 2010-05-27 03:54:16.57 UTC | 5 | 2021-04-25 15:48:34.923 UTC | 2012-03-06 14:30:21.9 UTC | null | 594,137 | null | 312,675 | null | 1 | 11 | c++|qt|qt-creator | 44,855 | <p>If your argc and argv are good, I'm surprised this would be possible as <code>QApplication::arguments()</code> is extremely simple. Note <a href="http://qt.gitorious.org/qt/qt/blobs/4.6-stable/src/corelib/kernel/qcoreapplication.cpp#line2057" rel="noreferrer">the source code</a>. Filtering the #ifdefs for Linux, it's just:</p>
<pre><code>QStringList QCoreApplication::arguments()
{
QStringList list;
if (!self) {
qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first");
return list;
}
const int ac = self->d_func()->argc;
char ** const av = self->d_func()->argv;
for (int a = 0; a < ac; ++a) {
list << QString::fromLocal8Bit(av[a]);
}
return list;
}
</code></pre>
<p>That's all you've got. There's a Unicode caveat which I would not think would apply to Karmic:</p>
<p><i>"On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using QString::fromLocal8Bit(); hence it is not possible to pass, for example, Japanese command line arguments on a system that runs in a Latin1 locale. Most modern Unix systems do not have this limitation, as they are Unicode-based."</i></p>
<p>You might try a copy of that code against your argc and argv directly and see what happens.</p> |
28,992,362 | dplyr join define NA values | <p>Can I define a "fill" value for NA in dplyr join? For example in the join define that all NA values should be 1?</p>
<pre><code>require(dplyr)
lookup <- data.frame(cbind(c("USD","MYR"),c(0.9,1.1)))
names(lookup) <- c("rate","value")
fx <- data.frame(c("USD","MYR","USD","MYR","XXX","YYY"))
names(fx)[1] <- "rate"
left_join(x=fx,y=lookup,by=c("rate"))
</code></pre>
<p>Above code will create NA for values "XXX" and "YYY". In my case I am joining a large number of columns and there will be a lot of non-matches. All non-matches should have the same value. I know I can do it in several steps but the question is can all be done in one?
Thanks!</p> | 28,995,196 | 4 | 0 | null | 2015-03-11 16:38:56.597 UTC | 5 | 2022-04-08 09:05:21.253 UTC | 2015-03-11 17:39:47.693 UTC | null | 817,778 | null | 2,519,368 | null | 1 | 34 | r|left-join|dplyr|na | 48,080 | <p>First off, I would like to recommend not to use the combination <code>data.frame(cbind(...))</code>. Here's why: <code>cbind</code> creates a <code>matrix</code> by default if you only pass atomic vectors to it. And matrices in R can only have one type of data (think of matrices as a vector with dimension attribute, i.e. number of rows and columns). Therefore, your code </p>
<pre><code>cbind(c("USD","MYR"),c(0.9,1.1))
</code></pre>
<p>creates a character matrix:</p>
<pre><code>str(cbind(c("USD","MYR"),c(0.9,1.1)))
# chr [1:2, 1:2] "USD" "MYR" "0.9" "1.1"
</code></pre>
<p>although you probably expected a final data frame with a character or factor column (rate) and a numeric column (value). But what you get is:</p>
<pre><code>str(data.frame(cbind(c("USD","MYR"),c(0.9,1.1))))
#'data.frame': 2 obs. of 2 variables:
# $ X1: Factor w/ 2 levels "MYR","USD": 2 1
# $ X2: Factor w/ 2 levels "0.9","1.1": 1 2
</code></pre>
<p>because strings (characters) are converted to factors when using <code>data.frame</code> by default (You can circumvent this by specifying <code>stringsAsFactors = FALSE</code> in the <code>data.frame()</code> call).</p>
<p>I suggest the following alternative approach to create the sample data (also note that you can easily specify the column names in the same call):</p>
<pre><code>lookup <- data.frame(rate = c("USD","MYR"),
value = c(0.9,1.1))
fx <- data.frame(rate = c("USD","MYR","USD","MYR","XXX","YYY"))
</code></pre>
<p>Now, for you actual question, if I understand correctly, you want to replace all <code>NA</code>s with a <code>1</code> in the joined data. If that's correct, here's a custom function using <code>left_join</code> and <code>mutate_each</code> to do that:</p>
<pre><code>library(dplyr)
left_join_NA <- function(x, y, ...) {
left_join(x = x, y = y, by = ...) %>%
mutate_each(funs(replace(., which(is.na(.)), 1)))
}
</code></pre>
<p>Now you can apply it to your data like this:</p>
<pre><code>> left_join_NA(x = fx, y = lookup, by = "rate")
# rate value
#1 USD 0.9
#2 MYR 1.1
#3 USD 0.9
#4 MYR 1.1
#5 XXX 1.0
#6 YYY 1.0
#Warning message:
#joining factors with different levels, coercing to character vector
</code></pre>
<p>Note that you end up with a character column (rate) and a numeric column (value) and all NAs are replaced by 1.</p>
<pre><code>str(left_join_NA(x = fx, y = lookup, by = "rate"))
#'data.frame': 6 obs. of 2 variables:
# $ rate : chr "USD" "MYR" "USD" "MYR" ...
# $ value: num 0.9 1.1 0.9 1.1 1 1
</code></pre> |
46,263,773 | Jackson: parse custom offset date time | <p>I have a model which has a timestamp property:</p>
<pre><code>class Model {
@JsonProperty("timestamp")
private OffsetDateTime timestamp;
}
</code></pre>
<p>The format of the timestamp is as following:</p>
<pre><code>2017-09-17 13:45:42.710576+02
</code></pre>
<p><code>OffsetDateTime</code> is unable to parse this:</p>
<blockquote>
<p>com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type <code>java.time.OffsetDateTime</code> from String "2017-09-17 13:45:42.710576+02": Text '2017-09-17 13:45:42.710576+02' could not be parsed at index 10</p>
</blockquote>
<p>How can I fix this?</p> | 46,263,957 | 1 | 0 | null | 2017-09-17 11:54:34.617 UTC | 10 | 2017-09-17 17:39:24.46 UTC | 2017-09-17 12:15:09.023 UTC | user7605325 | null | null | 8,622,137 | null | 1 | 12 | java|datetime|jackson|java-time|datetime-parsing | 31,228 | <p>You must tell Jackson in what format the date is. Basically, you have <code>year-month-day</code> followed by <code>hour:minute:second.microseconds</code> and the offset with 2 digits (<code>+02</code>). So your pattern will be:</p>
<pre><code>@JsonProperty("timestamp")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSSSSx")
private OffsetDateTime timestamp;
</code></pre>
<p>Take a look at <a href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns" rel="noreferrer">all the date/time patterns</a> for a more detailed explanation.</p>
<hr>
<p>If you want to preserve the same offset (<code>+02</code>) in the <code>OffsetDateTime</code>, don't forget to adjust the <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html#ADJUST_DATES_TO_CONTEXT_TIME_ZONE" rel="noreferrer"><code>DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE</code> option</a> to <code>false</code>.</p>
<p>If this option is set to <code>true</code> (in my tests), the result is converted to UTC (but it actually converts to whatever timezone is configured in Jackson):</p>
<blockquote>
<p>2017-09-17T11:45:42.710576Z</p>
</blockquote>
<p>If I set to <code>false</code>, the offset used in the input is preserved:</p>
<blockquote>
<p>2017-09-17T13:45:42.710576+02:00</p>
</blockquote>
<hr>
<p>The code above works with exactly 6 digits after decimal point. But if this quantity varies, you can use optional patterns, delimited by <code>[]</code>.</p>
<p>Example: if the input can have 6 or 3 decimal digits, I can use <code>pattern = "yyyy-MM-dd HH:mm:ss.[SSSSSS][SSS]x"</code>. The optional sections <code>[SSSSSS]</code> and <code>[SSS]</code> tells the parser to either consider 6 or 3 digits.</p>
<p>The problem with optional patterns is that, when serializing, it prints all the patterns (so it will print the fraction of second twice: with 6 <strong>and</strong> with 3 digits).</p>
<hr>
<p>Another alternative is to create custom serializers and deserializers (by extending <code>com.fasterxml.jackson.databind.JsonSerializer</code> and <code>com.fasterxml.jackson.databind.JsonDeserializer</code>):</p>
<pre><code>public class CustomDeserializer extends JsonDeserializer<OffsetDateTime> {
private DateTimeFormatter formatter;
public CustomDeserializer(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
return OffsetDateTime.parse(parser.getText(), this.formatter);
}
}
public class CustomSerializer extends JsonSerializer<OffsetDateTime> {
private DateTimeFormatter formatter;
public CustomSerializer(DateTimeFormatter formatter) {
this.formatter = formatter;
}
@Override
public void serialize(OffsetDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException {
gen.writeString(value.format(this.formatter));
}
}
</code></pre>
<p>Then you can register those in the <code>JavaTimeModule</code>. How to configure this will depend on the environment you're using (example: in Spring you can configure in the <a href="https://stackoverflow.com/questions/7854030/configuring-objectmapper-in-spring">xml files</a>). I'll just do it programatically as an example.</p>
<p>First I create the formatter, using a <code>java.time.format.DateTimeFormatterBuilder</code>:</p>
<pre><code>DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// date/time
.appendPattern("yyyy-MM-dd HH:mm:ss")
// optional fraction of seconds (from 0 to 9 digits)
.optionalStart().appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true).optionalEnd()
// offset
.appendPattern("x")
// create formatter
.toFormatter();
</code></pre>
<p>This formatter accepts an optional fraction of second with 0 to 9 digits. Then I use the custom classes above and register them in the <code>ObjectMapper</code>:</p>
<pre><code>// set formatter in the module and register in object mapper
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(OffsetDateTime.class, new CustomSerializer(formatter));
module.addDeserializer(OffsetDateTime.class, new CustomDeserializer(formatter));
mapper.registerModule(module);
</code></pre>
<p>I also remove the <code>@JsonFormat</code> annotation from the field:</p>
<pre><code>@JsonProperty("timestamp")
private OffsetDateTime timestamp;
</code></pre>
<p>And now it accepts values like <code>2017-09-17 13:45:42+02</code> (no fraction of seconds) and <code>2017-09-17 13:45:42.71014+02</code> (5 decimal digits). It can parse from 0 to 9 decimal digits (9 is the maximum supported by the API), and it prints exactly the same quantity when serializing.</p>
<hr>
<p>The alternative above is very flexible as it allows to set the formatter in the custom classes. But it also sets the serialization and deserialization for all <code>OffsetDateTime</code> fields.</p>
<p>If you don't want that, you can also create a class with a fixed formatter:</p>
<pre><code>static class CustomDeserializer extends JsonDeserializer<OffsetDateTime> {
private DateTimeFormatter formatter = // create formatter as above
// deserialize method is the same
}
static class CustomSerializer extends JsonSerializer<OffsetDateTime> {
private DateTimeFormatter formatter = // create formatter as above
// serialize method is the same
}
</code></pre>
<p>Then, you can add those to only the fields you want, using the annotations <code>com.fasterxml.jackson.databind.annotation.JsonSerialize</code> and <code>com.fasterxml.jackson.databind.annotation.JsonDeserialize</code>:</p>
<pre><code>@JsonProperty("timestamp")
@JsonSerialize(using = CustomSerializer.class)
@JsonDeserialize(using = CustomDeserializer.class)
private OffsetDateTime timestamp;
</code></pre>
<p>With this, you don't need to register the custom serializers in the module, and only the annotated field will use the custom classes (the other <code>OffsetDateTime</code> fields will use the default settings).</p> |
49,323,225 | Expose all ports for a Docker image | <p>I am troubleshooting a solution in which I am setting up a HA cluster. Although I know the ports needed for the application to perform failover and failback, somehow the dockerized solution is not working. I suspect that there are some ports that I do not know about yet.</p>
<p>Currently, my <code>EXPOSE</code> statement says:</p>
<pre><code>EXPOSE 8080 61616 5672 61613 5445 1883
</code></pre>
<p>I also start my docker containers with</p>
<pre><code>docker run --network host -p 8080:8080 -p 61616:61616 -p 5672:5672 -p 61613:61613 -p 5445:5445 -p 1883:1883
</code></pre>
<p>But for the sake of troubleshooting, I want to expose ALL ports.</p>
<p>I tried something like:</p>
<pre><code>EXPOSE 1-65535
</code></pre>
<p>But this gives an ERROR.</p>
<p>What is the best way I can expose ALL ports of the docker container?</p> | 49,323,975 | 3 | 0 | null | 2018-03-16 14:33:21.48 UTC | 8 | 2020-07-23 07:45:40.887 UTC | 2020-07-23 07:41:20.057 UTC | null | 1,402,846 | user4889345 | null | null | 1 | 33 | docker | 45,980 | <p>When running using <code>--network host</code> there is no need to map the ports. All the docker container ports will be available since the network host mode makes the container use the host's network stack.</p>
<p>Also the <code>EXPOSE 8080 61616 5672 61613 5445 1883</code> is not needed. This instruction doesn't do anything. It is just a way to document which ports need to be mapped.</p>
<p>In short, running <code>docker run --network host ...</code> will expose all the container ports.</p> |
625,467 | What do the numbers in rsync's output mean? | <p>When I run <code>rsync</code> with the <code>--progress</code> flag, I get information about the transfers as follows.</p>
<pre><code>path/to/file
16 100% 0.01kB/s 0:00:01 (xfer#10857, to-check=427700/441502)
</code></pre>
<p>What do the numbers in the second row mean? I know what some of them are, but what do the others mean (marked with ??? below)?</p>
<blockquote>
<p>16 ???</p>
<p>100% amount of transfer completed in this file</p>
<p>0.0.1kB/s speed of current file transfer</p>
<p>0:00:01: time elapsed in current file transfer</p>
<p>10857 count of files transferred</p>
<p>427700 ???</p>
<p>441502 ???</p>
</blockquote> | 625,472 | 2 | 0 | null | 2009-03-09 08:52:15.173 UTC | 3 | 2014-05-11 15:13:58.013 UTC | 2013-09-29 02:06:14.327 UTC | null | 1,944,384 | andy | 63,051 | null | 1 | 42 | rsync | 18,629 | <blockquote>
<p>When the file transfer finishes, rsync
replaces the progress line with a
summary line that looks like this:</p>
<pre><code> 1238099 100% 146.38kB/s 0:00:08 (xfer#5, to-check=169/396)
</code></pre>
<p>In this example, the file was 1238099
bytes long in total, the average rate
of transfer for the whole file was
146.38 kilobytes per second over the 8 seconds that it took to complete, it
was the 5th transfer of a regular file
during the current rsync session, and
there are 169 more files for the
receiver to check (to see if they are
up-to-date or not) remaining out of
the 396 total files in the file-list.</p>
</blockquote>
<p>from <a href="http://samba.anu.edu.au/ftp/rsync/rsync.html" rel="noreferrer">http://samba.anu.edu.au/ftp/rsync/rsync.html</a> under --progress switch</p> |
2,856,417 | Reading a text file in MATLAB line by line | <p>I have a CSV file, I want to read this file and do some pre-calculations on each row to see for example that row is useful for me or not and if yes I save it to a new CSV file.
can someone give me an example?
in more details this is how my data looks like: (string,float,float) the numbers are coordinates.</p>
<pre><code>ABC,51.9358183333333,4.183255
ABC,51.9353866666667,4.1841
ABC,51.9351716666667,4.184565
ABC,51.9343083333333,4.186425
ABC,51.9343083333333,4.186425
ABC,51.9340916666667,4.18688333333333
</code></pre>
<p>basically i want to save the rows that have for distances more than 50 or 50 in a new file.the string field should also be copied.
thanks</p> | 2,858,346 | 5 | 2 | null | 2010-05-18 10:42:02.817 UTC | 3 | 2017-11-29 13:05:30.687 UTC | 2012-08-28 14:23:43.62 UTC | null | 97,160 | null | 313,245 | null | 1 | 17 | file|matlab|file-io|csv | 102,781 | <p>You could actually use <a href="https://www.mathworks.com/help/matlab/ref/xlsread.html" rel="nofollow noreferrer"><code>xlsread</code></a> to accomplish this. After first placing your sample data above in a file <code>'input_file.csv'</code>, here is an example for how you can get the numeric values, text values, and the raw data in the file from the three outputs from <a href="https://www.mathworks.com/help/matlab/ref/xlsread.html" rel="nofollow noreferrer"><code>xlsread</code></a>:</p>
<pre><code>>> [numData,textData,rawData] = xlsread('input_file.csv')
numData = % An array of the numeric values from the file
51.9358 4.1833
51.9354 4.1841
51.9352 4.1846
51.9343 4.1864
51.9343 4.1864
51.9341 4.1869
textData = % A cell array of strings for the text values from the file
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
'ABC'
rawData = % All the data from the file (numeric and text) in a cell array
'ABC' [51.9358] [4.1833]
'ABC' [51.9354] [4.1841]
'ABC' [51.9352] [4.1846]
'ABC' [51.9343] [4.1864]
'ABC' [51.9343] [4.1864]
'ABC' [51.9341] [4.1869]
</code></pre>
<p>You can then perform whatever processing you need to on the numeric data, then resave a subset of the rows of data to a new file using <a href="https://www.mathworks.com/help/matlab/ref/xlswrite.html" rel="nofollow noreferrer"><code>xlswrite</code></a>. Here's an example:</p>
<pre><code>index = sqrt(sum(numData.^2,2)) >= 50; % Find the rows where the point is
% at a distance of 50 or greater
% from the origin
xlswrite('output_file.csv',rawData(index,:)); % Write those rows to a new file
</code></pre> |
3,052,288 | Dynamically load nib for iPhone/iPad within view controller | <p>I have converted an iPhone application using the wizard like thing in XCode into a universal app. </p>
<p>It builds fine but obviously looks a bit rubbish in some areas :)</p>
<p>I need to load nibs according to which device is being used. I dont wish to create my view controllers using <code>initWithNib</code> as I already have code to create the controllers with some data (<code>initWithMyLovelyData</code>) which doesnt do anything to do with nib loading. </p>
<p>I know to find out the device you use <code>UI_USER_INTERFACE_IDIOM()</code> so I tried overriding the <code>initWithNibName</code> within the actual view controllers themselves, assuming they get called internally somehow. But it's not working as I guess I am unsure of the syntax. </p>
<p>I have tried</p>
<pre><code>if(ipad..) self = [super initWithNibName:@"MyIpadNib" bundle:nibBundleOrNil];
</code></pre>
<p>And that doesnt work :/</p>
<p>EDIT - I know I have massively edited this, made my question a bit more specific after doing some more research - apologies!</p> | 3,052,660 | 5 | 0 | null | 2010-06-16 10:05:06.027 UTC | 9 | 2014-11-13 20:11:08.253 UTC | 2010-06-16 12:04:47.313 UTC | null | 121,278 | null | 3,193 | null | 1 | 21 | iphone|objective-c|ipad|universal | 22,028 | <p>EDIT: @Adam's answer below is the correct answer.</p>
<p>To determine which nib to load, do the following, and scrap your <code>initWithMyLovelyData</code> method and use a property to set the data. You should be able to easily move all your init code into the property setter method.</p>
<pre><code>MyViewController *viewController;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
viewController = [[MyViewController alloc] initWithNibName:@"ipadNIB" bundle:nil];
} else {
viewController = [[MyViewController alloc] initWithNibName:@"iphoneNIB" bundle:nil];
}
viewController.myLovelyData = someData;
</code></pre> |
2,503,235 | Vimeo videos in iPhone app | <p>I was wondering if there's a way to "embed" a Vimeo video in an iPhone app. </p>
<p>For YouTube videos I'm using a webview containing the correct embed code for the YouTube video and the iPhone's native YouTube support will then transform the flash player into a YouTube button. </p>
<p>Is there a similar way to play Vimeo videos from my app?</p>
<p>Maybe someone knows the correct <code><video></code>-src for Vimeo videos?</p>
<p>thanks,
Thomas</p> | 3,243,798 | 6 | 0 | null | 2010-03-23 20:09:39.76 UTC | 9 | 2013-04-10 05:51:16.19 UTC | null | null | null | null | 141,266 | null | 1 | 4 | iphone|vimeo | 11,434 | <p>It appears that vimeo is transcoding all videos being uploaded these days into versions compatible for the iphone which are used on their site when you browse from an iphone or ipad. You can however call their videos into an HTML5 player on your site by doing some <a href="http://www.stacyconaway.com/bucket/JS-Vimeo-embed-code-with-notes.pdf" rel="nofollow noreferrer">simple tricks found here.</a> If you can host a page on your site somewhere, you can load the video into a UIWebView and it should all work. Vimeo's only limitation is that there embed code is flash but the video infrastructure is all there for HTML5. Hope this helps!</p> |
3,212,982 | Need to write XML using PHP - how? | <p>I've got this basic code.</p>
<pre><code><chart lowerLimit='0' upperLimit='100' caption='Revenue' subcaption='US $ (1,000s)' numberPrefix='$' numberSuffix='K' showValue='1' >
<colorRange>
<color minValue='0' maxValue='50' color='A6A6A6'/>
<color minValue='50' maxValue='75' color='CCCCCC'/>
<color minValue='75' maxValue='100' color='E1E1E1'/>
</colorRange>
<value>78.9</value>
<target>80</target>
</chart>
</code></pre>
<p>it's used from fusionwidgets and there's no documentation on how to write this in PHP.</p>
<p>can anybody advise?</p> | 3,213,276 | 6 | 0 | null | 2010-07-09 13:26:27.977 UTC | 7 | 2017-08-28 16:24:13.863 UTC | 2017-08-28 16:24:13.863 UTC | null | 319,741 | user293838 | null | null | 1 | 23 | php|xml | 39,699 | <p>There is complete example with <a href="http://php.net/XMLWriter" rel="noreferrer">php.net/XMLWriter</a> to produce exactly the same XML output like you posted.</p>
<pre><code><?php
$writer = new XMLWriter();
$writer->openURI('php://output');
$writer->startDocument('1.0','UTF-8');
$writer->setIndent(4);
$writer->startElement('chart');
$writer->writeAttribute('lowerLimit', '0');
$writer->writeAttribute('upperLimit', '100');
$writer->writeAttribute('caption', 'Revenue');
$writer->writeAttribute('subcaption', 'US $ (1,000s)');
$writer->writeAttribute('numberPrefix', '$');
$writer->writeAttribute('numberSuffix', 'K');
$writer->writeAttribute('showValue', '1');
$writer->startElement('colorRange');
$writer->startElement('color');
$writer->writeAttribute('minValue', '0');
$writer->writeAttribute('maxValue', '50');
$writer->writeAttribute('color', 'A6A6A6');
$writer->endElement();
$writer->startElement('color');
$writer->writeAttribute('minValue', '50');
$writer->writeAttribute('maxValue', '75');
$writer->writeAttribute('color', 'CCCCCC');
$writer->endElement();
$writer->startElement('color');
$writer->writeAttribute('minValue', '75');
$writer->writeAttribute('maxValue', '100');
$writer->writeAttribute('color', 'E1E1E1');
$writer->endElement();
$writer->endElement();
$writer->writeElement('value','78.9');
$writer->writeElement('target','78.9');
$writer->endElement();
$writer->endDocument();
$writer->flush();
?>
</code></pre> |
2,678,779 | Why do I get an error 'Cannot resolve symbol <symbolname>' in ReSharper? | <p>Using VS2008 and R# 5 I'm running into an odd situation, where on an aspx page I keep getting</p>
<pre><code>Cannot resolve symbol 'symbolname'
</code></pre>
<p>But the code compiles and runs fine. While having a fix for this would be great, I'm just trying to figure out if I'm losing my mind.</p>
<p>The CodeFile directive and Inherits directives are fine. If I compile the app or just let devenv sit for a bit it'll go away, but as soon as I <em>save</em> the aspx [via ctrl+s] R# suddenly has trouble with the Inherits attribute and flips out on every method in the page (OnClick etc).</p>
<pre><code>// Anonymized of course but otherwise intact
<%@ Page AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" Language="C#" MasterPageFile="~/MasterPage.master" Title="Test Page Title" %>
</code></pre>
<p>This is mostly just a grievance, because since the code compiles it doesn't stop me from doing what I need. </p>
<p>I would post a bug report to the JetBrains site but first I would like to know I'm not alone. It could be my machine. Maybe when I roll to VS2010 in a couple weeks this will go away?</p> | 2,691,736 | 7 | 10 | 2010-04-20 21:27:29.833 UTC | 2010-04-20 21:27:29.833 UTC | 7 | 2018-10-04 09:21:45.32 UTC | 2010-05-13 17:41:46.96 UTC | null | 274,402 | null | 109,749 | null | 1 | 27 | c#|asp.net|visual-studio-2008|resharper | 43,059 | <p>So no final resolution yet. According to tech-support this is a known issue and is being researched. Final resolution undetermined at this time. If you're experiencing a similar issue, just hang tight. URL: <a href="http://youtrack.jetbrains.net/issue/RSRP-178681" rel="noreferrer">http://youtrack.jetbrains.net/issue/RSRP-178681</a></p> |
2,667,908 | Find out what variable is throwing a NullPointerException programmatically | <p>I know I can find out if a variable is null in Java using these techniques:</p>
<ul>
<li>if <code>(var==null)</code> -> too much work</li>
<li><code>try { ... } catch (NullPointerException e) { ...}</code> -> it tells me what line is throwing the exception</li>
<li>using the debugger -> by hand, too slow</li>
</ul>
<p>Consider this line of code:</p>
<pre><code>if (this.superSL.items.get(name).getSource().compareTo(VIsualShoppingList.Source_EXTRA)==0) {
</code></pre>
<p>I would like to know if there's a generic way to find out programatically what variable (not just the line) is throwing the NullPointerException in a certain area of code. In the example, knowing that</p> | 2,667,970 | 8 | 5 | null | 2010-04-19 13:55:10.063 UTC | 8 | 2020-05-04 16:06:49.19 UTC | 2017-09-30 18:16:36.353 UTC | null | 1,033,581 | null | 110,514 | null | 1 | 30 | java|debugging|nullpointerexception | 26,242 | <p>Since it's possible to cause a null pointer exception without even involving a variable:</p>
<pre><code>throw new NullPointerException();
</code></pre>
<p>I would have to say that there is no generic way to pin down a null pointer exception to a specific variable.</p>
<p>Your best bet would be to put as few as possible statements on each line so that it becomes obvious what caused the null pointer exception. Consider refactoring your code in the question to look something like this:</p>
<pre><code>List items = this.superSL.items;
String name = items.get(name);
String source = name.getSource();
if (source.compareTo(VIsualShoppingList.Source_EXTRA) == 0) {
// ...
}
</code></pre>
<p>It's more lines of code to be sure. But it's also more readable and more maintainable.</p> |
2,586,842 | Is ternary operator, if-else or logical OR faster in javascript? | <p>Which method is faster or more responsive in javascript, if-else, the ternary operator or logical OR? Which is advisable to use, for what reasons?</p> | 2,586,861 | 8 | 3 | null | 2010-04-06 17:18:42.53 UTC | 13 | 2021-08-11 05:48:53.863 UTC | 2018-02-23 06:22:22.91 UTC | null | 9,009,597 | null | 310,253 | null | 1 | 50 | javascript|performance | 32,827 | <p>The speed difference will be negligible - use whichever you find to be more readable. In other words I highly doubt that a bottleneck in your code will be due to using the wrong conditional construct.</p> |
2,974,954 | Correct word-count of a LaTeX document | <p>I'm currently searching for an application or a script that does a <strong>correct</strong> word count for a LaTeX document.</p>
<p>Up till now, I have only encountered scripts that only work on a single file but what I want is a script that can safely ignore LaTeX keywords and also <strong>traverse linked files</strong>...ie follow <code>\include</code> and <code>\input</code> links to produce a correct word-count for the <em>whole</em> document.</p>
<p>With vim, I currently use <code>ggVGg CTRL+G</code> but obviously that shows the count for the current file and does not ignore LaTeX keywords.</p>
<p>Does anyone know of any script (or application) that can do this job?</p> | 2,989,807 | 9 | 4 | null | 2010-06-04 14:20:21.157 UTC | 24 | 2020-02-17 02:41:52.997 UTC | 2012-05-27 21:40:24.823 UTC | null | 248,065 | null | 44,084 | null | 1 | 77 | latex|word-count | 85,567 | <p>I use <code>texcount</code>. The <a href="http://folk.uio.no/einarro/Services/texcount.html" rel="noreferrer">webpage</a> has a Perl script to download (and a manual).</p>
<p>It will include <code>tex</code> files that are included (<code>\input</code> or <code>\include</code>) in the document (see <code>-inc</code>), supports macros, and has many other nice features.</p>
<p>When following included files you will get detail about each separate file as well as a total. For example here is the total output for a 12 page document of mine:</p>
<pre><code>TOTAL COUNT
Files: 20
Words in text: 4188
Words in headers: 26
Words in float captions: 404
Number of headers: 12
Number of floats: 7
Number of math inlines: 85
Number of math displayed: 19
</code></pre>
<p>If you're only interested in the total, use the <code>-total</code> argument.</p> |
2,728,278 | What is a practical use for a closure in JavaScript? | <p>I'm <a href="http://jsbin.com/ojuxo/edit" rel="noreferrer">trying</a> my hardest to wrap my head around JavaScript closures.</p>
<p>I get that by returning an inner function, it will have access to any variable defined in its immediate parent.</p>
<p>Where would this be useful to me? Perhaps I haven't quite got my head around it yet. Most of the <a href="http://blog.morrisjohns.com/javascript_closures_for_dummies.html" rel="noreferrer">examples I have seen online</a> don't provide any real world code, just vague examples.</p>
<p>Can someone show me a real world use of a closure?</p>
<p>Is this one, for example?</p>
<pre><code>var warnUser = function (msg) {
var calledCount = 0;
return function() {
calledCount++;
alert(msg + '\nYou have been warned ' + calledCount + ' times.');
};
};
var warnForTamper = warnUser('You can not tamper with our HTML.');
warnForTamper();
warnForTamper();
</code></pre> | 2,728,341 | 24 | 4 | null | 2010-04-28 09:39:19.74 UTC | 173 | 2022-08-24 02:52:18.687 UTC | 2015-07-22 17:33:59.247 UTC | null | 2,246,380 | null | 31,671 | null | 1 | 340 | javascript|closures|terminology | 138,882 | <p>I've used closures to do things like:</p>
<pre><code>a = (function () {
var privatefunction = function () {
alert('hello');
}
return {
publicfunction : function () {
privatefunction();
}
}
})();
</code></pre>
<p>As you can see there, <code>a</code> is now an object, with a method <code>publicfunction</code> ( <code>a.publicfunction()</code> ) which calls <code>privatefunction</code>, which only exists inside the closure. You can <strong>not</strong> call <code>privatefunction</code> directly (i.e. <code>a.privatefunction()</code> ), just <code>publicfunction()</code>.</p>
<p>It's a minimal example, but maybe you can see uses to it? We used this to enforce public/private methods.</p> |
33,814,343 | Angular material layout-align = "center center" not working | <p>I'm trying to use the layout-align = "center center" which should align the content at center both vertically and horizontally. But it's only aligning the content horizontally and not vertically.</p>
<p>Here's the plnkr <a href="http://embed.plnkr.co/GKot1i15DAi6OFP7G0BD/preview">link</a> of the code I'm trying.</p>
<pre><code><body ng-app="app" ng-controller="appCtrl">
<md-toolbar>
<div class="md-toolbar-tools">
<h2 flex>Hello Angular-material!</h2>
</div>
</md-toolbar>
<div class="flexbox-parent">
<div layout="row" layout-align="center center">
<div flex="15">First line</div>
<div flex="15">Second line</div>
</div>
</div>
</body>
</code></pre> | 33,815,412 | 3 | 2 | null | 2015-11-19 21:05:09.393 UTC | 1 | 2018-02-15 02:20:36.567 UTC | null | null | null | null | 5,372,399 | null | 1 | 11 | html|css|angularjs|material-design|angular-material | 98,635 | <p>The reason why it is not centering it vertically is because your div containing the layout-align attribute does not have a height.</p>
<p>Try something like</p>
<pre><code><div class="flexbox-parent">
<div layout="row" layout-align="center center" style="min-height: 500px">
<div flex="15">First line</div>
<div flex="15">Second line</div>
</div>
</div>
</code></pre> |
42,558,903 | Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted | <p>I recently encountered a SwiftMail error while trying to send a mail through gmail.</p>
<pre><code> Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted.
</code></pre>
<p>I was trying to send mail through my gmail and google thought that I was a spam(maybe because I was requesting too fast) I received a mail from them saying my account was access and I told them it was me. I was able to send mail without problem and it just occured now.</p>
<p>This is the contents of my env file.</p>
<pre><code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=mypasswordhere
[email protected]
MAIL_NAME=talentscout
</code></pre> | 42,558,904 | 13 | 0 | null | 2017-03-02 15:04:47.89 UTC | 34 | 2022-06-27 08:41:58.603 UTC | null | null | null | null | 7,529,998 | null | 1 | 59 | php|laravel|gmail | 143,603 | <p>I researched on the internet and some answers includes enabling the "<strong>access for lesser app</strong>" and "<strong>unlocking gmail captcha</strong>" which sadly didn't work for me until I found the 2-step verification.</p>
<p><strong>What I did the following was:</strong></p>
<ol>
<li><p>enable the <strong>2-step verification</strong> to google <a href="https://www.google.com/landing/2step/" rel="noreferrer">HERE</a></p></li>
<li><p>Create App Password to be use by your system <a href="https://security.google.com/settings/security/apppasswords" rel="noreferrer">HERE</a></p></li>
<li><p>I selected <em>Others (custom name)</em> and clicked generate</p></li>
<li><p>Went to my env file in laravel and edited this</p>
<p>[email protected]</p>
<p>MAIL_PASSWORD=thepasswordgenerated</p></li>
<li>Restarted my apache server and boom! <strong>It works again</strong>.</li>
</ol>
<p>This was my solution. I created this to atleast make other people not go wasting their time researching for a possible answer.</p> |
10,698,157 | Selenium webdriver: finding all elements with similar id | <p>I have this xpath: <code>//*[@id="someId::button"]</code></p>
<p>Pressing it shows a dropdown list of values.</p>
<p>Now, I know all the elements in the list have an id like this :</p>
<pre><code>//*[@id="someId--popup::popupItemINDEX"]
</code></pre>
<p>, where INDEX is a number from 1 to whatever the number of options are.</p>
<p>I also know the value which I must click.</p>
<p>One question would be: since I will always know the id of the button which generates the dropdown, can I get all the elements in the dropdown with a <strong>reusable</strong> method? (I need to interact with more than one dropdown)</p>
<p>The way I thought about it is:
get the root of the initial ID, as in: </p>
<pre><code>//*[@id="someId
</code></pre>
<p>then add the rest : <code>--popup::popupItem</code>. I also need to add the index and I thought I could use a try block (in order to get though the exceptions when I give a bigger than expected index) like this:</p>
<pre><code> for(int index=1;index<someBiggerThanExpectedNumber;index++){
try{
WebElement aux= driver.findElement(By.xpath(builtString+index+"\"]"));
if(aux.getText().equals(myDesiredValue))
aux.click();
}catch(Exception e){}
}
</code></pre>
<p>Note that I am using the webdriver api and java.</p>
<p><em><strong>I would like to know if this would work and if there is an easier way of doing this, given the initial information I have.</em></strong></p>
<p>EDIT: The way I suggested works, but for an easier solution, the accepted answer should be seen</p> | 10,698,817 | 3 | 0 | null | 2012-05-22 08:08:51.657 UTC | 3 | 2014-04-09 09:35:51.603 UTC | 2012-05-22 09:46:48.377 UTC | null | 1,321,957 | null | 1,321,957 | null | 1 | 11 | java|xpath|selenium|webdriver | 55,167 | <p>As a rule of thumb, try to select more elements by one query, if possible. Searching for many elements one-by-one will get seriously slow.</p>
<p>If I understand your needs well, a good way to do this would be using</p>
<pre><code>driver.findElement(By.id("someId::button")).click();
driver.findElement(By.xpath("//*[contains(@id, 'someId--popup::popupItem') " +
"and text()='" + myDesiredValue + "']"))
.click();
</code></pre>
<p>For more information about XPath, see <a href="http://www.w3.org/TR/xpath/">the spec</a>. It's surprisingly a very good read if you can skip the crap!</p>
<p>That finds and clicks an element with text equal to you desired value which contains "someId--popup::popupItem" in its ID.</p>
<pre><code>List<WebElement> list = driver.findElements(By.xpath("//*[contains(@id, 'someId--popup::popupItem')]"));
</code></pre>
<p>That finds all just all elements that contain "someId--popup::popupItem" in their ID. You can then traverse the list and look for your desired element.</p>
<p>Did you know you can call <code>findElement()</code> on a <code>WebElement</code> to search just it's children?
- <code>driver.findElement(By.id("someId")).findElements(By.className("clickable"))</code></p>
<p>Without a peek on the underlying HTML, I guess I can't offer the best approach, but I have some in my head.</p> |
33,457,639 | How to inject dependencies to a laravel job | <p>I'm adding a laravel job to my queue from my controller as such</p>
<pre><code>$this->dispatchFromArray(
'ExportCustomersSearchJob',
[
'userId' => $id,
'clientId' => $clientId
]
);
</code></pre>
<p>I would like to inject the <code>userRepository</code> as a dependency when implementing the <code>ExportCustomersSearchJob</code> class. Please how can I do that?</p>
<p>I have this but it doesn't work</p>
<pre><code>class ExportCustomersSearchJob extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels, DispatchesJobs;
private $userId;
private $clientId;
private $userRepository;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($userId, $clientId, $userRepository)
{
$this->userId = $userId;
$this->clientId = $clientId;
$this->userRepository = $userRepository;
}
}
</code></pre> | 33,458,379 | 3 | 0 | null | 2015-10-31 23:17:31.37 UTC | 3 | 2021-11-10 10:31:33.653 UTC | null | null | null | null | 2,561,122 | null | 1 | 31 | php|laravel|laravel-5|laravel-5.1 | 15,598 | <p>You inject your dependencies in the <code>handle</code> method:</p>
<pre><code>class ExportCustomersSearchJob extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels, DispatchesJobs;
private $userId;
private $clientId;
public function __construct($userId, $clientId)
{
$this->userId = $userId;
$this->clientId = $clientId;
}
public function handle(UserRepository $repository)
{
// use $repository here...
}
}
</code></pre> |
23,302,049 | run robocopy bat to copy entire drive to another drive | <p>I'm trying to run a simple backup (mirror) of one entire drive (d:) to another drive (k:). I've created a .bat file ('backup.bat') defining the source (d:) and destination (k:) and placed this batch file within a folder on the d drive (d:\temp). When I double-click on the batch file it defines the source as d:\temp, instead of what I've defined it as in the batch file; d:. </p>
<p>Here is the text in the .bat file:</p>
<pre><code>@echo off
echo To begin backing up data:
pause
robocopy "D:" "K:" /L /v
echo.
pause
exit
</code></pre>
<p>And this is what shows up when I double-click on the backup.bat</p>
<p><img src="https://i.stack.imgur.com/TAKU3.png" alt="enter image description here"></p>
<p>As you can see, source is defined as d:\temp. This is where the batch file is located, but in the batch file I defined it as D:. For some reason, the destination is defined correctly.</p>
<p>Any ideas? </p>
<p>-al</p>
<p>EDIT: If I add the '/' to the source and destination location, see code below, I see even more odd behavior (see screenshot). The source is now both the defined source and destination combined, w/ no destination. </p>
<pre><code>@echo off
echo To begin backing up data:
pause
robocopy "D:\" "K:\" /L /v
echo.
pause
exit
</code></pre>
<p><img src="https://i.stack.imgur.com/uP25u.png" alt="enter image description here"></p>
<p>And, if I remove the "" from the source and destination....IT WORKs! </p>
<pre><code>@echo off
echo To begin backing up data:
pause
robocopy D:\ K:\ /L /v
echo.
pause
exit
</code></pre>
<p><img src="https://i.stack.imgur.com/4snQV.png" alt="enter image description here"></p> | 23,302,499 | 4 | 0 | null | 2014-04-25 20:05:54.963 UTC | 8 | 2021-09-06 14:42:10.65 UTC | 2014-04-25 20:51:56.163 UTC | null | 3,178,354 | null | 3,178,354 | null | 1 | 14 | windows|batch-file|windows-7|cmd|robocopy | 100,282 | <p>with <code>"D:"</code> you are <strong>not</strong> specifying the <em>root</em> directory of the D drive (<code>D:\</code>) but the <em>current</em> directory of D instead, (<code>D:\temp</code> in your example). </p>
<p>To solve this problem, just add <code>\</code> to the source spec (and while there, to the dest spec as well)</p>
<pre><code>robocopy d:\ k:\ /L /v
</code></pre> |
32,292,262 | How to change UICollectionView Scroll Direction? | <p>I have successfully implemented a <code>UICollectionView</code>. Is it possible to change the <code>scrollDirection</code>? </p>
<p>Can you please show how to implement it programmatically?</p> | 32,292,660 | 3 | 0 | null | 2015-08-30 01:10:35.3 UTC | 9 | 2021-06-24 16:41:44.723 UTC | 2017-11-07 12:03:43.483 UTC | null | 3,397,217 | null | 5,213,477 | null | 1 | 44 | swift|uicollectionview | 51,693 | <p>This is how you create it in code with <code>UICollectionViewFlowLayout</code></p>
<pre><code>let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
</code></pre>
<p>or if you are working with an existent collection view</p>
<pre><code>if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .vertical
}
</code></pre> |
34,145,791 | Diverting twilio call to voicemail if unanswered | <p>I'd love some advice on my twilio setup for a problem I'm trying to solve.</p>
<p><strong>Overview:</strong></p>
<p>Each user in our system is provisioned a twilio phone number that they can hand out to anyone to contact them.</p>
<p>If personA contacts a user in our system (userB) via the provisioned twilio phone number, we'd like to connect them with userB if they are available. If userB is not available, we'd like to direct personA to voicemail. In other words, we want to make sure that we have control of the voicemail experience and the voicemail itself so that we can store it in our system, rather than having the voicemail be left on userB's device.</p>
<p><strong>Current solution:</strong></p>
<ul>
<li>PersonA's incoming call gets added to a queue. At the same time, the system dials out userB. </li>
<li>UserB is asked to press 1 to accept the call. The reason for the explicit entry from UserB is to detect whether UserB is available to answer the call. (For example, if the call to UserB goes to their personal voicemail, the explicit digit entry will not happen telling us they are not available to answer.)</li>
<li>If UserB does not enter 1 in a specified amount of time, PersonA is directed to voicemail.</li>
<li>If UserB presses 1, call to UserB is modified (via twilio rest api) to dial the queue that PersonA is in to connect UserB and PersonA.</li>
</ul>
<p><strong>Problem with current solution:</strong></p>
<p>In this solution, the control of when to divert personA's call to voicemail is controlled by the outcome of the call to UserB, which seems suboptimal. For instance, we may not be able to call UserB at all. In this case, personA would stay in the queue indefinitely. </p>
<p>What I'd like to happen in this case is to poll the queue personA is in to check the time in queue, and divert the call to voicemail if time in queue is greater than a threshold. However, it does not seem like it is possible to accurately know how long a call is unattended in a queue because:</p>
<ul>
<li><p>The status of a call in a queue is <code>in-progress</code> even if the caller is listening to wait music. This is the same status as if PersonA's call had been answered.</p></li>
<li><p>If UserB dials into the queue, the call is only dequeued when the bridged parties disconnect, with no change in the call status of PersonA's call to indicate that they have been connected to UserB.</p></li>
</ul>
<p><strong>Questions</strong></p>
<ul>
<li>Is my understanding of why I cannot poll the call queue to divert calls to voicemail correct?</li>
<li>Should I instead be calling PersonA into a conference, and if UserB is available, connecting him/her to the conference that PersonA is in?</li>
<li>If I use a conference setup, what would be the easiest way to detect how long PersonA has been waiting in the conference so as to divert PersonA's call to voicemail in the event of UserB never joining the conference?</li>
</ul> | 34,177,165 | 1 | 0 | null | 2015-12-08 00:12:22.617 UTC | 10 | 2015-12-18 11:01:00.217 UTC | null | null | null | null | 111,856 | null | 1 | 13 | twilio | 7,106 | <p>Twilio developer evangelist here.</p>
<p>I think you may have overcomplicated things a bit here with the queue. You can actually provide the message and gather within the original call without having to dial out yourself and eventually connect the two calls.</p>
<p>Here's how:</p>
<p>Your incoming call TwiML should look like this:</p>
<pre><code><Response>
<Dial action="/call_complete" timeout="30">
<Number url="/whisper">
ONWARD DIAL NUMBER
</Number>
</Dial>
</Response>
</code></pre>
<p>Giving the <code><Number></code> noun a URL will play the TwiML contents of that URL before the two calls are connected. You can use <code><Gather></code> in here to make sure the user has answered the call and not their own voicemail system:</p>
<pre><code>/whisper
<Response>
<Gather numDigits="1" timeout="10" action="/gather_result">
<Say voice="alice">You are receiving a call, press any key to accept</Say>
</Gather>
<Hangup/>
</Response>
</code></pre>
<p>The <code>/gather_result</code> needs to work out whether a key was pressed or not. If it was pressed then we head through to the call, which we can do with an empty response as this gives control back to the original <code><Dial></code>. If no number was pressed we hangup this end, which causes the original <code><Dial></code> to complete and direct onto its <code>action</code> attribute. (I'm not sure what language you're working with but here is some Rubyish pseudo code)</p>
<pre><code>/gather_result
<Response>
if params["Digits"] and params["Digits"].empty?
<Hangup/>
end
</Response>
</code></pre>
<p><code>/call_complete</code> will then get called once the <code><Dial></code> action is over. If the status of the call at this point is "completed" or "answered" then the user has picked up the call and responded correctly to the whisper and we can hang up. If it's anything else, we redirect our call onto our voicemail recorder.</p>
<pre><code>/call_complete
<Response>
if params["DialCallStatus"] == "completed" or params["DialCallStatus"] == "answered"
<Hangup/>
else
<Say voice="alice">The call could not be answered this time, please leave a message</Say>
<Record action="/record_complete" />
end
</Response>
</code></pre>
<p>Then finally your <code>/record_complete</code> action can do whatever you want with the recording URL and hang up the call.</p>
<pre><code>/record_complete
<Response>
<Hangup/>
</Response>
</code></pre>
<p>This can all be achieved with Twimlets, as described <a href="https://www.twilio.com/blog/2011/06/build-your-own-google-voice-using-twilio-twimlets.html" rel="noreferrer">in this blog post</a>. Let me know if this helps at all.</p> |
21,143,028 | Exception in thread "main" java.util.InputMismatchException | <p>I need help with one exercise in java, I'm stuck on this error for 2 hours maybe. Any help would be great.</p>
<pre><code>Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at prodavnica.Prodavnica.main(Prodavnica.java:60)
Java Result: 1
</code></pre>
<hr />
<pre><code>package prodavnica;
public class Proizvod {
private String ime_proizvod;
private static int cena;
public Proizvod(String ime_proizvod, int cena) {
this.ime_proizvod = ime_proizvod;
this.cena=cena;
}
public String getIme_proizvod() {
return ime_proizvod;
}
public void setIme_proizvod(String ime_proizvod) {
this.ime_proizvod = ime_proizvod;
}
public static int getCena() {
return cena;
}
public static void setCena(int cena) {
Proizvod.cena = cena;
}
public void pecatiPodatoci(){
System.out.println("Ime: "+ime_proizvod+" Cena: "+cena);
}
}
</code></pre>
<p>AND:</p>
<pre><code>package prodavnica;
import java.util.Scanner;
public class Prodavnica {
private String ime_prodavnica;
private Proizvod proizvodi[]=new Proizvod[20];
public Prodavnica(String ime_prodavnica) {
this.ime_prodavnica = ime_prodavnica;
}
int br=0;
public void dodadiProizvod(Proizvod p){
proizvodi[br]=p;
br++;
}
public Proizvod najskapProizvod(){
Proizvod max=proizvodi[0];
for(int r=0;r<proizvodi.length;r++){
if(max.getCena()<proizvodi[r+1].getCena()){
max=proizvodi[r+1];
}
}
return max;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Prodavnica pro1=new Prodavnica("Tinex");
int n;
System.out.println("Vnesete kolku proizvodi ke stavite: ");
n=input.nextInt();
String imer = input.nextLine();
int cenar = input.nextInt();
pro1.dodadiProizvod(new Proizvod(imer, cenar));
System.out.println("Ime-pr: "+pro1.proizvodi[0].getIme_proizvod()+" Cena= "+pro1.proizvodi[0].getCena());
}
}
</code></pre>
<p>I can't enter The string "imer" or the int "cenar" on the variable "proizvodi" from the class Proizvod.</p> | 21,143,523 | 2 | 1 | null | 2014-01-15 16:35:09.647 UTC | 1 | 2022-09-08 07:33:38.45 UTC | 2022-09-08 04:58:10.947 UTC | null | 4,826,457 | null | 3,199,067 | null | 1 | 7 | java|program-entry-point|inputmismatchexception | 73,125 | <p>This Exception Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.</p>
<pre><code>String imer = input.next();// Use for String Input
input.nextLine();//Use for next line of input
int cenar = input.nextInt();
</code></pre> |
35,657,362 | How to return dynamic type struct in Golang? | <p>I am using Golang Revel for some web project and I did like 12 projects in that so far. In all of them I have a lot of code redundancy because of return types. Look at this two functions:</p>
<pre><code>func (c Helper) Brands() []*models.Brand{
//do some select on rethinkdb and populate correct model
var brands []*models.Brand
rows.All(&brands)
return brands
}
func (c Helper) BlogPosts() []*models.Post{
//do some select on rethinkdb and populate correct model
var posts []*models.Post
rows.All(&posts)
return posts
}
</code></pre>
<p>As you can see they they both returns same type of data (type struct).
My idea was just to pass string var like this:</p>
<pre><code>func (c Helper) ReturnModels(modelName string) []*interface{} {
//do rethinkdb select with modelName and return []*interface{} for modelName
}
</code></pre>
<p>Like this I can have just one helper for returning data types instead of
doing same thing over and over again for different models but same data type.</p>
<p>My questions are:</p>
<ol>
<li>Is this possible at all</li>
<li>If yes can you point me to right docs</li>
<li>If no, I will be more then happy to return your answer :)</li>
</ol> | 35,657,622 | 1 | 0 | null | 2016-02-26 16:51:09.433 UTC | 12 | 2016-08-03 09:50:25.02 UTC | 2016-08-03 09:50:25.02 UTC | user6169399 | null | null | 1,108,279 | null | 1 | 30 | go|revel | 46,217 | <p>Yes it's possible however your function should return <code>interface{}</code> and not <code>[]*interface</code>.</p>
<pre><code>func (c Helper) ReturnModels(modelName string) interface{} {}
</code></pre>
<p>In this case you could use <a href="https://golang.org/doc/effective_go.html#type_switch" rel="noreferrer">Type Switches and/or Type Assertions</a> to cast the return value into it's original type.</p>
<p><strong>Example</strong></p>
<p>Note: I've never used Revel, but the following snippet should give you an a general idea:</p>
<p><a href="https://play.golang.org/p/1sLXtWpnuW" rel="noreferrer">Playground</a></p>
<pre><code>package main
import "fmt"
type Post struct {
Author string
Content string
}
type Brand struct {
Name string
}
var database map[string]interface{}
func init() {
database = make(map[string]interface{})
brands := make([]Brand, 2)
brands[0] = Brand{Name: "Gucci"}
brands[1] = Brand{Name: "LV"}
database["brands"] = brands
posts := make([]Post, 1)
posts[0] = Post{Author: "J.K.R", Content: "Whatever"}
database["posts"] = posts
}
func main() {
fmt.Println("List of Brands: ")
if brands, ok := ReturnModels("brands").([]Brand); ok {
fmt.Printf("%v", brands)
}
fmt.Println("\nList of Posts: ")
if posts, ok := ReturnModels("posts").([]Post); ok {
fmt.Printf("%v", posts)
}
}
func ReturnModels(modelName string) interface{} {
return database[modelName]
}
</code></pre> |
8,617,162 | fast way to copy formatting in excel | <p>I have two bits of code. First a standard copy paste from cell A to cell B</p>
<pre><code>Sheets(sheet_).Cells(x, 1).Copy Destination:=Sheets("Output").Cells(startrow, 2)
</code></pre>
<p>I can do almost the same using </p>
<pre><code>Sheets("Output").Cells(startrow, 2) = Sheets(sheet_).Cells(x, 1)
</code></pre>
<p>Now this second method is much faster, avoiding copying to clipboard and pasting again. However it does not copy across the formatting as the first method does. The Second version is almost instant to copy 500 lines, while the first method adds about 5 seconds to the time. And the final version could be upwards of 5000 cells.</p>
<p>So my question can the second line be altered to included the cell formatting (mainly font colour) while still staying fast. </p>
<p>Ideally I would like to be able to copy the cell values to a array/list along with the font formatting so I can do further sorting and operations on them before I "paste" them back on to the worksheet.. </p>
<p>So my ideal solution would be some thing like </p>
<pre><code>for x = 0 to 5000
array(x) = Sheets(sheet_).Cells(x, 1) 'including formatting
next
for x = 0 to 5000
Sheets("Output").Cells(x, 1)
next
</code></pre>
<p>is it possible to use RTF strings in VBA or is that only possible in vb.net, etc. </p>
<p><em><strong>Answer</em>*</strong></p>
<p>Just to see how my origianl method and new method compar, here are the results or before and after </p>
<p>New code = 65msec</p>
<pre><code>Sheets("Output").Cells(startrow, 2) = Sheets(sheet_).Cells(x, 1)
Sheets("Output").Range("B" & startrow).Font.ColorIndex = Sheets(sheet_).Range("A" & x).Font.ColorIndex 'copy font colour as well
</code></pre>
<p>Old code = 1296msec</p>
<pre><code>'Sheets("Output").Cells(startrow, 2).Value = Sheets(sheet_).Cells(x, 1)
'Sheets(sheet_).Cells(x, 1).Copy
'Sheets("Output").Cells(startrow, 2).PasteSpecial (xlPasteFormats)
'Application.CutCopyMode = False
</code></pre> | 8,617,348 | 5 | 0 | null | 2011-12-23 14:27:05.227 UTC | 5 | 2015-07-02 11:16:23.68 UTC | 2011-12-23 21:12:00.253 UTC | null | 726,150 | null | 726,150 | null | 1 | 13 | vba|copy|format|rtf | 115,384 | <p>For me, you can't. But if that suits your needs, you could have speed <em>and</em> formatting by copying the whole range at once, instead of looping:</p>
<pre><code>range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)
</code></pre>
<p>And, by the way, you can build a custom range string, like <code>Range("B2:B4, B6, B11:B18")</code> </p>
<hr>
<p><strong>edit</strong>: if your source is "sparse", can't you just format the destination at once when the copy is finished ?</p> |
8,527,139 | Showing commits made directly to a branch, ignoring merges in Git | <p>When using git, is there a way to show commits made to a branch, while ignoring all commits that were brought in by merging? </p>
<p>I'm trying to review the code changes made on a branch while ignoring the ones we made on other branches that were merged in. I know it's damn near impossible to show a diff in that fashion, but I'd like to be able to find out which commits I need to review.</p> | 8,527,200 | 3 | 0 | null | 2011-12-15 21:53:23.863 UTC | 24 | 2019-01-02 13:42:17.033 UTC | 2011-12-15 22:10:57.23 UTC | null | 119,963 | null | 1,100,832 | null | 1 | 91 | git|merge|branch|diff | 24,389 | <h3><code>--no-merges</code></h3>
<p>Both parents have equal weight in many contexts in git. If you've always been consistent in merging other changes in then you may find that this gives you what you want.</p>
<pre><code>git log --no-merges --first-parent
</code></pre>
<p>Otherwise you may be able to exclude commits from other named branches.</p>
<pre><code>git log --no-merges ^other-branch-1 ^other-branch-2 ^other-branch-3
</code></pre>
<p>If you want to review the changes that you are going to merge back into a principal branch then the easiest thing to do is to perform the merge on a local clone and then just look at the diff with the first parent before publishing the merge.</p> |
47,671,732 | Keras - Input a 3 channel image into LSTM | <p>I have read a sequence of images into a numpy array with shape <code>(7338, 225, 1024, 3)</code> where <code>7338</code> is the sample size, <code>225</code> are the time steps and <code>1024 (32x32)</code> are flattened image pixels, in <code>3</code> channels (RGB).</p>
<p>I have a sequential model with an LSTM layer:</p>
<pre><code>model = Sequential()
model.add(LSTM(128, input_shape=(225, 1024, 3))
</code></pre>
<p>But this results in the error:</p>
<pre><code>Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4
</code></pre>
<p>The <a href="https://keras.io/layers/recurrent/" rel="noreferrer">documentation</a> mentions that the input tensor for LSTM layer should be a <code>3D tensor with shape (batch_size, timesteps, input_dim)</code>, but in my case my <code>input_dim</code> is 2D.</p>
<p>What is the suggested way to input a 3 channel image into an LSTM layer in Keras?</p> | 47,673,249 | 2 | 2 | null | 2017-12-06 10:12:40.403 UTC | 9 | 2021-03-12 10:51:54.903 UTC | 2017-12-06 10:49:23.99 UTC | null | 3,832,088 | null | 3,832,088 | null | 1 | 12 | python|keras|lstm|recurrent-neural-network | 13,675 | <p>If you want the number of images to be a sequence (like a movie with frames), you need to put pixels AND channels as features:</p>
<pre><code>input_shape = (225,3072) #a 3D input where the batch size 7338 wasn't informed
</code></pre>
<p>If you want more processing before throwing 3072 features into an LSTM, you can combine or interleave 2D convolutions and LSTMs for a more refined model (not necessarily better, though, each application has its particular behavior). </p>
<p>You can also try to use the new <a href="https://keras.io/layers/recurrent/#convlstm2d" rel="noreferrer">ConvLSTM2D</a>, which will take the five dimensional input:</p>
<pre><code>input_shape=(225,32,32,3) #a 5D input where the batch size 7338 wasn't informed
</code></pre>
<hr>
<p>I'd probably create a convolutional net with several <code>TimeDistributed(Conv2D(...))</code> and <code>TimeDistributed(MaxPooling2D(...))</code> before adding a <code>TimeDistributed(Flatten())</code> and finally the <code>LSTM()</code>. This will very probably improve both your image understanding and the performance of the LSTM. </p> |
27,128,425 | Add multiple custom views to layout programmatically | <p>If I for example have empty layout like this:</p>
<h3>layout1.xml</h3>
<pre class="lang-xml prettyprint-override"><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
</code></pre>
<p>And some other Layout like this:</p>
<h3>layout2.xml</h3>
<pre class="lang-xml prettyprint-override"><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:layout_weight="1"/>
</LinearLayout>
</code></pre>
<p>I would like to add <code>layout2.xml</code> to <code>layout1.xml</code> programmatically. I would need to have multiple different version <code>layout2.xml</code> which I would add when I want. Each one would have different text on <code>TextView</code> and <code>Button</code>s.</p>
<p>In case of regular Android <code>View</code> I would usually do it similarly like this with <code>addView</code>:</p>
<pre class="lang-java prettyprint-override"><code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv1 = new TextView(this);
tv1.setText("HELLO");
my_linear_layout.addView(tv1);
Button btn2 = new Button(this);
bt2.setText("WORLD");
my_linear_layout.addView(btn2);
}
</code></pre>
<p>How can I do it if I don't have something simple like <code>TextView</code> or <code>Button</code>, and if I have my own XML defined <code>View</code>?</p>
<p>Would it be possible to somehow put all the views inside adapter like for a <code>ListView</code> and then get it when needed and just call <code>addView</code> on those <code>View</code>s?</p> | 27,128,720 | 4 | 1 | null | 2014-11-25 13:46:27.757 UTC | 13 | 2021-11-18 14:11:17.173 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 3,304,086 | null | 1 | 37 | android|xml|android-layout|android-custom-view | 74,076 | <p>You can inflate the <code>layout2.xml</code> file, edit the texts, and add it to the first layout:</p>
<pre class="lang-java prettyprint-override"><code>public class MyActivity extends Activity {
private ViewGroup mLinearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
mLinearLayout = (ViewGroup) findViewById(R.id.linear_layout);
addLayout("This is text 1", "This is first button", "This is second Button");
}
private void addLayout(String textViewText, String buttonText1, String buttonText2) {
View layout2 = LayoutInflater.from(this).inflate(R.layout.layout2, mLinearLayout, false);
TextView textView = (TextView) layout2.findViewById(R.id.button1);
Button button1 = (Button) layout2.findViewById(R.id.button2);
Button button2 = (Button) layout2.findViewById(R.id.button3);
textView1.setText(textViewText);
button1.setText(buttonText1);
button2.setText(buttonText2);
mLinearLayout.addView(layout2);
}
}
</code></pre>
<p>You may want to change <code>android:layout_height</code> of the <code>layout2.xml</code> root view to <code>wrap_content</code>.</p>
<p>If you are using ViewBinding, here is how it would look like for the <code>addLayout</code> function :</p>
<pre class="lang-java prettyprint-override"><code>MyLayoutBinding binding = MyLayoutBinding.inflate(getLayoutInflater(), mLinearLayout, false);
binding.getTextView1().setText(textViewText);
binding.getButton1().setText(buttonText1);
binding.getButton2().setText(buttonText2);
mLinearLayout.addView(binding.getRoot());
</code></pre> |
43,633,452 | When to use square brackets [ ] in directives @Inputs and when not? | <p>I'm confused a little.</p>
<p>See this simple directive:</p>
<pre><code> @Directive({
selector: '[myDirective]'
})
export class MyDirective {
private text: string;
private enabled: boolean;
@Input() myDirective:string;
@Input('myText')
set myText(val: string) {
this.text = val;
}
@Input('myEnabled')
set myEnabled(val: boolean) {
this.enabled = val;
}
ngOnInit() {
console.log("myDirective string: " + this.myDirective);
console.log("myText string: " + this.text);
console.log("myEnabled boolean: " + this.enabled);
}
}
</code></pre>
<p>if my html will look like this:</p>
<pre><code><div [myDirective]="myDefaultText" [myEnabled]="true" [myText]="abc"></div>
</code></pre>
<p>The output will be:</p>
<pre><code>myDirective string: myDefaultText real value // good
myEnabled boolean: true // good
myText string: undefined // Why?
</code></pre>
<p>If I REMOVE the [] from <code>myText</code>:</p>
<pre><code><div [myDirective]="myDefaultText" [myEnabled]="true" myText="abc"></div>
</code></pre>
<p>The output will be:</p>
<pre><code>myDirective string: myDefaultText real value // good
myEnabled boolean: true // good
myText string: abc // GOOD
</code></pre>
<p>I can also remove the <code>[]</code> from <code>myEnabled</code> and it will work too.
So here is my confusion - when I need to use square brackets <code>[]</code> and when not, while I want the user who is going to use <code>myDirective</code> will never need to wonder if or if not, I think the square brackets <code>[]</code> should always be there. Aren't they?</p> | 43,633,605 | 6 | 0 | null | 2017-04-26 11:53:03.883 UTC | 18 | 2022-02-08 12:15:30.05 UTC | 2017-04-26 12:16:23.497 UTC | null | 573,032 | null | 1,555,548 | null | 1 | 85 | angular|typescript|angular2-directives | 45,962 | <p>When you use <code>[]</code> to bind to an <code>@Input()</code>, it's basically a template expression.</p>
<p>The same way displaying <code>{{abc}}</code> wouldn't display anything (unless you actually had a variable called <code>abc</code>).</p>
<p>If you have a string <code>@Input()</code>, and you want to bind it to a constant string, you could bind it like this: <code>[myText]=" 'some text' "</code>, or in short, like a normal HTML attribute: <code>myText="some text"</code>.</p>
<p>The reason <code>[myEnabled]="true"</code> worked is because <code>true</code> is a valid template expression which of course evaluates to the boolean <code>true</code>.</p> |
43,919,166 | Django and Celery - re-loading code into Celery after a change | <p>If I make a change to tasks.py while celery is running, is there a mechanism by which it can re-load the updated code? or do I have to shut Celery down a re-load?</p>
<p>I read celery had an <code>--autoreload</code> argument in older versions, but I can't find it in the current version: </p>
<p><code>celery: error: unrecognized arguments: --autoreload</code></p> | 43,929,298 | 4 | 0 | null | 2017-05-11 15:03:02.63 UTC | 8 | 2020-04-27 07:53:31.593 UTC | null | null | null | null | 282,918 | null | 1 | 28 | django|celery|django-celery | 12,719 | <p>Unfortunately <code>--autoreload</code> doesn't work and it is <a href="https://github.com/celery/celery/issues/1658" rel="noreferrer">deprecated</a>.</p>
<p>You can use Watchdog which provides watchmedo a shell utilitiy to perform actions based on file events. </p>
<pre><code>pip install watchdog
</code></pre>
<p>You can start worker with </p>
<pre><code>watchmedo auto-restart -- celery worker -l info -A foo
</code></pre>
<p>By default it will watch for all files in current directory. These can be changed by passing corresponding parameters.</p>
<pre><code>watchmedo auto-restart -d . -p '*.py' -- celery worker -l info -A foo
</code></pre>
<p>Add <code>-R</code> option to recursively watch the files. </p>
<p>If you are using django and don't want to depend on watchdog, there is a simple trick to achieve this. Django has autoreload utility which is used by runserver to restart WSGI server when code changes.</p>
<p>The same functionality can be used to reload celery workers. Create a seperate management command called celery. Write a function to kill existing worker and start a new worker. Now hook this function to autoreload as follows. For Django >= 2.2</p>
<pre><code>import sys
import shlex
import subprocess
from django.core.management.base import BaseCommand
from django.utils import autoreload
class Command(BaseCommand):
def handle(self, *args, **options):
autoreload.run_with_reloader(self._restart_celery)
@classmethod
def _restart_celery(cls):
if sys.platform == "win32":
cls.run('taskkill /f /t /im celery.exe')
cls.run('celery -A phoenix worker --loglevel=info --pool=solo')
else: # probably ok for linux2, cygwin and darwin. Not sure about os2, os2emx, riscos and atheos
cls.run('pkill celery')
cls.run('celery worker -l info -A foo')
@staticmethod
def run(cmd):
subprocess.call(shlex.split(cmd))
</code></pre>
<p>For django < 2.2</p>
<pre><code>import sys
import shlex
import subprocess
from django.core.management.base import BaseCommand
from django.utils import autoreload
class Command(BaseCommand):
def handle(self, *args, **options):
autoreload.main(self._restart_celery)
@classmethod
def _restart_celery(cls):
if sys.platform == "win32":
cls.run('taskkill /f /t /im celery.exe')
cls.run('celery -A phoenix worker --loglevel=info --pool=solo')
else: # probably ok for linux2, cygwin and darwin. Not sure about os2, os2emx, riscos and atheos
cls.run('pkill celery')
cls.run('celery worker -l info -A foo')
@staticmethod
def run(cmd):
subprocess.call(shlex.split(cmd))
</code></pre>
<p>Now you can run celery worker with <code>python manage.py celery</code> which will autoreload when codebase changes.</p>
<p>This is only for development purposes and do not use it in production.</p> |
1,073,396 | Is generator.next() visible in Python 3? | <p>I have a generator that generates a series, for example:</p>
<pre><code>def triangle_nums():
'''Generates a series of triangle numbers'''
tn = 0
counter = 1
while True:
tn += counter
yield tn
counter += + 1
</code></pre>
<p>In Python 2 I am able to make the following calls:</p>
<pre><code>g = triangle_nums() # get the generator
g.next() # get the next value
</code></pre>
<p>however in Python 3 if I execute the same two lines of code I get the following error:</p>
<pre><code>AttributeError: 'generator' object has no attribute 'next'
</code></pre>
<p>but, the loop iterator syntax does work in Python 3</p>
<pre><code>for n in triangle_nums():
if not exit_cond:
do_something()...
</code></pre>
<p>I haven't been able to find anything yet that explains this difference in behavior for Python 3.</p> | 1,073,582 | 3 | 0 | null | 2009-07-02 09:29:44.727 UTC | 43 | 2020-06-18 01:49:44.397 UTC | 2020-06-18 01:49:44.397 UTC | null | 3,064,538 | null | 14,555 | null | 1 | 285 | python|python-3.x|iteration | 151,546 | <p><code>g.next()</code> has been renamed to <code>g.__next__()</code>. The reason for this is consistency: special methods like <code>__init__()</code> and <code>__del__()</code> all have double underscores (or "dunder" in the current vernacular), and <code>.next()</code> was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]</p>
<p>But instead of calling <code>g.__next__()</code>, use <a href="https://docs.python.org/library/functions.html#next" rel="noreferrer"><code>next(g)</code></a>.</p>
<p>[*] There are other special attributes that have gotten this fix; <code>func_name</code>, is now <code>__name__</code>, <a href="https://docs.python.org/whatsnew/3.0.html#operators-and-special-methods" rel="noreferrer">etc.</a></p> |
1,276,753 | XPath - Select first element after some other element | <p>I'm fairly new to XPath, been fiddling around with it for a few hours now, so i'm not entirely sure if you can even do something like the following with it. </p>
<p><strong>Okay, here's the scenario:</strong> I want to find a link from a page. That link is only recognizable by it's text value, ie. the text between <a> tags (<a href="#">this link<a>). So far i've managed to get my hands on to link elements with that text, the only problem is that there's a few of those lying around. </p>
<p><em>These links are found from unordered lists which are preceded by another link tag, which would serve as a really good <strong>"anchor"</strong> point to begin the search for the final element that i want to find (ie. then i could just accept the first one that matches)</em></p>
<p><strong>To clarify things a bit, here's an example of what's going on:</strong></p>
<pre><code><a href="#">first dropdown menu</a>
<ul>
<li><a href="#">some link</a></li>
<li><a href="#">link i want to find</a></li>
</ul>
<-- *And i would actually want to find the thing from this list* -->
<a href="#">second dropdown menu</a>
<ul>
<li><a href="#">some link</a></li>
<li><a href="#">link i want to find</a></li>
</ul>
</code></pre>
<p>And i should probably specify, that i only want to receive either one result or a set of results with the first element being the "correct" element - the element i want to find. </p>
<p><strong>EDIT:</strong>
The question has been answered already, but there were some comments that I should specify this a bit more, so that people could actually understand the question ;)</p>
<p>So the idea was to use an element to specify the location of another element that could have duplicate search results scattered all around the document. </p>
<p>Essentially you would run into something like this if you wanted to find a given link from a group of dropdown menus that would have elements with same names or values. </p>
<p>That's basically it. I know that it's still a bit difficult to get the point, but unfortunately I'm having a hard time trying to explain it better. I'm sure that somebody else could do a better job and if that happens, I'm more than happy to include that description here. </p> | 1,276,826 | 3 | 1 | null | 2009-08-14 08:51:40.463 UTC | 14 | 2015-06-18 16:17:00.337 UTC | 2015-06-18 16:17:00.337 UTC | null | 2,877,364 | null | 7,382 | null | 1 | 57 | xpath | 82,609 | <p>I had to read through your question a couple of times but I think I understand it. What you are interested in is predicates. Predicates allow you to pick nodes based on conditions.</p>
<p>For example, you could do:</p>
<pre><code>//a[text()='second dropdown menu']/following::ul[1]/li/a[text()='link i want to find']
</code></pre>
<p>this would select any anchor with certain text in, find the next ul, then proceed through it's children.</p>
<p>Also, you can specify positional index within a result set, the following XPath is a demonstration (but it won't solve your problem):</p>
<pre><code>//a[text()='first dropdown menu']/ul/li[last()]/a/text()
</code></pre>
<p>or you could use axes to navigate across siblings/ancestors/children:</p>
<pre><code>//a[ancestor::ul/preceding::a[1]/text() = 'second dropdown menu']/text()
</code></pre>
<p>So I'm not sure I quite understood your question but this should help you write your XPath.</p>
<p>Basically, I'm assuming your XPath matches the anchor in multiple lists and you want to make sure you pick the right one. At some point in your XPath you need a predicate to specify a condition that will only be true for the list your desired node is in.</p> |
12,900,062 | C# Fill combo box from SQL DataTable | <pre><code>DataTable _dt = new DataTable();
using (SqlConnection _cs = new SqlConnection("Data Source=COMNAME; Initial Catalog=DATABASE; Integrated Security=True"))
{
string _query = "SELECT * FROM Doctor";
SqlCommand _cmd = new SqlCommand(_query, _cs);
using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
{
_da.Fill(_dt);
}
}
cbDoctor.DataSource = _dt;
foreach(DataRow _dr in _dt.Rows)
{
cbDoctor.Items.Add(_dr["name"].ToString());
}
</code></pre>
<p>There was an Error... </p>
<p>The result is <code>System.Data.DataRowView</code> instead of data from database..</p> | 12,900,421 | 3 | 2 | null | 2012-10-15 16:37:13.307 UTC | 1 | 2021-01-27 16:52:01.92 UTC | 2012-10-15 17:06:07.083 UTC | null | 275,567 | null | 790,226 | null | 1 | 1 | c#|sql | 57,498 | <p>I'm not yet sure what is the exact error in your code, but if you're ok with not using <code>DataTable</code>, you can do it this way:</p>
<pre><code>using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
cbDoctor.Items.Add(sqlReader["name"].ToString());
}
sqlReader.Close();
}
</code></pre>
<p>For more information take a look at <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx" rel="noreferrer">SqlDataReader reference on MSDN</a>.</p>
<p>In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.</p> |
28,738,331 | Show files in current directory using Git Bash? | <p>How can I check files in current directory, from git bash?
Like command <code>dir</code>, in Windows <code>cmd</code> ?</p>
<p>I found a command <code>git ls-files</code>, but it's work only with git repository files. But if I navegate through drive C:\, and want to see files in current directory, how can I do that in git bash?</p> | 28,738,397 | 4 | 1 | null | 2015-02-26 09:12:19.003 UTC | 8 | 2018-06-06 08:56:20.8 UTC | 2018-06-06 08:56:20.8 UTC | null | 4,505,446 | null | 2,206,822 | null | 1 | 23 | git|directory|git-bash|working-directory | 98,639 | <p>The git bash is basically a Unix shell, therefore you can list current files and directories with the <code>ls</code> command</p>
<p>You can also use <code>ls -a</code> to show hidden files and folders.</p>
<p>Since it is a Unix shell, you can make an alias called <code>dir</code> in a .bashrc file. It's handy when you are on windows, such that you don't have to remember both the Linux and the Windows command for listing directories.</p> |
23,985,887 | Install Error: 'rubygems' has no installation candidate | <p>Hi I would appreciate some help installing rubygems. This is what happens when I try. "ruby-full" has already been installed. How do I fix this? What is the issue?</p>
<pre><code>$ sudo apt-get install rubygems
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package rubygems is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
ruby
E: Package 'rubygems' has no installation candidate
</code></pre>
<p>I am running Ubuntu 14.04. Ruby version installed: 1:1.9.3.4. Please let me know if there are any other additional details that could help solve this issue.</p> | 24,045,909 | 1 | 0 | null | 2014-06-02 00:33:14.367 UTC | 13 | 2015-06-02 14:24:05.85 UTC | 2014-10-12 18:02:55.59 UTC | null | 3,103,033 | null | 3,103,033 | null | 1 | 52 | rubygems | 14,819 | <p>In <strong>Ubuntu 14.04</strong>, try the following:</p>
<pre><code>sudo apt-get install rubygems-integration
</code></pre> |
42,950,104 | How to save in a polymorphic relationship in Laravel? | <p>I'm reading the tutorial* on how to define many-to-many polymorphic relationships in Laravel but it doesn't show how to save records with this relationship.</p>
<p>In the their example they have</p>
<pre><code>class Post extends Model
{
/**
* Get all of the tags for the post.
*/
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
</code></pre>
<p>and</p>
<pre><code>class Tag extends Model
{
/**
* Get all of the posts that are assigned this tag.
*/
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
/**
* Get all of the videos that are assigned this tag.
*/
public function videos()
{
return $this->morphedByMany('App\Video', 'taggable');
}
}
</code></pre>
<p>I've tried saving in different ways but the attempts that makes most sense to me is:</p>
<pre><code>$tag = Tag::find(1);
$video = Video::find(1);
$tag->videos()->associate($video);
or
$tag->videos()->sync($video);
</code></pre>
<p>None of these are working. Can anyone give me a clue on what I could try?</p>
<ul>
<li><a href="https://laravel.com/docs/5.4/eloquent-relationships#many-to-many-polymorphic-relations" rel="noreferrer">https://laravel.com/docs/5.4/eloquent-relationships#many-to-many-polymorphic-relations</a></li>
</ul> | 42,950,233 | 7 | 1 | null | 2017-03-22 11:16:39.96 UTC | 6 | 2022-03-11 12:34:12.577 UTC | null | null | null | null | 1,647,948 | null | 1 | 31 | php|laravel|orm|polymorphism | 62,602 | <p>It's simple like that, see <a href="https://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models" rel="noreferrer">this</a> section.</p>
<blockquote>
<p>Instead of manually setting the attribute on the videos, you may insert the Comment directly from the relationship's save method:</p>
</blockquote>
<pre><code>//Create a new Tag instance (fill the array with your own database fields)
$tag = new Tag(['name' => 'Foo bar.']);
//Find the video to insert into a tag
$video = Video::find(1);
//In the tag relationship, save a new video
$tag->videos()->save($video);
</code></pre> |
66,489,605 | Is 'constructor LocationRequest()' deprecated in google maps v2? | <p>I stumbled upon this message recently, and I was pretty sure that this constructor wasn't deprecated in prior versions to 18.0.0, but I cannot find information anywhere that this one has been deprecated either.</p>
<p>And what should we use instead, is there another way to create a <code>locationRequest</code> ?</p>
<p><a href="https://i.stack.imgur.com/3IcJv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3IcJv.png" alt="message complaining that LocationRequest() is deprecated" /></a></p> | 66,489,771 | 5 | 0 | null | 2021-03-05 09:04:18.27 UTC | 3 | 2022-08-07 17:29:48.843 UTC | 2021-03-07 07:56:51.197 UTC | null | 4,475,206 | null | 4,475,206 | null | 1 | 40 | android|kotlin|google-maps-android-api-2|google-location-services | 15,492 | <p>Yes, the LocationRequest constructor is deprecated. You can use its static method <code>LocationRequest.create()</code> to create a location request.</p>
<p>Kotlin:</p>
<pre><code>locationRequest = LocationRequest.create().apply {
interval = 100
fastestInterval = 50
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
maxWaitTime = 100
}
</code></pre>
<p>Java:</p>
<pre><code>locationRequest = LocationRequest.create()
.setInterval(100)
.setFastestInterval(3000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setMaxWaitTime(100);
</code></pre>
<p><strong>Update</strong></p>
<p>As @Shimon pointed out <strong>LocationRequest.PRIORITY_HIGH_ACCURACY</strong> is now deprecated, so instead use
<strong>Priority.PRIORITY_HIGH_ACCURACY</strong></p> |
6,284,743 | Convert JSON String to JSON Array in rails? | <p>I have a JSON string in rails as shown below: </p>
<pre><code>[{"content":"1D","createdTime":"09-06-2011 00:59"},{"content":"2D","createdtime":"09-06-2011 08:00"}]
</code></pre>
<p>which are the objects of a class content with attributes content and created time.</p>
<p>I would like to <strong>convert this JSON string to its respective JSON object array</strong> so that I can run a loop and decode the JSON to its objects in rails. How can I achieve this?</p> | 6,284,787 | 3 | 0 | null | 2011-06-08 20:18:55.72 UTC | 9 | 2017-01-31 06:03:37.8 UTC | 2017-01-31 06:03:37.8 UTC | null | 4,758,119 | null | 598,714 | null | 1 | 37 | ruby-on-rails|ruby|json | 79,881 | <p>You can use the json library <a href="http://flori.github.com/json/">json</a></p>
<p>You can then do:</p>
<pre><code>jsonArray = [{"content":"1D","createdTime":"09-06-2011 00:59"},
{"content":"2D","createdtime":"09-06-2011 08:00"}]
objArray = JSON.parse(jsonArray)
</code></pre>
<p>In response to your comment, you can do this, as long as your JSON fits your model</p>
<pre><code>objArray.each do |object|
# This is a hash object so now create a new one.
newMyObject = MyObject.new(object)
newMyObject.save # You can do validation or any other processing around here.
end
</code></pre> |
6,097,370 | Calculation in DataGridView column | <p>I have a DataGridView in which I want to sum up values from two different columns into a third column.</p>
<p><strong>Example DataGridView:</strong></p>
<pre><code>A B Total
1 2 3
25 35 60
5 -5 0
</code></pre>
<p>I want to add (A+B) in total, just after entering values in <code>A & B column</code> or leaving current row. And also want to set Total Column as <code>ReadOnly</code>.</p> | 6,097,673 | 4 | 4 | null | 2011-05-23 12:44:06.08 UTC | 5 | 2015-08-27 20:26:08.957 UTC | 2011-05-23 13:02:26.7 UTC | null | 41,956 | null | 479,468 | null | 1 | 3 | c#|.net|winforms|datagridview | 38,415 | <p>You can do that on CellValidatedEvent and you can apply the same method to RowValidated:</p>
<pre><code> private void dataGridView_CellValidated(object sender, DataGridViewCellEventArgs e) {
if (e.RowIndex > -1) {
DataGridViewRow row = dataGridView.Rows[e.RowIndex];
string valueA = row.Cells[columnA.Index].Value.ToString();
string valueB = row.Cells[columnB.Index].Value.ToString();
int result;
if (Int32.TryParse(valueA, out result)
&& Int32.TryParse(valueB, out result)) {
row.Cells[columnTotal.Index].Value = valueA + valueB;
}
}
}
</code></pre>
<p>You can set column to ReadOnly in the designer, or like this:</p>
<pre><code>dataGridView.Columns["Total"].ReadOnly = true
</code></pre> |
5,744,207 | jQuery: outer html() | <p>imagine what we have something like this:</p>
<pre><code><div id="xxx"><p>Hello World</p></div>
</code></pre>
<p>if we call .html function in this way:</p>
<pre><code>$("#xxx").html();
</code></pre>
<p>we will get:</p>
<pre><code><p>Hello World</p>
</code></pre>
<p>But i need to get:</p>
<pre><code><div id="xxx"><p>Hello World</p></div>
</code></pre>
<p>So, what i need to do? I think to add another wrapper around #xxx, but this is not a good idea.</p> | 5,744,246 | 4 | 2 | null | 2011-04-21 12:37:28.95 UTC | 45 | 2021-09-16 11:07:53.447 UTC | 2020-02-02 13:31:12.323 UTC | null | 584,192 | null | 190,454 | null | 1 | 373 | jquery | 419,949 | <p>Create a temporary element, then <code>clone()</code> and <code>append()</code>:</p>
<pre><code>$('<div>').append($('#xxx').clone()).html();
</code></pre> |
2,238,611 | How to change string date to MySQL date format at time of import of CSV using MySQL's LOAD DATA LOCAL INFILE | <p>I'm using MySQL's LOAD DATA LOCAL INFILE SQL statement to load data from a CSV file into an existing database table.</p>
<p>Here is an example SQL statement:</p>
<pre><code>LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE my_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(name, address, dateOfBirth)
</code></pre>
<p>The third column in the CSV that maps to the dateOfBirth field currently has the date in the following format:</p>
<pre><code>14-Feb-10
</code></pre>
<p>How can I modify the above SQL statement to format the date into MySQL's date format i.e. <code>2010-02-14</code>?</p>
<p>I know how to convert a string date when using normal INSERT syntax using:</p>
<p><code>STR_TO_DATE('14-Feb-10', '%d-%b-%y')</code></p> | 2,239,127 | 2 | 0 | null | 2010-02-10 16:46:56.62 UTC | 4 | 2013-07-04 08:54:29.943 UTC | 2012-01-24 16:51:52.21 UTC | null | 59,870 | null | 248,848 | null | 1 | 17 | sql|mysql|datetime|load-data-infile | 43,772 | <p>You need to use the <code>SET</code> clause, along with a variable to reference the contents of the row at that column. In your column list, you assign your date column to a variable name. You can then use it in your <code>SET</code> statement. (Note, I haven't got MySQL in front of me to test this on.)</p>
<pre><code>LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE my_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(name, address, @var1)
set dateOfBirth = STR_TO_DATE(@var1, '%d-%b-%y')
</code></pre>
<p>See examples a way down the page at: <a href="http://mysql2.mirrors-r-us.net/doc/refman/5.1/en/load-data.html" rel="noreferrer">http://mysql2.mirrors-r-us.net/doc/refman/5.1/en/load-data.html</a> (Not sure why this page seems to differ from the main documentation in that it actually contains an example of <code>SET</code> usage.)</p> |
29,518,137 | jq: selecting a subset of keys from an object | <p>Given an input json string of keys from an array, return an object with only the entries that had keys in the original object and in the input array.</p>
<p>I have a solution but I think that it isn't elegant (<code>{($k):$input[$k]}</code> feels especially clunky...) and that this is a chance for me to learn.</p>
<pre><code>jq -n '{"1":"a","2":"b","3":"c"}' \
| jq --arg keys '["1","3","4"]' \
'. as $input
| ( $keys | fromjson )
| map( . as $k
| $input
| select(has($k))
| {($k):$input[$k]}
)
| add'
</code></pre>
<p>Any ideas how to clean this up?</p>
<p>I feel like <a href="https://stackoverflow.com/questions/29259249/extracting-selected-properties-from-a-nested-json-object-with-jq">Extracting selected properties from a nested JSON object with jq</a> is a good starting place but i cannot get it to work.</p> | 46,293,301 | 5 | 1 | null | 2015-04-08 14:52:20.473 UTC | 8 | 2018-08-21 20:48:30.797 UTC | 2017-05-23 11:46:34.517 UTC | null | -1 | null | 1,779,702 | null | 1 | 30 | json|select|key|subset|jq | 41,271 | <p>the inside operator works for most of time; however, I just found the inside operator has side effect, sometimes it selected keys not desired, suppose input is <code>{ "key1": val1, "key2": val2, "key12": val12 }</code> and select by <code>inside(["key12"])</code> it will select both <code>"key1"</code> and <code>"key12"</code></p>
<p>use the in operator if need an exact match: like this will select <code>.key2</code> and <code>.key12</code> only</p>
<pre><code>jq 'with_entries(select(.key | in({"key2":1, "key12":1})))'
</code></pre>
<p>because the in operator checks key from an object only (or index <code>exists?</code> from an array), here it has to be written in an object syntax, with desired keys as keys, but values do not matter; the use of in operator is not a perfect one for this purpose, I would like to see the Javascript ES6 includes API's reverse version to be implemented as jq builtin</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes</a></p>
<pre><code>jq 'with_entries(select(.key | included(["key2", "key12"])))'
</code></pre>
<p>to check an item <code>.key</code> is <code>included?</code> from an array</p> |
50,313,525 | Room Using Date field | <p>I am using date converter class to convert my date object. However, I still encounter an error saying. error: Cannot figure out how to save this field into a database. You can consider adding a type converter for it.</p>
<p><strong>My Date Converter class</strong></p>
<pre><code>public class DateConverter {
@TypeConverter
public static Date toDate(Long dateLong){
return dateLong == null ? null: new Date(dateLong);
}
@TypeConverter
public static long fromDate(Date date){
return date == null ? null :date.getTime();
}
}
</code></pre>
<p><strong>My Database table for using the date object.</strong></p>
<pre><code>@Entity(tableName = "userFitnessDailyRecords")
@TypeConverters(DateConverter.class)
public class UserFitnessDailyRecords {
@NonNull
@PrimaryKey(autoGenerate = true)
public int id;
public Date forDay;
public Date getForDay() {
return forDay;
}
public void setForDay(Date forDay) {
this.forDay = forDay;
}
}
</code></pre>
<p>I followed the example from google code persistence labs and from commonwares room respective GitHub example. I am using room version 1.0.0. </p> | 50,316,000 | 9 | 1 | null | 2018-05-13 06:52:45.18 UTC | 11 | 2021-12-26 14:23:13.717 UTC | 2018-05-13 08:47:40.277 UTC | null | 2,649,012 | null | 899,074 | null | 1 | 45 | android|android-room|android-database|android-date | 50,943 | <p>You're converting from Date to <strong>Long</strong> (wrapper) and from <strong>long</strong> (primitive) to Date. I changed it to Long and it compiled. Besides, unboxing null in your converter produces a NPE.</p>
<pre><code>public class DateConverter {
@TypeConverter
public static Date toDate(Long dateLong){
return dateLong == null ? null: new Date(dateLong);
}
@TypeConverter
public static Long fromDate(Date date){
return date == null ? null : date.getTime();
}
}
</code></pre> |
5,716,021 | jQuery form input select by id | <h2>Code</h2>
<pre><code><form id='a'>
<input id='b' value='dave'>
</form>
</code></pre>
<h2>Question</h2>
<p>How do I get the value from input 'b' while at the same time make sure it is inside 'a' (something like <code>$('#a:input[id=b]')</code>).</p>
<p>I only ask because I might have other inputs called 'b' somewhere else in my page and I want to make sure I'm getting the value from the correct form.</p> | 5,716,060 | 5 | 3 | null | 2011-04-19 12:02:14.143 UTC | 0 | 2015-11-06 00:00:54.21 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 563,247 | null | 1 | 13 | jquery | 125,638 | <p>You can do that using the descendant selectors:</p>
<pre><code> $("#a #b")
</code></pre>
<p>However, id values are supposed to be unique on a page.</p> |
5,878,131 | Referencing multiple submit buttons in django | <p>How would I call on the following multiple submit forms -- </p>
<pre><code><form action="/" method="post">
{% csrf_token %}
<input type="text" name="{{ email.id }}" value=" {{email}}"></td>
<td><input type="submit" value="Edit"></td>
<td><input type="submit" value="Delete"></td>
</tr>
</form>
</code></pre>
<p>I want to do something like this --</p>
<pre><code>if value = edit:
do this
if value = delete:
do this
</code></pre>
<p>How would I code this in the views.py file?</p> | 5,878,171 | 5 | 0 | null | 2011-05-04 03:22:23.023 UTC | 9 | 2020-02-01 11:32:33.877 UTC | null | null | null | null | 651,174 | null | 1 | 19 | django | 20,546 | <p>Give the input types a name and look for them in your <code>request.POST</code> dictionary. </p>
<p>E.g.:</p>
<pre><code><form action="/" method="post">
{% csrf_token %}
<input type="text" name="{{ email.id }}" value=" {{email}}"></td>
<td><input type="submit" value="Edit" name="_edit"></td>
<td><input type="submit" value="Delete" name="_delete"></td>
</tr>
</code></pre>
<p>and in views.py something like</p>
<pre><code>if request.POST:
if '_edit' in request.POST:
do_edit()
elif '_delete' in request.POST:
do_delete()
</code></pre>
<p>EDIT: Changed <code>d.has_key(k)</code> to <code>k in d</code> per Daniel's comment. <code>has_key</code> is deprecated in python 3.0 and the in style is preferred as its more generic -- specifically <code>d.has_key(k)</code> fails if d isn't a dictionary, but <code>k in d</code> works for any <code>d</code> that's an iterable (e.g., dict, string, tuple, list, set).</p> |
6,297,072 | Color for the PROMPT (just the PROMPT proper) in cmd.exe and PowerShell? | <p>So in Bash you just configure <code>PS1</code> to add colors to your prompt. I'm talking about the prompt proper, not the color of the foreground (text) or the background. And it's really easy in Bash and it helps a lot if you need to find your commands in a sea of messy text output.</p>
<p>Can you achieve the same for <code>cmd.exe</code>, or as a fallback, for PowerShell? A colored prompt?</p>
<p>I don't know if it could be done in the old days before Win32 by loading <code>ANSI.SYS</code>. I think that was just to make the foreground and the background colorful. But I might be wrong. And anyway, those days are gone, and in our modern times (I know), we're using <code>cmd.exe</code>, or PowerShell.</p>
<p>I know both cmd.exe and PowerShell are capable of colored output. For cmd.exe, just run <code>color /?</code> to find out. But my question is not about the foreground and the background, that's all known to humankind - it's about just changing the prompt color for cmd.exe, probably via the <code>PROMPT</code> environment variable as via the <code>PS1</code> variable for Bash? Is it possible?</p>
<p>And no, Cygwin is not an alternative for this. I'm a Cygwin user with MinTTY and all, and I love it. But I still want my <code>cmd.exe</code> prompt colored, too.</p> | 6,298,825 | 5 | 0 | null | 2011-06-09 17:47:44.193 UTC | 11 | 2019-07-26 13:36:03.593 UTC | 2011-06-09 22:40:16.363 UTC | null | 269,126 | null | 269,126 | null | 1 | 26 | powershell|command-prompt|prompt|cmd | 17,231 | <p>follow this link. There's an ANSI hack developped for the CMD.exe shell</p>
<p><a href="http://gynvael.coldwind.pl/?id=188&lang=en" rel="noreferrer">link to ansi hack</a></p>
<p>I've tried it on my win 7 professional SP1 and works like a charm </p>
<p><img src="https://i.stack.imgur.com/J1aOR.jpg" alt="enter image description here"></p> |
5,868,733 | What do we need the PHP-exception code for? Any use case scenario? | <p>Okay, its a very lame question for many but I hope I will have overwhelming response :)</p>
<p>When I throw an Exception in PHP I can add a code to the message.<br>
I catch an exception and handle it according to its type (Like <code>InvalidArgumentException</code> or <code>OutOfBoundException</code>). I log the <strong>message</strong> or display it or do whatever is suitable.<br>
I can add also append a previous exception to trace a path to the origin of the error.<br></p>
<p>BUT one thing I have never used or never thought of: how useful is <strong>code</strong>?<br></p>
<p>For example: <br></p>
<pre><code>throw new Exception("db Error", $code, $previousException);
</code></pre>
<p>What do I do with <code>$code</code>?</p> | 5,868,791 | 6 | 2 | null | 2011-05-03 11:25:44.073 UTC | 4 | 2022-06-23 13:48:09.12 UTC | 2015-05-04 14:49:53.91 UTC | null | 3,218,828 | null | 260,998 | null | 1 | 52 | php|exception|exception-handling | 22,496 | <p>The message is for display to the user, while the code is for use by your program. So for example, in your "database error" example, you might make up a set of codes like</p>
<ol>
<li>Can't connect</li>
<li>Error during query</li>
<li>Empty result</li>
<li>Error closing connection</li>
</ol>
<p>and then use the appropriate code. Then when other parts of your code saw they exception, they would know what happened and could possibly deal with it intelligently.</p> |
6,282,198 | Reading string from input with space character? | <p>I'm using Ubuntu and I'm also using Geany and CodeBlock as my IDE.
What I'm trying to do is reading a string (like <code>"Barack Obama"</code>) and put it in a variable:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
scanf("%s", name);
printf("Your Name is: %s", name);
return 0;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Enter your name: Barack Obama
Your Name is: Barack
</code></pre>
<p>How can I make the program read the whole name?</p> | 6,282,236 | 13 | 1 | null | 2011-06-08 16:37:35.023 UTC | 96 | 2018-08-31 09:43:37.313 UTC | 2018-06-17 16:41:18.303 UTC | null | 694,576 | null | 1,087,430 | null | 1 | 113 | c|string|input|scanf|whitespace | 586,298 | <p>Use:</p>
<pre><code>fgets (name, 100, stdin);
</code></pre>
<p><code>100</code> is the max length of the buffer. You should adjust it as per your need.</p>
<p>Use:</p>
<pre><code>scanf ("%[^\n]%*c", name);
</code></pre>
<p>The <code>[]</code> is the scanset character. <code>[^\n]</code> tells that while the input is <em>not</em> a newline (<code>'\n'</code>) take input. Then with the <code>%*c</code> it reads the newline character from the input buffer (which is not read), and the <code>*</code> indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.</p>
<p>Read here about the <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html">scanset</a> and the <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html">assignment suppression</a> operators.</p>
<p>Note you can also use <code>gets</code> but ....</p>
<blockquote>
<p>Never use <code>gets()</code>. Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because <code>gets()</code> will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use <code>fgets()</code> instead.</p>
</blockquote> |
46,340,106 | Activity with multiple ViewModels | <p>I have an <code>Activity</code> that contains 3 <code>RecyclerViews</code>. I need populate <code>RecyclerViews</code> with data from remote repository (3 different requests). Can I use multiple <code>ViewModels</code> in the <code>Activity</code>, or is there any better solution (best practice).</p> | 47,081,594 | 4 | 1 | null | 2017-09-21 09:22:07.18 UTC | 9 | 2018-09-01 09:11:43.533 UTC | 2017-11-10 08:56:14.01 UTC | null | 1,000,551 | null | 1,635,108 | null | 1 | 38 | android|viewmodel|android-architecture-components | 26,538 | <p>In this case I would recommend to use one view model which populates three different LiveData objects. This way the UI can get updated whenever one of your three requests gets a response. For details how to use a RecyclerView with LiveData take a look into the <a href="https://github.com/googlesamples/android-architecture-components/blob/master/BasicSample/app/src/main/java/com/example/android/persistence/ui/ProductFragment.java" rel="noreferrer">Google Example</a>.</p>
<p>I think having multiple viewmodels per activity only increases complexity and I do not see any value in doing that.</p> |
39,037,049 | How to upload a file and JSON data in Postman? | <p>I am using Spring MVC and this is my method:</p>
<pre><code>/**
* Upload single file using Spring Controller.
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(
@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,
HttpServletRequest request,
HttpServletResponse response) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists()) {
dir.mkdirs();
}
// Create the file on server
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location=" + serverFile.getAbsolutePath());
return null;
} catch (Exception e) {
return null;
}
}
}
</code></pre>
<p><br>
I need to pass the session id in postman and also the file. How can I do that?</p> | 39,037,889 | 24 | 2 | null | 2016-08-19 10:43:59.203 UTC | 82 | 2022-07-04 21:50:45.79 UTC | 2020-02-12 11:31:31.847 UTC | null | 814,702 | null | 6,059,272 | null | 1 | 380 | java|json|spring-mvc|postman | 787,657 | <p>In postman, set method type to <strong>POST</strong>.</p>
<p>Then select
Body -> form-data -> Enter your parameter name (<strong>file</strong> according to your code)</p>
<p>On the right side of the Key field, while hovering your mouse over it, there is a <strong>dropdown menu</strong> to select between <strong>Text/File</strong>. Select File, then a "Select Files" button will appear in the Value field.</p>
<p>For rest of <strong>"text" based parameters</strong>, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.</p> |
25,197,249 | Best way to Upgrade wamp 2.0 to 2.5 | <p>My wamp 2.0 is using around more than 100 large database and a lot of projects.I also made around more than 50 virtual host. Now I need to upgrade wamp 2.0 to 2.5.</p>
<p>I got some suggestion on internet that take back up of database and files , then uninstall wamp 2.0 and install 2.5 then set up every thing again, but it seems it is not a right way.</p>
<p>What is the best way ?</p> | 25,197,724 | 4 | 1 | null | 2014-08-08 06:30:14.723 UTC | 15 | 2019-09-24 03:53:55.61 UTC | null | null | null | null | 3,921,073 | null | 1 | 27 | wamp|upgrade | 35,213 | <p>Usually I follow following steps to do it easily.</p>
<ol>
<li>Stop Wamp Service</li>
<li>Rename the wamp folder to wamp-backup</li>
<li>Download latest version of wamp and install it</li>
<li>Rename the data folder of mysql with some different name
(C:\wamp\bin\mysql\mysql5.5.20)</li>
<li>copy data folder of mysql from wamp-backup and paste it to new
install wamp mysql folder (C:\wamp\bin\mysql\mysql5.5.20)</li>
<li>Rename new httpd-vhosts.conf file to httpd-vhosts-backup.conf.</li>
<li>Copy old httpd-vhosts.conf and paste to new installed wamp
(C:\wamp\bin\apache\Apache2.2.21\conf\extra)</li>
<li>In apache 2.4, the directive Allow was dropped in favor of new
directive Require. So change the settings from Order Deny,Allow
Deny from all Allow from all to Require all granted</li>
</ol>
<p>From</p>
<pre><code>Order Deny,Allow
Deny from all
Allow from all
</code></pre>
<p>to</p>
<pre><code>Require all granted
</code></pre>
<p>9.The old www folder in wamp needs to be copied into the new one.
Let me know whether it's working or not.</p> |
24,718,824 | Manifest merger failed : uses-sdk:minSdkVersion 8 cannot be smaller | <p>The problem is..</p>
<pre><code>Error:Execution failed for task ':app:processDebugManifest'.
</code></pre>
<blockquote>
<p>Manifest merger failed : uses-sdk:minSdkVersion 8 cannot be smaller than version L declared in library com.android.support:support-v4:21.0.0-rc1</p>
</blockquote>
<p>The code in build.gradle</p>
<pre><code> apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.androidexample.gcm"
minSdkVersion 8
targetSdkVersion 16
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile 'com.android.support:support-v4:+'
compile 'com.google.android.gms:play-services:+'
//compile 'com.android.support:support-v4:20.0.0'
//compile 'com.google.android.gms:play-services:5.0.77'
}
</code></pre>
<p>Code in the AndroidManifest is ..</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.gcm"
android:versionCode="1"
android:versionName="1.0" >
<!-- GCM requires Android SDK version 2.2 (API level 8) or above. -->
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<!-- Main activity. -->
<application
android:name="com.androidexample.gcm.Controller"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<!-- Register Activity -->
<activity
android:name="com.androidexample.gcm.RegisterActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.DELETE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="com.idrivecare.familypro" />
</intent-filter>
</activity>
<!-- Main Activity -->
<activity
android:name="com.androidexample.gcm.MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name" >
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.androidexample.gcm" />
</intent-filter>
</receiver>
<service android:name="com.androidexample.gcm.GCMIntentService" />
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
</application>
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.androidexample.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.androidexample.gcm.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Network State Permissions to detect Internet status -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
</manifest>
</code></pre>
<p>Thank you sir..</p> | 24,718,859 | 6 | 1 | null | 2014-07-13 01:36:56.417 UTC | 7 | 2017-07-13 05:40:10.147 UTC | null | null | null | null | 1,438,799 | null | 1 | 34 | java|android | 81,651 | <p>If you use</p>
<pre><code>'com.android.support:support-v4:+'
</code></pre>
<p>It will suppose it can use 21.x since is the latest version (but not compatible with target less than L)</p>
<p>Change it to</p>
<pre><code>'com.android.support:support-v4:20.+'
</code></pre>
<p>So it will download the latest 20.x version</p> |
48,895,103 | Why use Arrow's Options instead of Kotlin nullable | <p>I was having a look at the Arrow library found <a href="https://github.com/arrow-kt/arrow" rel="noreferrer">here</a>. Why would ever want to use an <code>Option</code> type instead of Kotlin's built in nullables?</p> | 48,895,668 | 3 | 2 | null | 2018-02-20 22:12:45.287 UTC | 8 | 2022-04-20 07:38:50.41 UTC | 2018-10-16 20:11:58.103 UTC | null | 9,585 | null | 4,564,505 | null | 1 | 25 | kotlin|functional-programming|arrow-kt | 7,384 | <p><strong>Disclaimer</strong>: If you really want to have a detailed talk about why <em>Arrow</em> is useful, then please head over to <a href="https://soundcloud.com/user-38099918/arrow-functional-library" rel="nofollow noreferrer">https://soundcloud.com/user-38099918/arrow-functional-library</a> and listen to one of the people who work on it. <em>(5:35min)</em></p>
<p>The people who create and use that library simple want to use Kotlin differently than the people who created it and use <a href="http://arrow-kt.io/docs/datatypes/option/" rel="nofollow noreferrer">"the Option datatype similar to how Scala, Haskell and other FP languages handle optional values"</a>.</p>
<p>This is just another way of defining return types of values that you do not know the output of.</p>
<p>Let me show you three versions:</p>
<p><strong>nullability in Kotlin</strong></p>
<pre><code>val someString: String? = if (condition) "String" else null
</code></pre>
<p><strong>object with another value</strong></p>
<pre><code>val someString: String = if (condition) "String" else ""
</code></pre>
<p><strong>the Arrow version</strong></p>
<pre><code>val someString: Option<String> = if (condition) Some("String") else None
</code></pre>
<p>A major part of Kotlin logic can be to never use <a href="https://kotlinlang.org/docs/reference/null-safety.html" rel="nofollow noreferrer">nullable types</a> like <code>String?</code>, but you will need to use it when interopting with Java. When doing that you need to use safe calls like <code>string?.split("a")</code> or the <a href="https://kotlinlang.org/docs/reference/null-safety.html#the--operator" rel="nofollow noreferrer">not-null assertion</a> <code>string!!.split("a")</code>.</p>
<p>I think it is perfectly valid to use safe calls when using Java libraries, but the <a href="https://github.com/arrow-kt" rel="nofollow noreferrer">Arrow guys</a> seem to think different and want to use their logic all the time.</p>
<p>The benefit of using the Arrow logic is <a href="https://github.com/arrow-kt/arrow" rel="nofollow noreferrer">"empowering users to define pure FP apps and libraries built atop higher order abstractions. Use the below list to learn more about Λrrow's main features"</a>.</p> |
27,876,306 | User registration/authentication flow on a REST API | <p>I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.</p>
<p>I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.</p>
<p>I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.</p>
<h2>REGISTER</h2>
<p>I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:</p>
<ul>
<li><p>My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?</p>
</li>
<li><p>If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in <a href="https://stackoverflow.com/a/25953066/2129043">this answer</a>. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?</p>
</li>
</ul>
<p>For now my flow works like follows:</p>
<pre><code>1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
</code></pre>
<p>The token never expires, preserving REST statelessness.</p>
<h2>EMAIL VALIDATION</h2>
<p>Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.</p>
<p>Normally I'd go for the following workflow:</p>
<pre><code>1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
</code></pre>
<p>This looks overcomplicated and totally ruins the UX. How'd you go about it?</p>
<h2>LOGIN</h2>
<p>This is quite simple, for now I am doing it this way so please correct me if wrong:</p>
<pre><code>1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
</code></pre>
<p>login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.</p>
<h2>LOGOUT</h2>
<p>Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.</p>
<p>As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.</p>
<h2>REMEMBER ME</h2>
<p>I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?</p>
<p>If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!</p> | 44,358,651 | 3 | 2 | null | 2015-01-10 12:37:55.003 UTC | 22 | 2018-12-27 22:08:44.787 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,129,043 | null | 1 | 37 | api|rest|authentication|web-applications|asp.net-web-api | 29,526 | <p><strong>REGISTER</strong></p>
<blockquote>
<p>Tokens that expire/tokens per session are not complying with the statelessness of REST, right?</p>
</blockquote>
<p>No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.</p>
<blockquote>
<p>My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?</p>
</blockquote>
<p>Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:</p>
<ol>
<li>Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).</li>
<li>If you want be more RESTful, I'll offer an alternative.</li>
</ol>
<p>Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.</p>
<p>That still leaves you with the problem of creating a user on your API, and in response to this (<code>POST</code>) call, returning a secret which can be used as an access/refresh token.</p>
<p>My alternative is as follows:</p>
<p><strong>You don't need to have a user in order to start a session</strong>.</p>
<p>What you can do instead is start the session <em>before</em> you create the user. This guarantees that for any future call, you know you are talking to the same client.</p>
<p>If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on <code>/users</code>. What this means is that your system needs to be aware of 2 types of authenticated users:</p>
<ol>
<li>Users that logged in with a username/password (`grant_type = passsword1).</li>
<li>Users that logged in 'anonymously' and intend to create a user after the fact. (<code>grant_type = client_credentials</code>).</li>
</ol>
<p>Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.</p>
<p><strong>EMAIL VALIDATION</strong></p>
<p>Both your suggestions to either:</p>
<ul>
<li>Prevent the user from using the application until email validation is completed.</li>
<li>Allow the user to use the application immediately</li>
</ul>
<p>Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.</p>
<p>Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.</p>
<p>You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.</p>
<p>There's no right answer here, it just depends on how you intend to use the email address.</p>
<p><strong>LOGIN</strong></p>
<p>Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an <em>actually</em> use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.</p>
<p>Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is <em>not that hard</em> and you're already fairly close to building something similar.</p>
<p><strong>LOGOUT</strong></p>
<p>The two reasons you might want a logout endpoint are:</p>
<ol>
<li>If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.</li>
<li>If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that <em>could</em> be a reason why you would want it.</li>
</ol>
<p><strong>REMEMBER ME</strong></p>
<p>Yea, implementing "remember me" with local storage sounds like a good idea.</p> |
9,334,095 | background-size:100% 100%; doesn't work properly in Chrome | <p>I'm using an svg image as a background. I'm trying to use CSS3's <code>background-size: 100% 100%;</code> but it doesn't seem to work, even in browsers which should support it (like Chrome).</p>
<p>If you look at <a href="http://www.imadake.ca/" rel="noreferrer">this site</a> you'll see the <code>#special-post article</code> (to the right/below the food image) with a red banner-looking background. Notice that as you shrink the window down, the height of the background image drops to retain it's proportions, rather then stretching, as I would like.</p>
<p>EDIT:
I checked this on FireFox and it works correctly... so this appears to be a webkit issue.</p>
<p>EDIT:
I checked this on Safari and it works! So it looks like my problem is specific to Chrome.</p>
<p><img src="https://dl-web.dropbox.com/get/Public/background100-100.png?w=0d3d0045" /></p>
<p>(PS: I'm familiar with <a href="https://stackoverflow.com/questions/1150163/stretch-and-scale-a-css-image-background-with-css-only">this</a> alternative solution, using an <code>img</code> tag, but I'd rather not use it.)</p> | 11,281,157 | 4 | 0 | null | 2012-02-17 19:22:24.857 UTC | 9 | 2014-12-04 20:30:19.237 UTC | 2017-05-23 11:54:44.313 UTC | null | -1 | null | 1,141,918 | null | 1 | 31 | google-chrome|css|background-image | 17,480 | <p>Here's a workaround:</p>
<p>Open your <code>.svg</code> file, find the <code><svg></code> tag at the beginning and add the following property inside it: </p>
<pre><code>preserveAspectRatio="none"
</code></pre>
<p>Source: <a href="http://www.yootheme.com/support/question/6801?order=modified" rel="noreferrer">http://www.yootheme.com/support/question/6801?order=modified</a></p> |
52,081,383 | (Kotlin) Backend Internal error: Exception during code generation | <p>I am creating a very thorough converter for Android with Kotlin, using the latest Android Studio Canary build and latest Kotlin.
I am suddenly getting a compiling error, even thought Android Studio doesn't see any bug in the code, it is complaining about a backend error, so I think my project is good but the Android Studio has a bug?? Please help confirm, this has been a lot of work....</p>
<p>It is complaining about my class MassCalc, which is 6500 lines long, because of many cases for conversion, so maybe that is the problem??</p>
<p>UPDATE
The error does not occur when hitting Clean project or Rebuild Project, it occurs when I try to launch it in the emulator!</p>
<p>Very simple code but long file: </p>
<p><a href="https://github.com/Josep-Jesus-Bigorra-Algaba/SuperConverterAndroid" rel="noreferrer">https://github.com/Josep-Jesus-Bigorra-Algaba/SuperConverterAndroid</a></p>
<p>I am experienced with Java but had never seen this exception!</p>
<pre><code>e: java.lang.IllegalStateException: Backend Internal error: Exception during code generation
</code></pre>
<p>Also:</p>
<pre><code>org.gradle.execution.MultipleBuildFailures: Build completed with 1 failures.
at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:350)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:216)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:146)
at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:121)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:77)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:74)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
at org.gradle.internal.work.StopShieldingWorkerLeaseService.withLocks(StopShieldingWorkerLeaseService.java:38)
at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:96)
at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:74)
at org.gradle.tooling.internal.provider.runner.ClientProvidedBuildActionRunner.run(ClientProvidedBuildActionRunner.java:68)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$3.run(RunAsBuildOperationBuildActionRunner.java:47)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:43)
at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:50)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$1.transform(InProcessBuildActionExecuter.java:46)
at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:74)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:46)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:32)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:62)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:34)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:59)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:46)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:273)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:258)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
... 6 more
Caused by: org.gradle.api.GradleException: Internal compiler error. See log for more details
at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:17)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:434)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:396)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:292)
at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:254)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
... 34 more
</code></pre>
<p>And in the log:</p>
<pre><code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:110)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:77)
at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.run(EventFiringTaskExecuter.java:51)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
at org.gradle.execution.taskgraph.LocalTaskInfoExecutor.execute(LocalTaskInfoExecutor.java:42)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:273)
at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareWorkItemExecutor.execute(DefaultTaskExecutionGraph.java:258)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:135)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:130)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.execute(DefaultTaskPlanExecutor.java:200)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.executeWithWork(DefaultTaskPlanExecutor.java:191)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$ExecutorWorker.run(DefaultTaskPlanExecutor.java:130)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.api.GradleException: Internal compiler error. See log for more details
at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:17)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:434)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:396)
at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:292)
at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:254)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:131)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:300)
at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:292)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:174)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:120)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:99)
... 34 more
</code></pre>
<p>Any help will be greatly appreciated!
Edit: I work from macOS High Sierra but am downloading Linux Mint and will probably try in that to see if the issue persists!</p> | 53,709,161 | 13 | 1 | null | 2018-08-29 15:41:04.507 UTC | 4 | 2021-07-27 11:48:45.59 UTC | 2018-08-29 16:15:54.153 UTC | null | 8,845,653 | null | 8,845,653 | null | 1 | 31 | java|android|exception|kotlin|code-generation | 22,701 | <p>I had the same problem, because I was using inconsistent version of Anko. With kotlin <strong>1.3.x</strong> you have to use this <a href="https://github.com/Kotlin/anko/releases/tag/v0.10.8" rel="noreferrer">v0.10.8</a> version of anko or newer.</p> |
29,929,178 | ImportError: No module named django_filters | <p>I am using Django 1.7.1 and I pip installed django-filters to my virtual env at <code>/.virtualenvs/auction2/lib/python2.7/site-packages$</code></p>
<p>It said it was installed successfully. </p>
<p>So I placed django-filters in installed apps like so:</p>
<pre><code>INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'django_filters',
'donations',
)
</code></pre>
<p>I ran <code>python manage.py runserver</code> and got this error:</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/Dani/.virtualenvs/auction2/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Users/Dani/.virtualenvs/auction2/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Users/Dani/.virtualenvs/auction2/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/Dani/.virtualenvs/auction2/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/Users/Dani/.virtualenvs/auction2/lib/python2.7/site-packages/django/apps/config.py", line 87, in create
module = import_module(entry)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named django_filters
</code></pre>
<p>It said it installed, but why can't it import it? I have another package, crispy-forms, installed and working. I looked at my site packages on the virtual environment and I saw:</p>
<pre><code>crispy_forms
django
django_braces-1.4.0.dist-info
django_crispy_forms-1.4.0-py2.7.egg-info
django_filters-0.1.0-py2.7.egg-info
easy_install.py
easy_install.pyc
filters
pip
</code></pre>
<p>Seeing that it goes in as 'filters' instead of what the documentation says to import it as (django_filters), I thought I'd try changing it to just 'filters' in installed_apps. </p>
<p>I stoped and started the runserver, no problem, so I began building my filter in <code>filter.py</code>:</p>
<pre><code>import django_filters
from donations.models import Donor, Item, Issue
class DonorFilter(django_filters.FilterSet):
class Meta:
model = Donor
fields = {'type':['exact'],'donor':['icontains'],}
def __init__(self, *args, **kwargs):
super(DonorFilter, self).__init__(*args, **kwargs)
self.filters['type'].extra.update(
{'empty_label': 'All Types'})
</code></pre>
<p>I stop and start the runserver, no problem. Then I start adding a view and just the import statement at views.py:</p>
<pre><code>from donations.filters import DonorFilter
</code></pre>
<p>gives me the same <code>ImportError: No module named django_filters.</code> error.</p>
<p>I tried changing the import in my filters.py to filters rather than django_filters and the errors didn't change. I changed everything back to django_filters (in installed_apps and my filters.py) as the documentation says to do, I get the error <code>global name 'DonorFilter' is not defined</code> when I add the view. Here is the view.py:</p>
<pre><code>def donor_list(request):
f = DonorFilter(request.GET, queryset=Donor.objects.all())
return render_to_response('donations/donor_list', {'filter': f})
</code></pre>
<p>That means I need to import the function I created in filters.py? So I add
<code>from donations.filters import DonorFilter</code> to the top of my view.
Then the error is <code>'module' object has no attribute 'FilterSet'</code></p>
<p>I can see the FilterSet class in the filters.py file installed in my virtualenv </p>
<p>I noticed there is more development on django-filter, the <a href="https://github.com/alex/django-filter" rel="noreferrer">https://github.com/alex/django-filter</a> page goes up to v0.9.2, but pip installs 0.1.0. Should I be installing it another way (other than pip)?</p>
<p>I'm very new at this and appreciate any help!</p> | 29,932,635 | 10 | 4 | null | 2015-04-28 20:21:40.4 UTC | 5 | 2022-05-07 06:05:54.813 UTC | null | null | null | null | 3,816,545 | null | 1 | 45 | django|django-filter | 80,980 | <p>My pip version was old, really old. 1.5.6 When I installed my virtual environment it just worked, so I didn't question. Lesson learned! Here is what I did in case it helps someone else...</p>
<p>In the virtual environment, I installed pip as described in the docs:
<a href="https://pip.pypa.io/en/stable/installing.html" rel="noreferrer">https://pip.pypa.io/en/stable/installing.html</a>
<code>python get-pip.py</code> This upgraded me to pip 6.1.1</p>
<pre><code>pip install django-filter
pip freeze > requirements.txt
</code></pre>
<p>Reading requirements.txt showed I had </p>
<pre><code>django-filter==0.9.2
django-filters==0.1.0
</code></pre>
<p>So I uninstalled the older version with <code>pip uninstall django-filters</code></p>
<p><strong>notice the s on the older version but not on the new one</strong></p>
<p>Really basic stuff but it really tripped me up. Thanks to anyone who took time to look into this!</p> |
23,108,342 | Install cordova plugin for ONE platform only | <p>We want to install the com.blackberry.app plugin (<a href="http://plugins.cordova.io/#/package/com.blackberry.app">http://plugins.cordova.io/#/package/com.blackberry.app</a>) for our (cordova 3.4.0 CLI) project. IF I try "cordova plugin add com.blackberry.app", it is installing plugin for both android and blackberry10 platforms. Due to this, the android app crashes. I tried installing only this plugin for blackberry10 platform thru plugman, but the functionality doesn't work [although plugman says it successfully installed]</p>
<p>Is there a way in CLI to install a plugin for ONE platform only?</p>
<p>Thanks</p> | 23,197,150 | 2 | 1 | null | 2014-04-16 11:37:12.58 UTC | 13 | 2014-04-21 12:09:26.643 UTC | null | null | null | null | 1,511,823 | null | 1 | 36 | cordova|blackberry-10 | 20,894 | <p>I've found that the only clean way to make it work is to modify 3 things:<br><br></p>
<ol>
<li>Edit the <b>plugins/PLATFORM.js</b> file (ex. plugins/android.js) and remove the plugin object from the "installed_plugins" array<br></li>
<li>Do the same for the <b>platforms/PLATFORM/www/cordova_plugins.js</b> file where PLATFORM could be ios, blackberry10, firefoxos etc. In the android case will be inside assets/www instead of just www<br></li>
<li>Last step is to delete the plugin directory inside <b>platforms/PLATFORM/www/plugins/</b>. In your case again it will be assets/www and not just www</li>
</ol> |
31,319,942 | Change the size of a plot when plotting multiple plots in R | <p>I want to know if there is a way to define the size of a plot in R, when you are plotting different plots using the par(mfrow=c()) function.</p>
<p>As a simple example take this:</p>
<pre><code>par(mfrow = c(3,1))
plot(1:2)
plot(1:2)
plot(1:2)
</code></pre>
<p>All plots will have the same size.</p>
<p>Is it possible, for instance, to make the size of the third plot different?
For example make it half the size of the other plots?</p>
<p>If I use this:</p>
<pre><code>par(mfrow = c(3,1))
plot(1:2)
plot(1:2)
plot(1:2, ylim =c(0,1))
</code></pre>
<p>The ylim axis changes but no the size of the plot.</p>
<p>Thank you.</p> | 31,320,272 | 2 | 4 | null | 2015-07-09 14:07:00.567 UTC | 10 | 2018-10-04 11:20:48.94 UTC | null | null | null | null | 2,920,036 | null | 1 | 20 | r|plot | 51,835 | <p>Try <code>layout</code>
for example</p>
<pre><code>layout(matrix(c(1,1,2,3,4,4), nrow = 3, ncol = 2, byrow = TRUE))
plot(1,main=1)
plot(2,main=2)
plot(3,main=3)
plot(4,main=4)
</code></pre>
<p><img src="https://i.stack.imgur.com/mZlWa.png" alt="enter image description here"></p>
<pre><code>layout(matrix(c(1,1,2,1,1,2,3,4,4), nrow = 3, ncol = 3, byrow = TRUE))
plot(1,main=1)
plot(2,main=2)
plot(3,main=3)
plot(4,main=4)
</code></pre>
<p>give you
<img src="https://i.stack.imgur.com/2nUkc.png" alt="enter image description here"></p>
<p>Also you can use <code>par(fig= )</code>
for example</p>
<pre><code>par(mar=c(2,2,2,1))
par(fig=c(0,7,6,10)/10)
plot(1,main=1)
par(fig=c(7,10,6,10)/10)
par(new=T)
plot(2,main=2)
par(fig=c(0,7,0,6)/10)
par(new=T)
plot(3,main=3)
par(fig=c(7,10,0,6)/10)
par(new=T)
plot(4,main=4)
</code></pre>
<p>Give you
<img src="https://i.stack.imgur.com/XqIle.png" alt="enter image description here"></p>
<p>but i think layout better for use</p> |
35,565,758 | Spring Boot bind @Value to Enum case insensitive | <p><strong>Enum</strong></p>
<pre><code>public enum Property {
A,
AB,
ABC;
}
</code></pre>
<p><strong>Field</strong></p>
<pre><code>@Value("${custom.property}")
protected Property property;
</code></pre>
<p><strong>application.properties</strong> (lower case)</p>
<pre><code>custom.property=abc
</code></pre>
<p>When I'm running application I have an error:</p>
<blockquote>
<p>Cannot convert value of type [java.lang.String] to required type
[com.xxx.Property]: no matching editors or conversion
strategy found.</p>
</blockquote>
<p>Whereas (upper case):</p>
<pre><code>custom.property=ABC
</code></pre>
<p>Works fine. </p>
<p>Is there a way to bind the value case insensitive? Like <em>ABC</em>, <em>Abc</em>, <em>AbC</em>, <em>abc</em> any pattern should work.</p>
<p>NOTE: I saw this question - <a href="https://stackoverflow.com/questions/4617099/spring-3-0-mvc-binding-enums-case-sensitive">Spring 3.0 MVC binding Enums Case Sensitive</a> but in my case I have over 10 enums/values (and expect to have more) classes and to implement 10 different custom property binders would be painful, I need some generic solution.</p> | 35,571,932 | 3 | 2 | null | 2016-02-22 23:10:08.123 UTC | 1 | 2018-12-17 07:49:07.197 UTC | 2018-06-19 16:26:24.173 UTC | null | 3,523,579 | null | 3,523,579 | null | 1 | 21 | java|spring|spring-boot|enums|spring-properties | 40,116 | <p><code>@Value</code> and <code>@ConfigurationProperties</code> features do not match. I couldn't stress enough how <code>@ConfigurationProperties</code> is superior. </p>
<p>First, you get to design your configuration in a simple POJO that you can inject wherever you want (rather than having expressions in annotation that you can easily break with a typo). Second, the meta-data support means that you can <em>very easily</em> <a href="http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#configuration-metadata-annotation-processor" rel="noreferrer">get auto-completion in your IDE for your own keys</a>.</p>
<p>And finally, the relaxed binding described in the doc only applies to <code>@ConfigurationProperties</code>. <code>@Value</code> is a Spring Framework feature and is unaware of relaxed binding. We <a href="https://github.com/spring-projects/spring-boot/issues/4892" rel="noreferrer">intend to make that more clear in the doc</a>.</p>
<p>TL;DR <code>abc</code> works with <code>@ConfigurationProperties</code> but won't with <code>@Value</code>.</p> |
1,510,712 | Convert a string to XML input stream in java | <p>I'm trying to generate a PDF document using FOP and Java.</p>
<p>I receive the XML as a string and not as a file.</p>
<p>How can I convert this XML string to an XML input stream so that I can call xslfoTransformer.transform(source, res); where source is my XML string as an Input stream.</p>
<p>Please provide your suggestions.</p> | 1,510,737 | 3 | 0 | null | 2009-10-02 16:53:19.16 UTC | 9 | 2017-03-13 14:52:13.34 UTC | null | null | null | null | 133,946 | null | 1 | 25 | java|apache-fop | 44,471 | <p>You probably want to convert it to a <code>Reader</code>, not an <code>InputStream</code>. Use <a href="https://docs.oracle.com/javase/8/docs/api/java/io/StringReader.html" rel="noreferrer">StringReader</a> to do this. StreamSource has a constructor that takes a Reader, and you can pass that <code>StreamSource</code> to Transformer.transform().</p>
<p>I say you probably want a <code>Reader</code> rather than an <code>InputStream</code> because a String holds characters, not bytes, and an <code>InputStream</code> is a stream of bytes while a <code>Reader</code> is a stream of characters.</p> |
2,263,141 | Concurrency in Lucene.NET. | <p>I want to use Lucene.NET for fulltext search shared between two apps: one is an ASP.NET MVC application and the other one is a console application. Both applications are supposed to search and update index.
How the concurrency should be handled?<br/>
I found a <a href="http://www.ifdefined.com/blog/post/2009/02/Full-Text-Search-in-ASPNET-using-LuceneNET.aspx" rel="nofollow noreferrer">tutorial on ifdefined.com </a> where the similar use case is discussed. My concern is that locking will be a big bottleneck.</p>
<p>PS:
Also I noticed that IndexSearcher uses a snapshot of index and in the tutorial mentioned above searcher is created only when index is updated. Is this a good approach? Can I just create a regular searcher object at each search and if yes what is the overhead?</p>
<p>I found a related question <a href="https://stackoverflow.com/questions/193624/does-lucene-net-manage-multiple-threads-accessing-the-same-index-one-indexing-wh"><a href="https://stackoverflow.com/questions/193624/does-lucene-net-manage-multiple-threads-accessing-the-same-index-one-indexing-wh">Does Lucene.Net manage multiple threads accessing the same index, one indexing while the other is searching?</a></a> what claims that interprocess concurrency is safe. Does it mean that it is are no race conditions for index?</p>
<p><strong>Also one very important aspect. What is the performance hit involved if let's say 10-15 threads are trying to update Lucene index via acquiring shared lock presented in <a href="http://ifdefined.com/blog/post/Full-Text-Search-in-ASPNET-using-LuceneNET.aspx" rel="nofollow noreferrer">this solution</a>?</strong></p>
<p>After using it couple of months I have to add that opening index for search often can create OutOfMemory exception under high CPU and memory loads if query uses sorting. Cost of index opening operation is small (in my experience) but cost of GC can be quite high.</p> | 2,305,067 | 3 | 0 | null | 2010-02-14 22:42:28.697 UTC | 14 | 2013-03-16 13:10:21.47 UTC | 2017-05-23 10:29:47.48 UTC | null | -1 | null | 86,913 | null | 1 | 28 | .net|lucene|lucene.net | 6,477 | <p>First of all we have to define a "write" operation. A write operation will object a lock once you start a write operation and will continue until you close the object that is performing the work. Such as creating an IndexWriter and indexing a document will cause the write to object a lock and it will keep this lock until you close the IndexWriter.</p>
<p>Now we can talk about the lock a little bit. This lock that is object is a file based lock. Like mythz mentioned earlier, there is a file called 'write.lock' that is created. Once a write lock is objected it is exclusive! This lock causes all index modifying operations (IndexWriter, and some methods from IndexReader) to wait until the lock is removed. </p>
<p>Overall you and have multiple reads on an index. You can even read and write at the same time, no problem. But there is a problem when having multiple writers. If one thread is waiting for the lock too long it will time out. </p>
<p>1) Possible Solution #1 Direct Operations</p>
<p>If you are sure that your indexing operations are short and quick, you may be able to just use the same index at the same time. Otherwise you will have to think about how you want to organize the indexing operations of the applications. </p>
<p>2) Possible Solution #2 Web Service</p>
<p>Since you are working with a web solution it might be possible to create a web service. When implementing this web service I would dedicate a worker thread for indexing. I would create a work queue to contain the work and if the queue contained multiple jobs to do, it should grab them all and do them into batch. This will solve all of the problems.</p>
<p>3) create another index, then merge</p>
<p>If the console application does heavy work on the index you may be able to look into having the console application you could create a seperate index in the console application and then merge the indexes at some safe scheduled time using IndexWriter.AddIndexes.</p>
<p>from here you can do this in two ways, you can merge with the direct index. Or you can merge to create a 3rd index, and then when this index is ready replace the original index. You have to be careful in what your doing here as well to make sure that your not going to lock something in heavy use and cause a timeout for other write operations.</p>
<p>4) Index & Search multiple indexes</p>
<p>Personally I think people need to separate their indexes out. This helps separates responsibilities of the programs and minimizes down time and maintained of having a single point for all indexes. For example, if your console application is responsible for only adding in certain fields or your are kind of extending an index you could look separate the indexes out, but maintain identity by using an ID field in each document. Now with this you can take advantage of the built in support for searching multiple indexes using the MultiSercher class. Or if your wanting there is also a nice ParallelMultiSearch class that can search both indexes at once.</p>
<p>5) Look into SOLR</p>
<p>Something else that can help your issue of maintaining a single place for you index, you could change your program to work with a SOLR server. <a href="http://lucene.apache.org/solr/" rel="noreferrer">http://lucene.apache.org/solr/</a> there is also a nice SOLRNET <a href="http://code.google.com/p/solrnet/" rel="noreferrer">http://code.google.com/p/solrnet/</a> library that can be helpful in this situation. Although I'm not experienced with solr but i am under the impression that it will help you manage situation such as this. Also it has other benefits such as hit highlighting and searching for related items by finding items "MoreLikeThis", or provide spell checking. </p>
<p>I'm sure there are other methods but these are all the ones that I can think of. Overall it your solution depends upon how many people are writing and how up to date the search index you need it to be. Overall if you can defer some operations for a latter time and do some batch operations in any situation will give you the most performance. My suggestion is to understand what your able to work with and go from there. good luck</p> |
40,992,976 | Python - Convert datetime column into seconds | <p>I have a date column (called 'Time') which contains days/hours/mins etc (timedelta). I have created a new column in my dataframe and I want to convert the 'Time' column into seconds and put it in the new column for each row.</p>
<p>Does anyone have any pointers? All I can find on the internet is how to convert your column, not create a new column and convert another one.</p>
<p>Thank you in advance!</p> | 40,993,004 | 2 | 0 | null | 2016-12-06 10:23:18.167 UTC | 5 | 2019-05-17 11:31:19.08 UTC | 2019-05-17 11:31:19.08 UTC | null | 6,593,031 | null | 6,593,031 | null | 1 | 27 | python|pandas | 93,773 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.total_seconds.html" rel="noreferrer"><code>total_seconds</code></a>:</p>
<pre><code>print (df['col'].dt.total_seconds())
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'date1':pd.date_range('2015-01-01', periods=3),
'date2':pd.date_range('2015-01-01 02:00:00', periods=3, freq='23H')})
print (df)
date1 date2
0 2015-01-01 2015-01-01 02:00:00
1 2015-01-02 2015-01-02 01:00:00
2 2015-01-03 2015-01-03 00:00:00
df['diff'] = df['date2'] - df['date1']
df['seconds'] = df['diff'].dt.total_seconds()
print (df)
date1 date2 diff seconds
0 2015-01-01 2015-01-01 02:00:00 02:00:00 7200.0
1 2015-01-02 2015-01-02 01:00:00 01:00:00 3600.0
2 2015-01-03 2015-01-03 00:00:00 00:00:00 0.0
</code></pre>
<hr>
<pre><code>df['diff'] = df['date2'] - df['date1']
df['diff'] = df['diff'].dt.total_seconds()
print (df)
date1 date2 diff
0 2015-01-01 2015-01-01 02:00:00 7200.0
1 2015-01-02 2015-01-02 01:00:00 3600.0
2 2015-01-03 2015-01-03 00:00:00 0.0
</code></pre>
<p>If need cast to <code>int</code>:</p>
<pre><code>df['diff'] = df['date2'] - df['date1']
df['diff'] = df['diff'].dt.total_seconds().astype(int)
print (df)
date1 date2 diff
0 2015-01-01 2015-01-01 02:00:00 7200
1 2015-01-02 2015-01-02 01:00:00 3600
2 2015-01-03 2015-01-03 00:00:00 0
</code></pre> |
61,826,895 | How to avoid VS Code warning: "[myfile].java is a non-project file, only syntax errors are reported" | <p>I am running a build task in a java project in Visual Studio Code.
The warning in the "PROBLEMS" tab:</p>
<blockquote>
<p>[myfile].java is a non-project file, only syntax errors are reported</p>
</blockquote>
<p>It refers to the first line where I load in the class file containing the main():</p>
<pre><code>package [the project folder];
import [the project folder].[the file with other classes].*;
</code></pre>
<ul>
<li>I can only avoid the warning by copying the files' text (the code text itself) into new java files of a new project in a new unrelated folder. The code itself is correct and compiles without errors. Actually, this is the answer, but it is much manual work.</li>
<li>When I just copy the java files of the project with the warning message into a new folder, the warning still appears!!!! (!)</li>
<li>When I just copy the whole project folder to a new place, the error remains as well, of course.</li>
</ul>
<p>I guess that copying text into new java files with the same names and the same folder structure is different from copying the files themselves because the files probably get tagged by VS Code, so that they have a project stamp even when the folder structure is destroyed. Perhaps this supports recovering the project structure from recovered raw files? Could this be the problem of this Visual Code warning?</p>
<p>I checked other threads before, this is just the last step.</p>
<ul>
<li><a href="https://stackoverflow.com/questions/50454523/how-can-i-fix-build-failed-do-you-want-to-continue-in-vscode/55916509#comment109352218_55916509">How can I fix build failed, do you want to continue? in vscode</a></li>
<li><a href="https://stackoverflow.com/questions/45743779/visual-studio-code-java-import-errors-and-more/61825498#61825498">Visual Studio Code - Java - Import Errors and More</a></li>
</ul>
<p>--> Thus, I cleaned vscode's workspaceStorage (on Windows: <code>C:\Users\USER\AppData\Roaming\Code\User\workspaceStorage</code>) and restarted without success.</p> | 63,188,536 | 10 | 0 | null | 2020-05-15 19:27:09.223 UTC | 5 | 2022-08-14 17:54:35.477 UTC | 2020-09-11 13:00:57.453 UTC | null | 11,154,841 | null | 11,154,841 | null | 1 | 25 | java|visual-studio-code|package|compiler-warnings|project-structure | 75,567 | <p>I got the same warning simply because I had two Java (Maven) projects in the same vscode workspace. Once I moved projectA out of the workspace, the warning for projectB is gone.</p>
<pre><code>WorkspaceRoot
│ projectA
└───projectB
</code></pre>
<p>My current solution is to have one Java (Maven) project for one workspace, i.e,
one Maven project per vscode workspace.</p>
<p>My guess is that vscode treats all Java projects inside the same workspace as as one project and hence, the projects interfering with each other.</p> |
36,917,947 | create folder inside S3 bucket using Cloudformation | <p>I'm able to create an S3 bucket using cloudformation but would like to create a folder inside an S3 bucket..like</p>
<pre><code><mybucket>--><myfolder>
</code></pre>
<p>Please let me know the template to be used to create a folder inside a bucket ...both should be created at the sametime...</p>
<p>I'm Using AWS lambda as below</p>
<pre><code>stackname = 'myStack'
client = boto3.client('cloudformation')
response = client.create_stack(
StackName= (stackname),
TemplateURL= 'https://s3.amazonaws.com/<myS3bucket>/<myfolder>/nestedstack.json',
Parameters=<params>
)
</code></pre> | 36,930,460 | 5 | 0 | null | 2016-04-28 14:39:25.79 UTC | 9 | 2022-06-14 10:21:36.813 UTC | 2016-12-05 06:59:42.847 UTC | null | 1,736,679 | null | 1,065,358 | null | 1 | 36 | amazon-s3|amazon-cloudformation | 35,840 | <p>AWS doesn't provide an official CloudFormation resource to create objects within an S3 bucket. However, you can create a <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources-lambda.html" rel="noreferrer">Lambda-backed Custom Resource</a> to perform this function using the AWS SDK, and in fact the <a href="https://github.com/gilt/cloudformation-helpers#put-s3-objects" rel="noreferrer">gilt/cloudformation-helpers</a> GitHub repository provides an off-the-shelf custom resource that does just this.</p>
<p>As with any Custom Resource setup is a bit verbose, since you need to first deploy the Lambda function and IAM permissions, then reference it as a custom resource in your stack template.</p>
<p>First, add the <code>Lambda::Function</code> and associated <code>IAM::Role</code> resources to your stack template:</p>
<pre><code>"S3PutObjectFunctionRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version" : "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [ "lambda.amazonaws.com" ]
},
"Action": [ "sts:AssumeRole" ]
}
]
},
"ManagedPolicyArns": [
{ "Ref": "RoleBasePolicy" }
],
"Policies": [
{
"PolicyName": "S3Writer",
"PolicyDocument": {
"Version" : "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:DeleteObject",
"s3:ListBucket",
"s3:PutObject"
],
"Resource": "*"
}
]
}
}
]
}
},
"S3PutObjectFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"S3Bucket": "com.gilt.public.backoffice",
"S3Key": "lambda_functions/cloudformation-helpers.zip"
},
"Description": "Used to put objects into S3.",
"Handler": "aws/s3.putObject",
"Role": {"Fn::GetAtt" : [ "S3PutObjectFunctionRole", "Arn" ] },
"Runtime": "nodejs",
"Timeout": 30
},
"DependsOn": [
"S3PutObjectFunctionRole"
]
},
</code></pre>
<p>Then you can use the Lambda function as a Custom Resource to create your S3 object:</p>
<pre><code>"MyFolder": {
"Type": "Custom::S3PutObject",
"Properties": {
"ServiceToken": { "Fn::GetAtt" : ["S3PutObjectFunction", "Arn"] },
"Bucket": "mybucket",
"Key": "myfolder/"
}
},
</code></pre>
<p>You can also use the same Custom Resource to write a string-based S3 object by adding a <code>Body</code> parameter in addition to <code>Bucket</code> and <code>Key</code> (see the <a href="https://github.com/gilt/cloudformation-helpers#put-s3-objects" rel="noreferrer">docs</a>).</p> |
20,583,531 | Lvalue to rvalue reference binding | <p>The compiler keeps complaining I'm trying to bind an lvalue to an rvalue reference, but I cannot see how. I'm new to C++11, move semantics, etc., so please bear with me.</p>
<p>I have this function:</p>
<pre><code>template <typename Key, typename Value, typename HashFunction, typename Equals>
Value& FastHash<Key, Value, HashFunction, Equals>::operator[](Key&& key)
{
// Some code here...
Insert(key, Value()); // Compiler error here
// More code here.
}
</code></pre>
<p>which calls this method:</p>
<pre><code>template <typename Key, typename Value, typename HashFunction, typename Equals>
void FastHash<Key, Value, HashFunction, Equals>::Insert(Key&& key, Value&& value)
{
// ...
}
</code></pre>
<p>I keep getting errors like the following:</p>
<pre><code>cannot convert argument 1 from 'std::string' to 'std::string &&'
</code></pre>
<p>on the Insert() call. Isn't <code>key</code> defined as an rvalue in the operator overload? Why is it being reinterpreted as an lvalue?</p> | 20,583,578 | 1 | 0 | null | 2013-12-14 12:52:37.897 UTC | 12 | 2020-01-21 10:23:38.633 UTC | 2020-01-21 10:23:38.633 UTC | null | 264,325 | null | 374,253 | null | 1 | 29 | c++|c++11|move-semantics|rvalue-reference | 30,517 | <pre><code>Insert(key, Value()); // Compiler error here
</code></pre>
<p><code>key</code> here is <code>Key&& key</code> - this is an lvalue! It has a name, and you can take its address. It's just that type of that lvalue is "rvalue reference to <code>Key</code>".</p>
<p>You need to pass in an rvalue, and for that you need to use <code>std::move</code>:</p>
<pre><code>Insert(std::move(key), Value()); // No compiler error any more
</code></pre>
<p>I can see why this is counter-intuitive! But once you distinguish between and rvalue reference (which is a reference bound to an rvalue) and an actual rvalue, it becomes clearer.</p>
<p>Edit: the real problem here is using rvalue references at all. It makes sense to use them in a function template where the type of the argument is deduced, because this allows the argument to bind to either an lvalue reference or an rvalue reference, due to reference collapsing rules. See this article and video for why: <a href="http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers" rel="noreferrer">http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers</a></p>
<p>However, in this case the type of Key is not deduced when the function is called, as it has already been determined by the class when you instantiated <code>FastHash<std::string, ... ></code>. Thus you really are prescribing the use of rvalue references, and thus using <code>std::move</code> fixes the code.</p>
<p>I would change your code to that the parameters are take by value:</p>
<pre><code>template <typename Key, typename Value, typename HashFunction, typename Equals>
Value& FastHash<Key, Value, HashFunction, Equals>::operator[](Key key)
{
// Some code here...
Insert(std::move(key), Value());
// More code here.
}
template <typename Key, typename Value, typename HashFunction, typename Equals>
void FastHash<Key, Value, HashFunction, Equals>::Insert(Key key, Value value)
{
// ...
}
</code></pre>
<p>Don't worry too much about extra copies due to use of value arguments - these are frequently optimised out by the compiler.</p> |
20,760,772 | HTML Character - Invisible space | <p>I have a website called Dalton<b>Empire</b>.</p>
<p>When a user copies "DaltonEmpire" I would like "Dalton Empire" to be added to their clipboard.</p>
<p>I only came to one solution; use a space, but make the <code>letter-spacing</code> <code>-18px</code>.
Isn't there a neater solution, such as a HTML character for this?</p>
<p>My example <a href="http://jsfiddle.net/4BbLU/" rel="noreferrer">JSFiddle</a> and code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>span.nospace {
letter-spacing: -18px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>Dalton<b>Empire</b></li>
<li>Dalton&zwnj;<b>Empire</b></li>
<li>Dalton&zwj;<b>Empire</b></li>
<li>Dalton&#8203;<b>Empire</b></li>
<li>Dalton<span class="nospace"> </span><b>Empire</b> <i>The only one that works</i>
</li>
</ol></code></pre>
</div>
</div>
</p> | 20,761,017 | 6 | 0 | null | 2013-12-24 12:13:47.14 UTC | 1 | 2018-12-18 11:06:51.483 UTC | 2018-12-18 11:06:51.483 UTC | null | 4,551,041 | null | 2,204,668 | null | 1 | 13 | html|css|hidden|space | 41,030 | <p>You can use <code>word-spacing</code> for this. However to make a more dynamic property you want to use the <code>em</code> unit. This way the unit is based on the font-size, so actually supports all the font families <em>and</em> font sizes:</p>
<pre><code>ol li
{
word-spacing: -.2em;
}
</code></pre>
<blockquote>
<p>em is not an absolute unit - it is a unit that is relative to the
currently chosen font size.</p>
</blockquote>
<p>source: <a href="https://stackoverflow.com/questions/609517/why-em-instead-of-px">Why em instead of px?</a></p>
<h2><a href="http://jsfiddle.net/4BbLU/3/" rel="noreferrer">jsFiddle</a></h2> |
26,068,819 | How to kill all Pool workers in multiprocess? | <p>I want to stop all threads from a single worker.</p>
<p>I have a thread pool with 10 workers:</p>
<pre><code>def myfunction(i):
print(i)
if (i == 20):
sys.exit()
p = multiprocessing.Pool(10, init_worker)
for i in range(100):
p.apply_async(myfunction, (i,))
</code></pre>
<p>My program does not stop and the other processes continue working until all 100 iterations are complete. I want to stop the pool entirely from inside the thread that calls <code>sys.exit()</code>. The way it is currently written will only stop the worker that calls <code>sys.exit()</code>.</p> | 26,068,937 | 2 | 0 | null | 2014-09-26 21:52:48.76 UTC | 8 | 2017-11-02 12:09:58.813 UTC | 2017-09-02 14:31:49.77 UTC | null | 355,230 | null | 3,166,104 | null | 1 | 11 | python|multithreading|multiprocessing|kill-process | 24,222 | <p>This isn't working the way you're intending because calling <code>sys.exit()</code> in a worker process will only terminate the worker. It has no effect on the parent process or the other workers, because they're separate processes and raising <code>SystemExit</code> only affects the current process. You need to send a signal back the parent process to tell it that it should shut down. One way to do this for your use-case would be to use an <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.managers.SyncManager.Event" rel="noreferrer"><code>Event</code></a> created in a <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.sharedctypes.multiprocessing.Manager" rel="noreferrer"><code>multiprocessing.Manager</code></a> server:</p>
<pre><code>import multiprocessing
def myfunction(i, event):
if not event.is_set():
print i
if i == 20:
event.set()
if __name__ == "__main__":
p= multiprocessing.Pool(10)
m = multiprocessing.Manager()
event = m.Event()
for i in range(100):
p.apply_async(myfunction , (i, event))
p.close()
event.wait() # We'll block here until a worker calls `event.set()`
p.terminate() # Terminate all processes in the Pool
</code></pre>
<p>Output:</p>
<pre><code>0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</code></pre>
<p>As pointed out in Luke's answer, there is a race here: There's no guarantee that all the workers will run in order, so it's possible that <code>myfunction(20, ..)</code> will run prior to <code>myfuntion(19, ..)</code>, for example. It's also possible that other workers after <code>20</code> will run before the main process can act on the event being set. I reduced the size of the race window by adding the <code>if not event.is_set():</code> call prior to printing <code>i</code>, but it still exists.</p> |
29,130,664 | Detect if running from the command line in Laravel 5 | <p>I have a use case where we need to modify application flow if the application is being run from the command line via Artisan (migrations, seeds, route:list).</p>
<p>In Laravel 4 this could be done like this:</p>
<pre><code>App::runningInConsole()
</code></pre>
<p>Is there an equivalent in Laravel 5? </p>
<p>Using the Environment (.env) variables isn't preferred in this case as these commands occasionally need to be run on production (pointing to production resources) and I'd prefer to avoid resorting to duplicate (.env.commandline) files.</p> | 29,130,810 | 4 | 0 | null | 2015-03-18 19:07:44.197 UTC | 6 | 2019-10-23 09:34:07.42 UTC | null | null | null | null | 51,237 | null | 1 | 40 | php|laravel-5 | 22,154 | <p>You can use the PHP function <code>php_sapi_name</code> (<a href="http://php.net/manual/en/function.php-sapi-name.php">http://php.net/manual/en/function.php-sapi-name.php</a>), to found out if the script was launched from a command or not.</p>
<p>In your case, you should check something like</p>
<pre><code>if (strpos(php_sapi_name(), 'cli') !== false) {
// Run from command
}
</code></pre>
<p>You may have to check the doc to find the proper value to check in each case though. (It may differ sometimes, but basically there should always be a different output from a script launched through a command)</p> |
32,093,792 | How to remove extra host only network interfaces created by vagrant on windows 10? | <p>I have recently upgraded to Win 10 and hence to vagrant 1.7.4 and virtual box 5.0.2 r102096. While bringing one of the VM up using vagrant up, vagrant kept failing, but created new Host only adapters in the system on every attempt. Now I have 6 virtual host only adapters.</p>
<p>How do I remove the extraneous ones?</p> | 32,093,978 | 7 | 0 | null | 2015-08-19 11:08:21.96 UTC | 12 | 2019-01-29 02:11:24.693 UTC | null | null | null | null | 710,238 | null | 1 | 48 | vagrant|virtualbox|windows-10 | 72,596 | <p>Vboxmanage to the rescue.</p>
<p>Sample command:</p>
<pre><code>vboxmanage hostonlyif remove "VirtualBox Host-Only Ethernet Adapter #3"
</code></pre> |
8,751,497 | Latitude Longitude Coordinates to State Code in R | <p>Is there a fast way to convert latitude and longitude coordinates to State codes in R? I've been using the zipcode package as a look up table but it's too slow when I'm querying lots of lat/long values</p>
<p>If not in R is there any way to do this using google geocoder or any other type of fast querying service?</p>
<p>Thanks!</p> | 8,751,965 | 5 | 1 | null | 2012-01-05 23:36:14.06 UTC | 16 | 2021-02-16 02:15:23.07 UTC | null | null | null | null | 851,530 | null | 1 | 21 | r|latitude-longitude|google-geocoder | 31,140 | <p>Here are two options, one using <strong>sf</strong> and one using <strong>sp</strong> package functions. <strong>sf</strong> is the more modern (and, here in 2020, recommended) package for analyzing spatial data, but in case it's still useful, I am leaving my original 2012 answer showing how to do this with <strong>sp</strong>-related functions.</p>
<hr>
<h2>Method 1 (using sf):</h2>
<pre class="lang-r prettyprint-override"><code>library(sf)
library(spData)
## pointsDF: A data.frame whose first column contains longitudes and
## whose second column contains latitudes.
##
## states: An sf MULTIPOLYGON object with 50 states plus DC.
##
## name_col: Name of a column in `states` that supplies the states'
## names.
lonlat_to_state <- function(pointsDF,
states = spData::us_states,
name_col = "NAME") {
## Convert points data.frame to an sf POINTS object
pts <- st_as_sf(pointsDF, coords = 1:2, crs = 4326)
## Transform spatial data to some planar coordinate system
## (e.g. Web Mercator) as required for geometric operations
states <- st_transform(states, crs = 3857)
pts <- st_transform(pts, crs = 3857)
## Find names of state (if any) intersected by each point
state_names <- states[[name_col]]
ii <- as.integer(st_intersects(pts, states))
state_names[ii]
}
## Test the function with points in Wisconsin, Oregon, and France
testPoints <- data.frame(x = c(-90, -120, 0), y = c(44, 44, 44))
lonlat_to_state(testPoints)
## [1] "Wisconsin" "Oregon" NA
</code></pre>
<p>If you need higher resolution state boundaries, read in your own vector data as an <code>sf</code> object using <code>sf::st_read()</code> or by some other means. One nice option is to install the <strong>rnaturalearth</strong> package and use it to load a state vector layer from <strong>rnaturalearthhires</strong>. Then use the <code>lonlat_to_state()</code> function we just defined as shown here:</p>
<pre class="lang-r prettyprint-override"><code>library(rnaturalearth)
us_states_ne <- ne_states(country = "United States of America",
returnclass = "sf")
lonlat_to_state(testPoints, states = us_states_ne, name_col = "name")
## [1] "Wisconsin" "Oregon" NA
</code></pre>
<p>For very accurate results, you can download a geopackage containing <a href="https://en.wikipedia.org/wiki/GADM" rel="noreferrer">GADM</a>-maintained administrative borders for the United States from <a href="https://gadm.org/download_country_v3.html" rel="noreferrer">this page</a>. Then, load the state boundary data and use them like this:</p>
<pre class="lang-r prettyprint-override"><code>USA_gadm <- st_read(dsn = "gadm36_USA.gpkg", layer = "gadm36_USA_1")
lonlat_to_state(testPoints, states = USA_gadm, name_col = "NAME_1")
## [1] "Wisconsin" "Oregon" NA
</code></pre>
<hr>
<h2>Method 2 (using sp):</h2>
<p>Here is a function that takes a data.frame of lat-longs within the lower 48 states, and for each point, returns the state in which it is located. </p>
<p>Most of the function simply prepares the <code>SpatialPoints</code> and <code>SpatialPolygons</code> objects needed by the <code>over()</code> function in the <code>sp</code> package, which does the real heavy lifting of calculating the 'intersection' of points and polygons:</p>
<pre class="lang-r prettyprint-override"><code>library(sp)
library(maps)
library(maptools)
# The single argument to this function, pointsDF, is a data.frame in which:
# - column 1 contains the longitude in degrees (negative in the US)
# - column 2 contains the latitude in degrees
lonlat_to_state_sp <- function(pointsDF) {
# Prepare SpatialPolygons object with one SpatialPolygon
# per state (plus DC, minus HI & AK)
states <- map('state', fill=TRUE, col="transparent", plot=FALSE)
IDs <- sapply(strsplit(states$names, ":"), function(x) x[1])
states_sp <- map2SpatialPolygons(states, IDs=IDs,
proj4string=CRS("+proj=longlat +datum=WGS84"))
# Convert pointsDF to a SpatialPoints object
pointsSP <- SpatialPoints(pointsDF,
proj4string=CRS("+proj=longlat +datum=WGS84"))
# Use 'over' to get _indices_ of the Polygons object containing each point
indices <- over(pointsSP, states_sp)
# Return the state names of the Polygons object containing each point
stateNames <- sapply(states_sp@polygons, function(x) x@ID)
stateNames[indices]
}
# Test the function using points in Wisconsin and Oregon.
testPoints <- data.frame(x = c(-90, -120), y = c(44, 44))
lonlat_to_state_sp(testPoints)
[1] "wisconsin" "oregon" # IT WORKS
</code></pre> |
19,483,975 | Jekyll on Github Pages: any way to add footnotes in Markdown? | <p>I've recently switched over to using Jekyll on Github Pages for my various blogs, and love that I can just push Markdown to Github and they handle the processing. I'd like to continue using it this way (rather than running Jekyll locally and just pushing the pre-generated site to Github), since the Github UI makes it easy to add and tweak posts if I'm not at my own machine.</p>
<p>There's just one thing I haven't been able to figure out: I can't get Markdown footnotes working. I'm using this style:</p>
<pre><code>I bet you'd like more information about this sentence [^1].
[^1]: Well lucky for you, I've included more information in footnote form.
</code></pre>
<p>I did find one post (somewhere) that suggested enabling a footnotes extension for the redcarpet markdown processor, but this doesn't do it either:</p>
<pre><code>markdown: redcarpet
redcarpet:
extensions: ["footnotes"]
</code></pre>
<p>Is there any way to use Markdown footnotes without pre-generating the static site before pushing it to Github?</p> | 19,507,591 | 4 | 1 | null | 2013-10-20 23:13:24.903 UTC | 14 | 2021-09-30 18:47:15.5 UTC | null | null | null | null | 2,185 | null | 1 | 77 | jekyll|github-pages | 13,503 | <p>I use kramdown for markdown parsing and it handles footnotes nicely.</p>
<p>Change this line in your <code>_config.yml</code> file:</p>
<pre><code>markdown: redcarpet
</code></pre>
<p>to:</p>
<pre><code>markdown: kramdown
</code></pre> |
19,469,770 | How to find the callers and callee of a function in C code in vi/vim? | <p>I want to know how can I easily click (or maybe use some easy shortcuts) on a function name and find all its callee or open where it has been defined. Most of the web manuals in web are really hard to follow or don't happen to work out. Say I want to click on <code>allocuvm</code> and see where it has been defined?</p>
<pre><code>uint newstk=allocuvm(pgdir, USERTOP-PGSIZE, USERTOP);
</code></pre> | 19,470,086 | 3 | 1 | null | 2013-10-19 18:52:47.553 UTC | 9 | 2020-11-18 09:38:26.233 UTC | null | null | null | null | 2,414,957 | null | 1 | 11 | c|linux|vim|vi | 24,261 | <p>For that, Vim integrates with the <em>cscope</em> tool; see <code>:help cscope</code> for more information.</p> |
1,005,499 | Problems with asp:Button OnClick event | <p>Here is my button</p>
<pre><code><asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
</code></pre>
<p>Here is the server function</p>
<pre><code>public void doSomething(int num)
{
int someOtherNum = 10 + num;
}
</code></pre>
<p>When I try to compile the code I get the error "Method Name Expected" for the line:</p>
<pre><code><asp:Button ID="myButton" Text="Click Me" OnClick="doSomething(10)" runat="server" />
</code></pre>
<p>What am I doing wrong? Am I not allowed to pass values to the server from an OnClick event?</p> | 1,005,514 | 4 | 0 | null | 2009-06-17 07:05:16.437 UTC | 1 | 2015-05-26 14:39:34.307 UTC | null | null | null | null | 123,908 | null | 1 | 3 | c#|asp.net|onclick | 46,657 | <p>There are two problems here. First, the onclick event has a specific signature. It is</p>
<pre><code>MethodName(object sender, EventArgs e);
</code></pre>
<p>Second, in the markup, you need to pass the Method name only with no parentheses or params.</p>
<pre><code><asp:Button ID="myButton" Text="Click Me" OnClick="doSomething" runat="server" />
</code></pre>
<p>Then change your codebehind as follows:</p>
<pre><code>public void doSomething(object sender, EventArgs e)
{
....
}
</code></pre>
<p>The passing of parameters can done on a client side click event handler, in this case OnClientClick, but not on the server side handler.</p> |
929,585 | How to enable the PDO driver for sqlite3 in php? | <p>My SQLite is version 3.4.0:
<a href="http://www.picamatic.com/show/2009/05/30/03/33/3822461_343x44.jpg" rel="nofollow noreferrer">image</a></p>
<p>However my phpinfo's PDO support for SQLitev3 is not enabled/listed:
<a href="http://www.picamatic.com/show/2009/05/30/03/32/3822444_630x115.jpg" rel="nofollow noreferrer">image</a></p>
<p>How can I enable it? I installed my web server via XAMPP.</p> | 929,645 | 4 | 1 | null | 2009-05-30 11:36:05.31 UTC | null | 2019-05-02 18:55:46.843 UTC | 2015-03-28 00:28:21.693 UTC | null | 3,933,332 | null | 95,663 | null | 1 | 9 | php|sqlite|pdo|xampp | 75,518 | <p>I think that the PDO driver for sqlite3 is called 'sqlite', so you already have it installed. The sqlite2 driver is older.</p>
<blockquote>
<p>PDO_SQLITE is a driver that
implements the PHP Data Objects (PDO)
interface to enable access to SQLite 3
databases.</p>
<p>In PHP 5.1, the SQLite extension also
provides a driver for SQLite 2
databases; while it is not technically
a part of the PDO_SQLITE driver, it
behaves similarly, so it is documented
alongside it. The SQLite 2 driver for
PDO is provided primarily to make it
easier to import legacy SQLite 2
database files into an application
that uses the faster, more efficient
SQLite 3 driver. As a result, the
SQLite 2 driver is not as feature-rich
as the SQLite 3 driver.</p>
</blockquote>
<p>From <a href="http://php.net/manual/en/ref.pdo-sqlite.php" rel="noreferrer">http://php.net/manual/en/ref.pdo-sqlite.php</a></p> |
176,856 | Best Practices: What's the Best Way for Constructing Headers and Footers? | <p>What's the best way for constructing headers, and footers? Should you call it all from the controller, or include it from the view file? I'm using CodeIgniter, and I'm wanting to know what's the best practice for this. Loading all the included view files from the controller, like this?</p>
<pre><code>class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('header');
$this->load->view('menu');
$this->load->view('content', $data);
$this->load->view('footer');
}
}
</code></pre>
<p>or calling the single view file, and calling the header and footer views from there:</p>
<pre><code>//controller file
class Page extends Controller {
function index()
{
$data['page_title'] = 'Your title';
$this->load->view('content', $data);
}
}
//view file
<?php $this->load->view('header'); ?>
<p>The data from the controller</p>
<?php $this->load->view('footer'); ?>
</code></pre>
<p>I've seen it done both ways, but want to choose now before I go too far down a path.</p> | 178,882 | 4 | 1 | null | 2008-10-07 01:01:40.603 UTC | 18 | 2021-12-08 08:16:27.25 UTC | 2021-12-08 08:14:03.087 UTC | null | 4,595,675 | jmccartie | 24,708 | null | 1 | 19 | php|codeigniter|templates | 4,289 | <p>You could also try it this way -- define a default view template, which then pulls in the content based on a variable ('content' in my example) passed by the controller.</p>
<p>In your controller:</p>
<pre><code>$data['content'] = 'your_controller/index';
// more code...
$this->load->vars($data);
$this->load->view('layouts/default');
</code></pre>
<p>Then define a default layout for all pages e.g. views/layouts/default.php</p>
<pre><code>// doctype, header html etc.
<div id="content">
<?= $this->load->view($content) ?>
</div>
// footer html etc.
</code></pre>
<p>Then your views can just contain the pure content e.g. views/your_controller/index.php might contain just the variables passed from the controller/data array</p>
<pre><code><?= $archives_table ?>
<?= $pagination ?>
// etc.
</code></pre>
<p><a href="http://codeigniter.com/wiki/FAQ" rel="nofollow noreferrer">More details on the CI wiki/FAQ</a> -- (Q. How do I embed views within views? Nested templates?...)</p> |
56,844,746 | How to set uid and gid in Docker Compose? | <p>I can execute a <code>docker run</code> command as such ... </p>
<pre><code>docker run --rm --user $(id -u):$(id -g) -e MYDATA=/some/path/to/data -e USER=$USER -p 8883-8887:8883-8887 ...
</code></pre>
<p>However, in Docker Compose, when I write out the following ... </p>
<pre><code>version: '3.7'
services:
container_name: some-server
image: some:img
user: $(id -u):$(id -g)
...
</code></pre>
<p>... it does not work. </p>
<p>I understand I am asking <code>docker-compose up</code> to perform sub shell command substitution, and it cannot. </p>
<p>Is there any way to do this? </p> | 56,844,765 | 3 | 2 | null | 2019-07-02 03:00:06.673 UTC | 9 | 2022-06-09 07:01:58.233 UTC | 2019-07-02 03:03:54.633 UTC | null | 325,452 | null | 325,452 | null | 1 | 63 | bash|shell|docker|docker-compose | 82,020 | <p>Try <a href="https://dev.to/acro5piano/specifying-user-and-group-in-docker-i2e" rel="noreferrer">this</a></p>
<p>So, you need to put:</p>
<pre><code>user: "${UID}:${GID}"
</code></pre>
<p>in your docker compose and provide UID and GID as docker-compose parameter</p>
<pre><code>UID=${UID} GID=${GID} docker-compose up
</code></pre>
<p>(or define UID and GID as environment variables). </p> |
40,320,849 | NoClassDefFoundError org/apache/poi/ss/usermodel/Workbook | <p>I am running a shell script which calls a java class to get some data from database and create an excel report with that data. I get the error Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook when the code hits the below line in my java class:</p>
<pre><code>XSSFWorkbook workbook = new XSSFWorkbook ();
</code></pre>
<p>This is how I have defined the classpath:</p>
<pre><code>CLASSPATH=${CLASSPATH}:<path-to-jars>/poi-2.5.1-final-20040804.jar
CLASSPATH=${CLASSPATH}:<path-to-jars>/poi-ooxml-3.11.jar
</code></pre>
<p>I verified that the jars have been downloaded(via gradle), so trying to understand what am I missing here. Can someone please help me with this?</p>
<p>Stacktrace:</p>
<pre><code> Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/Workbook
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.test.ExcelReportGenerator.writeExcel(ExcelReportGenerator.java:26)
at com.test.ReportRunner.createReport(ReportRunner.java:109)
at com.test.ReportRunner.main(ReportRunner.java:93)
Caused by: java.lang.ClassNotFoundException: org.apache.poi.ss.usermodel.Workbook
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 15 more
</code></pre> | 40,321,789 | 5 | 1 | null | 2016-10-29 15:49:20.77 UTC | 2 | 2021-12-23 21:46:01.567 UTC | null | null | null | null | 1,318,369 | null | 1 | 3 | java|apache-poi|noclassdeffounderror|classnotfoundexception | 56,959 | <p>As per <a href="http://poi.apache.org/faq.html#faq-N10204" rel="noreferrer">this Apache POI FAQ entry</a>, mixing POI jars between different versions <em>is not supported</em> and will break in all sorts of ways, such as the one you've found. <strong>Don't do it!</strong></p>
<p>You need to be using your POI jars all from the same release. I'd suggest <a href="http://poi.apache.org/download.html" rel="noreferrer">the latest version, available here</a> (currently 3.15)</p>
<p>You should probably also review the <a href="http://poi.apache.org/overview.html#components" rel="noreferrer">components and their dependencies page</a>, to ensure you've got all the required jars for your use of Apache POI. Well, or use a dependency management tool like Maven or Gradle to handle that for you!</p> |
22,267,189 | What does the w flag mean when passed in via the ldflags option to the go command? | <p>Context: </p>
<blockquote>
<p>go 1.2, ubuntu 12.10</p>
</blockquote>
<p>Goal:</p>
<blockquote>
<p>Reduce size of compiled binaries</p>
</blockquote>
<p>Currently in my build process, I run "go install" to generate the binary.
The I read from somewhere that if I pass in <code>-w</code> it will shrink the binary.
I tried it by passing it into the <code>-ldflags</code> option & my binary lost 1MB in size.</p>
<ol>
<li>Is this <code>-w</code> flag documented anywhere? What does it actually do?</li>
<li>I then discovered the <code>strip -s <binary></code> command and ran that on top of <code>-w</code> and got
another weight loss of 750KB ! The resulting binary runs fine. Does stripping
cause problems in any situations ?</li>
</ol> | 22,276,273 | 4 | 0 | null | 2014-03-08 08:50:24.307 UTC | 13 | 2021-11-17 21:29:58.107 UTC | null | null | null | null | 834,839 | null | 1 | 37 | go | 13,552 | <p>You will get the smallest binaries if you compile with <code>-ldflags '-w -s'</code>.</p>
<p>The <code>-w</code> turns off DWARF debugging information: you will not be able to use <code>gdb</code> on the binary to look at specific functions or set breakpoints or get stack traces, because all the metadata <code>gdb</code> needs will not be included. You will also not be able to use other tools that depend on the information, like <code>pprof</code> profiling.</p>
<p>The <code>-s</code> turns off generation of the Go symbol table: you will not be able to use <code>go tool nm</code> to list the symbols in the binary. <code>strip -s</code> is like passing <code>-s</code> to <code>-ldflags</code> but it doesn't strip quite as much. <code>go tool nm</code> might still work after <code>strip -s</code>. I am not completely sure.</p>
<p>None of these — not <code>-ldflags -w</code>, not <code>-ldflags -s</code>, not <code>strip -s</code> — should affect the execution of the actual program. They only affect whether you can debug or analyze the program with other tools.</p> |
37,293,444 | PHP Laravel : How to get client browser/ Device? | <p>I'm building a laravel application where I want to keep track of client browser details such as browser name.
How do I do it using Laravel ?</p>
<pre><code>public function postUser(Request $request)
{
$user = new User();
$user->name = $request->Input(['name']);
$device= $request->header('User-Agent');
dd($device);
$user->save();
return redirect('userSavePage');
}
</code></pre>
<p>I have used this <code>$device= $request->header('User-Agent');</code>
But while I dd() the output I get something Like this:</p>
<pre><code>"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
</code></pre>
<p>How do I get actual browser details?</p> | 37,294,031 | 6 | 1 | null | 2016-05-18 07:53:05.98 UTC | 1 | 2021-05-27 09:18:06.07 UTC | null | null | null | null | 5,801,126 | null | 1 | 20 | php|laravel|laravel-5 | 57,325 | <p>First add the package to your composer:</p>
<pre><code>{
"require": {
"hisorange/browser-detect": "2.*" // For laravel 5.* versions
"hisorange/browser-detect": "1.*" // For laravel 4.* versions
}
}
</code></pre>
<p>After the composer update/install add the service provider to your app.php:</p>
<pre><code>'providers' => array(
// ...
'hisorange\BrowserDetect\Provider\BrowserDetectService',
// ...
)
</code></pre>
<p>Add the alias to the aliases in your app.php:</p>
<pre><code>'aliases' => array(
// ...
'BrowserDetect' => 'hisorange\BrowserDetect\Facade\Parser',
)
</code></pre>
<p>You must use personal configurations, just publish the package's configuration files, (plugins.php also published with this)</p>
<pre><code>php artisan vendor:publish
</code></pre>
<p>You can get result informations by simply call on the facade.</p>
<pre><code>// You can always get the result object from the facade if you wish to operate with it.
BrowserDetect::detect(); // Will resolve and return with the 'browser.result' container.
// Calls are mirrored to the result object for easier use.
BrowserDetect::browserVersion(); // return '3.6' string.
// Supporting human readable formats.
BrowserDetect::browserName(); // return 'Firefox 3.6' string.
// Or can be objective.
BrowserDetect::browserFamily(); // return 'Firefox' string.
</code></pre>
<p>For details: <a href="https://github.com/hisorange/browser-detect" rel="noreferrer">https://github.com/hisorange/browser-detect</a></p> |
36,394,101 | pip install - locale.Error: unsupported locale setting | <p>Full stacktrace: </p>
<pre><code>➜ ~ pip install virtualenv
Traceback (most recent call last):
File "/usr/bin/pip", line 11, in <module>
sys.exit(main())
File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main
locale.setlocale(locale.LC_ALL, '')
File "/usr/lib64/python3.4/locale.py", line 592, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
</code></pre>
<p>On the same server, I successfully ran <code>pip install virtualenv</code> with python 2.7.x. </p>
<p>Now, I've just installed python3.4 using <code>curl https://bootstrap.pypa.io/get-pip.py | python3.4</code>. </p>
<pre><code>➜ ~ pip --version
pip 8.1.1 from /usr/lib/python3.4/site-packages (python 3.4)
</code></pre>
<p><code>pip uninstall virtualenv</code> throws the same error too</p> | 36,394,262 | 10 | 4 | null | 2016-04-04 03:24:45.033 UTC | 88 | 2021-12-08 12:11:44.713 UTC | 2018-04-01 06:31:23.07 UTC | null | 541,624 | null | 541,624 | null | 1 | 255 | python|python-3.x|centos|pip | 202,860 | <p>The root cause is: your environment variable <code>LC_ALL</code> is missing or invalid somehow </p>
<p><strong>Short answer-</strong> </p>
<p>just run the following command:</p>
<pre><code>$ export LC_ALL=C
</code></pre>
<p>If you keep getting the error in new terminal windows, add it at the bottom of your <code>.bashrc</code> file.</p>
<p><strong>Long answer-</strong></p>
<p>Here is my <code>locale</code> settings:</p>
<pre><code>$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C
</code></pre>
<p><em>Python2.7</em></p>
<pre><code> $ uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
$ python --version
Python 2.7.9
$ pip --version
pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
$ unset LC_ALL
$ pip install virtualenv
Traceback (most recent call last):
File "/usr/local/bin/pip", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
locale.setlocale(locale.LC_ALL, '')
File "/usr/lib/python2.7/locale.py", line 579, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
$ export LC_ALL=C
$ pip install virtualenv
Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages
</code></pre> |
4,498,099 | Silent printing of a PDF in Python | <p>I'm trying to print a PDF with Python, without opening the PDF viewer application (Adobe, Foxit etc.). I need also to know when printing has finished (to delete the file).</p>
<p><a href="http://permalink.gmane.org/gmane.comp.python.windows/6558" rel="noreferrer">Here</a> I found this <strong>implementation</strong>:</p>
<pre><code>import win32ui, dde, os.path, time
from win32api import FindExecutable
from os import spawnl, P_NOWAIT
...
pd = "C:\\temp\\test.pdf"
pdbits = os.path.split(pd)
readerexe = FindExecutable(pdbits[1],pdbits[0])
spawnl(P_NOWAIT,readerexe[1],"DUMMY") #I added "DUMMY" to avoid a weird error
time.sleep(2)
s = dde.CreateServer()
s.Create('')
c = dde.CreateConversation(s)
c.ConnectTo('acroview', 'control')
c.Exec('[FilePrintSilent("%s")]' % (pd,))
s.Destroy()
</code></pre>
<p>But it throws this exception at the <code>ConnectTo</code> line:</p>
<pre><code>dde.error: ConnectTo failed
</code></pre>
<p>Someone knows how to solve it? Or has a <strong>different solution</strong> for silent printing? Or at list can give a link to a <strong>reference for <code>ConnectTo</code></strong>? Could find nothing on the web about it.</p>
<p>Working with: Python 2.7, Windows 7, Acrobat Reader 10.0</p> | 4,498,956 | 1 | 0 | null | 2010-12-21 10:07:16.21 UTC | 9 | 2012-07-19 13:47:48.237 UTC | 2010-12-30 16:12:11.25 UTC | null | 505,893 | null | 505,893 | null | 1 | 14 | python|windows|pdf|printing|silent | 13,183 | <p>I suggest you install <a href="http://pages.cs.wisc.edu/~ghost/gsview/get49.htm" rel="noreferrer">GSView</a> and <a href="http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm" rel="noreferrer">GSPrint</a> and shell out to <code>gsprint.exe</code> to print the pdf.</p>
<pre><code>p = subprocess.Popen([r"p:\ath\to\gsprint.exe", "test.pdf"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print stdout
print stderr
</code></pre>
<p>I have used this in a industrial label printing solution, works great.</p>
<p>When the <code>gsprint.exe</code> program exits (i.e. after the call to <code>communicate</code>), you can delete the pdf file.</p> |
14,062,402 | Awk: using a file to filter another one (out.tr) | <p>Help with awk, using a file to filter another one
I have a main file:</p>
<pre><code>...
17,466971 0,095185 17,562156 id 676
17,466971 0,096694 17,563665 id 677
17,466971 0,09816 17,565131 id 678
17,466971 0,099625 17,566596 id 679
17,466971 0,101091 17,568062 id 680
17,466971 0,016175 17,483146 id 681
17,466971 0,101793 17,568764 id 682
17,466971 0,10253 17,569501 id 683
38,166772 0,08125 38,248022 id 1572
38,166772 0,082545 38,249317 id 1573
38,233772 0,005457 38,239229 id 1574
38,233772 0,082113 38,315885 id 1575
38,299771 0,081412 38,381183 id 1576
38,299771 0,006282 38,306053 id 1577
38,299771 0,083627 38,383398 id 1578
38,299771 0,085093 38,384864 id 1579
38,299771 0,008682 38,308453 id 1580
38,299771 0,085094 38,384865 id 1581
...
</code></pre>
<p>I want to suppress/delete some lines based on this other file, last column (id) :</p>
<pre><code>...
d 17.483146 1 0 udp 181 ------- 1 19.0 2.0 681
d 38.239229 1 0 udp 571 ------- 1 19.0 2.0 1574
d 38.306053 1 0 udp 1000 ------- 1 19.0 2.0 1577
d 38.308453 1 0 udp 1000 ------- 1 19.0 2.0 1580
d 38.372207 1 0 udp 546 ------- 1 19.0 2.0 1582
d 38.441845 1 0 udp 499 ------- 1 19.0 2.0 1585
d 38.505262 1 0 udp 616 ------- 1 19.0 2.0 1586
d 38.572324 1 0 udp 695 ------- 1 19.0 2.0 1588
d 38.639246 1 0 udp 597 ------- 1 19.0 2.0 1590
d 38.639758 1 0 udp 640 ------- 1 19.0 2.0 1591
...
</code></pre>
<p>For the example above, the result would be:</p>
<pre><code>17,466971 0,095185 17,562156 id 676
17,466971 0,096694 17,563665 id 677
17,466971 0,09816 17,565131 id 678
17,466971 0,099625 17,566596 id 679
17,466971 0,016175 17,483146 id 680
17,466971 0,101793 17,568764 id 682
17,466971 0,10253 17,569501 id 683
38,166772 0,08125 38,248022 id 1572
38,166772 0,082545 38,249317 id 1573
38,233772 0,082113 38,315885 id 1575
38,299771 0,081412 38,381183 id 1576
38,299771 0,083627 38,383398 id 1578
38,299771 0,085093 38,384864 id 1579
38,299771 0,085094 38,384865 id 1581
</code></pre>
<p>The lines deletes were:</p>
<pre><code>17,466971 0,101091 17,568062 id 681
38,233772 0,005457 38,239229 id 1574
38,299771 0,006282 38,306053 id 1577
38,299771 0,008682 38,308453 id 1580
</code></pre>
<p>Is there a command using awk to make this automatic?</p>
<p>Thank you in advance</p> | 14,062,579 | 1 | 3 | null | 2012-12-27 22:58:36.287 UTC | 10 | 2018-06-25 07:26:07.443 UTC | 2015-03-26 06:12:33.653 UTC | null | 13,302 | null | 1,933,267 | null | 1 | 6 | awk | 6,685 | <p>Here's one way using <code>awk</code>:</p>
<pre><code>awk 'FNR==NR { a[$NF]; next } !($NF in a)' other main
</code></pre>
<p>Results:</p>
<pre><code>17,466971 0,095185 17,562156 id 676
17,466971 0,096694 17,563665 id 677
17,466971 0,09816 17,565131 id 678
17,466971 0,099625 17,566596 id 679
17,466971 0,101091 17,568062 id 680
17,466971 0,101793 17,568764 id 682
17,466971 0,10253 17,569501 id 683
38,166772 0,08125 38,248022 id 1572
38,166772 0,082545 38,249317 id 1573
38,233772 0,082113 38,315885 id 1575
38,299771 0,081412 38,381183 id 1576
38,299771 0,083627 38,383398 id 1578
38,299771 0,085093 38,384864 id 1579
38,299771 0,085094 38,384865 id 1581
</code></pre>
<p>Drop the exclamation mark to show the 'deleted' lines:</p>
<pre><code>awk 'FNR==NR { a[$NF]; next } $NF in a' other main
</code></pre>
<p>Results:</p>
<pre><code>17,466971 0,016175 17,483146 id 681
38,233772 0,005457 38,239229 id 1574
38,299771 0,006282 38,306053 id 1577
38,299771 0,008682 38,308453 id 1580
</code></pre>
<hr>
<p>Alternatively, if you'd like two files, one containing values 'present' and the other containing values 'deleted', try:</p>
<pre><code>awk 'FNR==NR { a[$NF]; next } { print > ($NF in a ? "deleted" : "present") }' other main
</code></pre>
<hr>
<p><em>Explanation1:</em></p>
<p><code>FNR==NR { ... }</code> is a commonly used construct that returns true for only the first file in the arguments list. In this case, <code>awk</code> will read the file 'other' first. When this file is being processed, the value in the last column (<code>$NF</code>) is added to an array (which we have called <code>a</code>). <code>next</code> then skips processing the rest of our code. Once the first file has been read, <code>FNR</code> will no longer be equal to <code>NR</code>, thus <code>awk</code> will be 'allowed' to skip the <code>FNR--NR { ... }</code> block and begin processing the remainder of the code which is applied to the second file in the arguments list, 'main'. For example, <code>!($NF in a)</code>, will not print the line if <code>$NF</code> is not in the array.</p>
<p><em>Explanation2:</em></p>
<p>With regards to which column, you may find this helpful:</p>
<pre><code>$1 # the first column
$2 # the second column
$3 # the third column
$NF # the last column
$(NF-1) # the second last column
$(NF-2) # the third last column
</code></pre> |
34,588,117 | How can I convert a part of Java source file to Kotlin? | <p>In my Kotlin project, I have some parts of Java code that I want to convert to Kotlin. The menu item that converts the Java file to Kotlin is disabled because it's not a whole file I want to convert.</p>
<p>How can I convert Java code to Kotlin?</p> | 34,588,153 | 15 | 2 | null | 2016-01-04 09:33:08.45 UTC | 13 | 2021-06-11 17:54:47.657 UTC | 2021-06-11 16:47:13.46 UTC | null | 11,598,941 | null | 1,708,058 | null | 1 | 95 | java|android|android-studio|kotlin | 149,452 | <p>There is no tool to convert Kotlin code to Java. If you want to convert part of a file from Java to Kotlin, the easiest way is to copy the code from the Java file in the IDE and paste it into the Kotlin file.</p> |
24,975,955 | Sending an ASP.net POST with Python's Requests | <p>I'm scraping an old ASP.net website using Python's requests module.</p>
<p>I've spent 5+ hours trying to figure out how to simulate this POST request to no avail. Doing it the way I do it below, I essentially get a message saying "No item matches this item reference."</p>
<p>Any help would be deeply appreciated – here's the request and my code, a few things are modified out of respect to brevity and/or privacy:</p>
<p><strong>My own code:</strong></p>
<pre><code>import requests
# Scraping the item number from the website, I have confirmed this is working.
#Then use the newly acquired item number to request the data.
item_url = http://www.example.com/EN/items/Pages/yourrates.aspx?vr= + item_number[0]
viewstate = r'/wEPD...' # Truncated for brevity.
# Create the appropriate request and payload.
payload = {"vr": int(item_number[0])}
item_request_body = {
"__SPSCEditMenu": "true",
"MSOWebPartPage_PostbackSource": "",
"MSOTlPn_SelectedWpId": "",
"MSOTlPn_View": 0,
"MSOTlPn_ShowSettings": "False",
"MSOGallery_SelectedLibrary": "",
"MSOGallery_FilterString": "",
"MSOTlPn_Button": "none",
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
"MSOAuthoringConsole_FormContext": "",
"MSOAC_EditDuringWorkflow": "",
"MSOSPWebPartManager_DisplayModeName": "Browse",
"MSOWebPartPage_Shared": "",
"MSOLayout_LayoutChanges": "",
"MSOLayout_InDesignMode": "",
"MSOSPWebPartManager_OldDisplayModeName": "Browse",
"MSOSPWebPartManager_StartWebPartEditingName": "false",
"__VIEWSTATE": viewstate,
"keywords": "Search our site",
"__CALLBACKID": "ctl00$SPWebPartManager1$g_dbb9e9c7_fe1d_46df_8789_99a6c9db4b22",
"__CALLBACKPARAM": "startvr"
}
# Write the appropriate headers for the property information.
item_request_headers = {
"Host": home_site,
"Connection": "keep-alive",
"Content-Length": len(encoded_valuation_request),
"Cache-Control": "max-age=0",
"Origin": home_site,
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Cookie": "__utma=48409910.1174413745.1405662151.1406402487.1406407024.17; __utmb=48409910.7.10.1406407024; __utmc=48409910; __utmz=48409910.1406178827.13.3.utmcsr=ratesandvallandingpage|utmccn=landingpages|utmcmd=button",
"Accept": "*/*",
"Referer": valuation_url,
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "en-US,en;q=0.8"
}
response = requests.post(url=item_url, params=payload, data=item_request_body, headers=item_request_headers)
print response.text
</code></pre>
<p><strong>What Chrome is telling me the request looks like:</strong></p>
<pre><code>Remote Address:202.55.96.131:80
Request URL:http://www.example.com/EN/items/Pages/yourrates.aspx?vr=123456789
Request Method:POST
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:21501
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:__utma=48409910.1174413745.1405662151.1406402487.1406407024.17; __utmb=48409910.7.10.1406407024; __utmc=48409910; __utmz=48409910.1406178827.13.3.utmcsr=ratesandvallandingpage|utmccn=landingpages|utmcmd=button
Host:www.site.com
Origin:www.site.com
Referer:http://www.example.com/EN/items/Pages/yourrates.aspx?vr=123456789
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Query String Parameters
vr:123456789
Form Data
__SPSCEditMenu:true
MSOWebPartPage_PostbackSource:
MSOTlPn_SelectedWpId:
MSOTlPn_View:0
MSOTlPn_ShowSettings:False
MSOGallery_SelectedLibrary:
MSOGallery_FilterString:
MSOTlPn_Button:none
__EVENTTARGET:
__EVENTARGUMENT:
MSOAuthoringConsole_FormContext:
MSOAC_EditDuringWorkflow:
MSOSPWebPartManager_DisplayModeName:Browse
MSOWebPartPage_Shared:
MSOLayout_LayoutChanges:
MSOLayout_InDesignMode:
MSOSPWebPartManager_OldDisplayModeName:Browse
MSOSPWebPartManager_StartWebPartEditingName:false
__VIEWSTATE:/wEPD...(Omitted for length)
keywords:Search our site
__CALLBACKID:ctl00$SPWebPartManager1$g_dbb9e9c7_fe1d_46df_8789_99a6c9db4b22
__CALLBACKPARAM:startvr
</code></pre> | 24,976,108 | 1 | 3 | null | 2014-07-26 22:06:38.87 UTC | 8 | 2020-03-04 21:38:52.303 UTC | null | null | null | null | 1,492,162 | null | 1 | 11 | python|asp.net|web-scraping|python-requests | 16,105 | <p>You have too many request parameters, and should <em>not</em> set the content-type, content-length, host, origin, or connection headers; <em>leave those to <code>requests</code> to set</em>.</p>
<p>You are also doubling up the url parameters; either add the <code>vr</code> parameter to the URL manually <em>or</em> use <code>params</code>, not do both.</p>
<p>It may well be that some of the parameters in the POST body are generated by the ASP application tied to a session. I'd use a GET request with a <a href="https://requests.readthedocs.io/en/latest/user/advanced/#session-objects" rel="noreferrer">Session object</a> the <code>valuation_url</code>, parse the form in that page to extract the <code>__CALLBACKID</code> parameter. The requests Session will then store any cookies the server sets and reuse those:</p>
<pre><code>item_request_headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "en-US,en;q=0.8"
}
payload = {"vr": int(item_number[0])}
session = requests.Session(headers=item_request_headers)
# Get form page
form_response = session.get(validation_url, params=payload)
# parse form page; BeautifulSoup could do this for example
soup = BeautifulSoup(form_response.content)
callbackid = soup.select('input[name=__CALLBACKID]')[0]['value']
item_request_body = {
"__SPSCEditMenu": "true",
"MSOWebPartPage_PostbackSource": "",
"MSOTlPn_SelectedWpId": "",
"MSOTlPn_View": 0,
"MSOTlPn_ShowSettings": "False",
"MSOGallery_SelectedLibrary": "",
"MSOGallery_FilterString": "",
"MSOTlPn_Button": "none",
"__EVENTTARGET": "",
"__EVENTARGUMENT": "",
"MSOAuthoringConsole_FormContext": "",
"MSOAC_EditDuringWorkflow": "",
"MSOSPWebPartManager_DisplayModeName": "Browse",
"MSOWebPartPage_Shared": "",
"MSOLayout_LayoutChanges": "",
"MSOLayout_InDesignMode": "",
"MSOSPWebPartManager_OldDisplayModeName": "Browse",
"MSOSPWebPartManager_StartWebPartEditingName": "false",
"__VIEWSTATE": viewstate,
"keywords": "Search our site",
"__CALLBACKID": callbackid,
"__CALLBACKPARAM": "startvr"
}
item_url = 'http://www.example.com/EN/items/Pages/yourrates.aspx'
response = session.post(url=item_url, params=payload, data=item_request_body,
headers={'Referer': form_response.url})
</code></pre>
<p>The session handles the headers (setting a user agent, and accept parameters), only on the POST with the session do we add a referrer header as well.</p> |
6,659,662 | Why is the DOMSubtreeModified event deprecated in DOM level 3? | <p>Why is the DOMSubtreeModified event <a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMSubtreeModified">deprecated</a> and what are we supposed to use instead?</p> | 6,659,678 | 2 | 0 | null | 2011-07-12 04:57:42.683 UTC | 12 | 2022-02-12 09:23:22.35 UTC | 2022-02-12 09:23:22.35 UTC | null | 4,370,109 | null | 161,972 | null | 1 | 59 | javascript|dom|dom-events|deprecated|dom3 | 60,315 | <p>If you <a href="http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents" rel="noreferrer">scroll down a bit</a>, you see:</p>
<blockquote>
<p>Warning! The <code>MutationEvent</code> interface was introduced in DOM Level 2
Events, but has not yet been completely and interoperably implemented
across user agents. In addition, there have been critiques that the
interface, as designed, introduces a performance and implementation
challenge. A new specification is under development with the aim of
addressing the use cases that mutation events solves, but in more
performant manner. Thus, this specification describes mutation events
for reference and completeness of legacy behavior, but deprecates the
use of both the <code>MutationEvent</code> interface and the <code>MutationNameEvent</code>
interface.</p>
</blockquote>
<p>The replacement API is <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver" rel="noreferrer">mutation observers</a>, which are fully specified <a href="https://dom.spec.whatwg.org/#mutation-observers" rel="noreferrer">in the DOM Living Standard</a> that supercedes all of the DOM level X silliness.</p> |
6,713,484 | smart pointers and arrays | <p>How do smart pointers handle arrays? For example,</p>
<pre><code>void function(void)
{
std::unique_ptr<int> my_array(new int[5]);
}
</code></pre>
<p>When <code>my_array</code> goes out of scope and gets destructed, does the entire integer array get re-claimed? Is only the first element of the array reclaimed? Or is there something else going on (such as undefined behavior)?</p> | 6,713,515 | 2 | 0 | null | 2011-07-15 21:44:16.047 UTC | 15 | 2018-05-11 11:10:43.543 UTC | 2011-07-15 22:40:03.873 UTC | null | 726,300 | null | 558,546 | null | 1 | 59 | c++|c++11|smart-pointers | 40,110 | <p>It will call <code>delete[]</code> and hence the entire array will be reclaimed but I believe you need to indicate that you are using an array form of <code>unique_ptr</code>by:</p>
<pre><code>std::unique_ptr<int[]> my_array(new int[5]);
</code></pre>
<p>This is called as <strong>Partial Specialization</strong> of the <code>unique_ptr</code>.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.