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
35,240,716
Webpack import returns undefined, depending on the order of imports
<p>I'm using webpack + babel. I have three modules looking like this:</p> <pre class="lang-js prettyprint-override"><code>// A.js // some other imports here console.log('A'); export default 'some-const'; // B.js import someConst from './A'; console.log('B', someConst); export default 'something-else'; // main.js import someConst from './A'; import somethingElse from './B'; console.log('main', someConst); </code></pre> <p>When <code>main.js</code> is executed, I see the following:</p> <pre><code>B undefined A main some-const </code></pre> <p>If I swap the imports in <code>main.js</code>, <code>B</code> becoming the first, I get:</p> <pre><code>A B some-const main some-const </code></pre> <p>How come <code>B.js</code> gets <code>undefined</code> instead of a module in the first version? What's wrong?</p>
35,240,717
3
0
null
2016-02-06 11:57:50.037 UTC
27
2022-06-22 06:30:30.64 UTC
2016-02-22 06:23:48.95 UTC
null
785,065
null
242,684
null
1
90
javascript|webpack|babeljs
33,035
<p>After almost a full workday of narrowing down the issue (AKA hair-pulling), I've finally came to realize that I have a circular dependency.</p> <p>Where it says <code>// some other imports here</code>, <code>A</code> imports another module <code>C</code>, which, in turn, imports <code>B</code>. <code>A</code> gets imported first in <code>main.js</code>, so <code>B</code> ends up being the last link in the "circle", and Webpack (or any CommonJS-like environment, for that matter, like Node) just short-circuits it by returning <code>A</code>'s <code>module.exports</code>, which is still <code>undefined</code>. Eventually, it becomes equal to <code>some-const</code>, but the synchronous code in <code>B</code> ends up dealing with <code>undefined</code> instead.</p> <p>Eliminating the circular dependency, by moving out the code that <code>C</code> depends on out of <code>B</code>, has resolved the issue. Wish Webpack would somehow warn me about this.</p> <p><strong>Edit:</strong> On the last note, as pointed out by @cookie, <a href="https://www.npmjs.com/package/circular-dependency-plugin">there's a plugin for circular dependency detection</a>, if you'd like to avoid hitting this problem [again].</p>
34,967,868
How to use data-binding in Dialog?
<p>I am having trouble in implementing databinding in a Dialog. Is it possible?</p> <p>Below is my xml.</p> <p> </p> <pre><code>&lt;data&gt; &lt;variable name="olaBooking" type="com.example.myapp.viewmodels.ViewModel" /&gt; &lt;/data&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;android.support.v7.widget.CardView android:id="@+id/cv" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:elevation="4dp" android:padding="15dp"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"&gt; &lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:gravity="center" android:padding="15dp" android:text="OLA Cab Booked !" android:textAppearance="@style/TextAppearance.AppCompat.Body1" /&gt; &lt;View android:layout_width="match_parent" android:layout_height="2dp" android:background="@color/colorPrimaryDark" /&gt; &lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="start|center" android:padding="15dp" android:text="Car Details" /&gt; &lt;View android:layout_width="match_parent" android:layout_height="2dp" android:background="@color/colorPrimaryDark" /&gt; &lt;TextView android:id="@+id/driverName" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" android:text="@{olaBooking.driverName}" /&gt; &lt;TextView android:id="@+id/carModel" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" android:text="@{olaBooking.getCarName}" /&gt; &lt;TextView android:id="@+id/carNo" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" android:text="@{olaBooking.getCabNo}" /&gt; &lt;TextView android:id="@+id/eta" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp" android:text="@{olaBooking.getEta}" /&gt; &lt;/LinearLayout&gt; &lt;/android.support.v7.widget.CardView&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>I want to bind the above layout in a Dialog. How is it possible? Below is my java code i tried but it's not working </p> <pre><code> dialog.setContentView(R.layout.dialog_ola_booking_confirmed); DialogOlaBookingConfirmedBinding binding = DataBindingUtil.inflate( LayoutInflater.from(dialog.getContext()), R.layout.dialog_ola_booking_confirmed, (ViewGroup) dialog.findViewById(R.id.cv), false); ViewModel viewModel = new ViewModel(this, event.olaBooking); </code></pre>
36,651,310
8
0
null
2016-01-23 19:33:41.943 UTC
16
2022-06-21 00:43:12.217 UTC
2016-01-25 08:15:14.71 UTC
null
2,214,748
null
2,214,748
null
1
82
android|mvvm|data-binding|android-databinding
61,231
<p>It is possible to use databinding in a Dialog, first to get the binding working on your Dialog you should inflate it first and pass it to the setContentView like this.</p> <pre><code>DialogOlaBookingConfirmedBinding binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout. dialog_ola_booking_confirmed, null, false); setContentView(binding.getRoot()); </code></pre> <p>Then you can pass the viewModel:</p> <pre><code>binding.setViewModel(new ViewModel(this, event.olaBooking)); </code></pre> <p>And now you can see it working.</p>
32,109,822
Why is `throw` invalid in an ES6 arrow function?
<p>I'm just looking for a reason as to <em>why</em> this is invalid:</p> <pre><code>() =&gt; throw 42; </code></pre> <p>I know I can get around it via:</p> <pre><code>() =&gt; {throw 42}; </code></pre>
32,109,863
3
0
null
2015-08-20 04:56:43.103 UTC
3
2022-04-13 11:58:42.18 UTC
2022-04-13 11:58:42.18 UTC
null
1,839,439
user578895
null
null
1
39
javascript|ecmascript-6|arrow-functions
5,673
<p>If you don't use a block (<code>{}</code>) as body of an <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-arrow-function-definitions">arrow function</a>, the body must be an <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ecmascript-language-expressions"><strong>expression</strong></a>:</p> <pre class="lang-none prettyprint-override"><code>ArrowFunction: ArrowParameters[no LineTerminator here] =&gt; ConciseBody ConciseBody: [lookahead ≠ { ] AssignmentExpression { FunctionBody } </code></pre> <p>But <code>throw</code> is a <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ecmascript-language-statements-and-declarations"><em>statement</em></a>, not an expression.</p> <hr> <p>In theory</p> <pre><code>() =&gt; throw x; </code></pre> <p>is equivalent to</p> <pre><code>() =&gt; { return throw x; } </code></pre> <p>which would not be valid either.</p>
27,337,819
WPF ToggleButton XAML styling
<p>So I have two toggle buttons that I am trying to combine - sort of. So the first button toggles the images based on whether it IsChecked is true or false, but this button has a border around it that I can't get rid of.</p> <p>The second toggle button doesn't have a border and doesn't blink when clicked, but it also doesn't change images based on it's state. </p> <p>What I want is the best of both worlds. Change the image AND get rid of the border. I have tried exactly 23 things and none of them work.</p> <p>Here is the code I am using:</p> <pre><code>&lt;ToggleButton x:Name="changeButBorderedBlinky" Margin="0,12,194,0" Width="82" Height="82" Background="Transparent" Padding="-1" Focusable="false" VerticalAlignment="Top" HorizontalAlignment="Right"&gt; &lt;ToggleButton.Style&gt; &lt;Style TargetType="{x:Type ToggleButton}"&gt; &lt;Setter Property="Content"&gt; &lt;Setter.Value&gt; &lt;Border BorderThickness="0" &gt; &lt;Image Source="images/buttonimages/back2.png" Stretch="Fill" /&gt; &lt;/Border&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="IsChecked" Value="True"&gt; &lt;Setter Property="Content"&gt; &lt;Setter.Value&gt; &lt;Border BorderThickness="0" &gt; &lt;Image Source="images/buttonimages/back.png" Stretch="fill" /&gt; &lt;/Border&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ToggleButton.Style&gt; &lt;/ToggleButton&gt; &lt;ToggleButton x:Name="noChangeNoBorder" Margin="0,12,104,0" VerticalAlignment="Top" HorizontalAlignment="Right" Height="80" Width="80" &gt; &lt;ToggleButton.Template&gt; &lt;ControlTemplate TargetType="{x:Type ToggleButton}"&gt; &lt;Border x:Name="border" &gt; &lt;Image x:Name="img" Source="images/buttonimages/back2.png" /&gt; &lt;/Border&gt; &lt;/ControlTemplate&gt; &lt;/ToggleButton.Template&gt; &lt;/ToggleButton&gt; </code></pre> <p>Thanks for any help on this. It's driving me insane.</p>
27,338,029
2
0
null
2014-12-06 23:36:41.637 UTC
null
2020-01-31 15:39:40.387 UTC
2014-12-07 01:15:32.48 UTC
null
979,580
null
3,232,211
null
1
3
wpf|xaml|togglebutton|wpf-style
42,289
<p>Try to use slightly modified XAML pertinent to your first ToggleButton:</p> <pre><code>&lt;ToggleButton x:Name="changeButBorderedBlinky" Margin="0,12,194,0" Width="82" Height="82" Background="Transparent" Padding="-1" Focusable="false" VerticalAlignment="Top" HorizontalAlignment="Right"&gt; &lt;ToggleButton.Style&gt; &lt;Style TargetType="{x:Type ToggleButton}"&gt; &lt;Setter Property="BorderThickness" Value="0"/&gt; &lt;Setter Property="Content"&gt; &lt;Setter.Value&gt; &lt;Image Source="images/buttonimages/back2.png" Stretch="Fill" /&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="IsChecked" Value="True"&gt; &lt;Setter Property="Content"&gt; &lt;Setter.Value&gt; &lt;Image Source="images/buttonimages/back.png" Stretch="fill" /&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ToggleButton.Style&gt; &lt;/ToggleButton&gt; </code></pre> <p>You can also try to customize other properties, for eg:</p> <pre><code> &lt;Setter Property="Background" Value="#FF1F3B53"/&gt; &lt;Setter Property="Foreground" Value="#FF000000"/&gt; &lt;Setter Property="BorderBrush" Value="Transparent"&gt; </code></pre> <p>For more styling options refer to: <a href="http://msdn.microsoft.com/en-us/library/cc296245%28v=vs.95%29.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc296245%28v=vs.95%29.aspx</a></p> <p>Hope this will help. Regards,</p>
40,398,779
dompdf : image not found or type unknown
<p>Here is my code, I mostly tried all the methods for displaying image on PDF but still didnt work. Could you please help me for this. I also set DOMPDF_ENABLE_REMOTE to true and still results is same.</p> <pre><code>require_once("dompdf/autoload.inc.php"); //require('WriteHTML.php'); $html = '&lt;body&gt; &lt;div id="watermark"&gt;&lt;img src="/var/htdocs/PDF/header.png" height="100%" width="100%"&gt;&lt;/div&gt; &lt;div id="header"&gt; &lt;h3 style="padding-top:10px;"&gt;'.$_POST['name'].'&lt;/h3&gt; &lt;/div&gt; &lt;div id="footer"&gt; &lt;h3 style="padding-top:8px; padding-right:25px;" class="CIJ"&gt;ABSOLUTE MARKET INSIGHTS&lt;/h3&gt; &lt;/div&gt; &lt;div&gt; &lt;br&gt;&lt;br&gt;&lt;div class="ooo" style="padding-top: 20px;"&gt;'.$_POST['comment'].'&lt;/div&gt; &lt;/div&gt; &lt;/body&gt;'; use Dompdf\Dompdf; $dompdf = new Dompdf(); $canvas = $dompdf-&gt;get_canvas(); $dompdf-&gt;load_html($html); $dompdf-&gt;render(); $dompdf-&gt;stream($_POST["name"], array("Attachment" =&gt; false)); </code></pre>
40,399,209
8
1
null
2016-11-03 10:09:19.473 UTC
null
2022-01-12 16:01:48.263 UTC
2016-11-03 14:02:23.973 UTC
null
7,109,093
null
7,109,093
null
1
5
php|html|twitter-bootstrap|dompdf
45,240
<p>You should be using the full URL instead of a direct path. Especially when it is not a static image: dompdf will open that php script directly, so it won't be executed as if it's a PHP script.</p> <p>If the full URL doesn't work, you can also show what the result of header.php is. Some good things to keep in mind are to send proper content-type headers and so on.</p>
50,942,544
Emit event from content in slot to parent
<p>I'm trying to build a flexible carousel control that allows inner content elements to force changing a slide, aswell as the carousel controls itself to change slides</p> <p>A sample structure in my page looks like</p> <pre><code>&lt;my-carousel&gt; &lt;div class="slide"&gt; &lt;button @click="$emit('next')"&gt;Next&lt;/button&gt; &lt;/div&gt; &lt;div class="slide"&gt; &lt;button @click="$emit('close')"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/my-carousel&gt; </code></pre> <p>The template for my carousel is like</p> <pre><code>&lt;div class="carousel"&gt; &lt;div class="slides" ref="slides"&gt; &lt;slot&gt;&lt;/slot&gt; &lt;/div&gt; &lt;footer&gt; &lt;!-- other carousel controls like arrows, indicators etc go here --&gt; &lt;/footer&gt; &lt;/div&gt; </code></pre> <p>And script like</p> <pre><code>... created() { this.$on('next', this.next) } ... </code></pre> <p>Accessing the slides etc is no problem, however using <code>$emit</code> will not work and I can't seem to find a simple solution for this problem.</p> <p>I want to component to be easily reusable without having to use</p> <ul> <li>central event bus</li> <li>hardcoded slides within a carousel</li> <li>implement the next slide methods on page level and pass the current index to the control (as I'd have to do this every time I use the carousel)</li> </ul>
50,943,093
10
0
null
2018-06-20 07:25:16.207 UTC
5
2022-07-23 22:10:12.753 UTC
2019-08-06 13:40:08.327 UTC
null
266,069
null
2,940,794
null
1
40
vue.js|vuejs2|vue-component
38,482
<p>Slots are compiled against the parent component scope, therefore events you emit from the slot will only be received by the component the template belongs to.</p> <p>If you want interaction between the carousel and slides, you can use a <a href="https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots" rel="noreferrer">scoped slot</a> instead which allows you to expose data and methods from the carousel to the slot.</p> <p>Assuming your carousel component has <code>next</code> and <code>close</code> methods:</p> <p><strong>Carousel template:</strong></p> <pre class="lang-vue prettyprint-override"><code>&lt;div class=&quot;carousel&quot;&gt; &lt;div class=&quot;slides&quot; ref=&quot;slides&quot;&gt; &lt;slot :next=&quot;next&quot; :close=&quot;close&quot;&gt;&lt;/slot&gt; &lt;/div&gt; &lt;footer&gt; &lt;!-- Other carousel controls like arrows, indicators etc go here --&gt; &lt;/footer&gt; &lt;/div&gt; </code></pre> <p><strong>Carousel example usage:</strong></p> <pre class="lang-vue prettyprint-override"><code>&lt;my-carousel v-slot=&quot;scope&quot;&gt; &lt;div class=&quot;slide&quot;&gt; &lt;button @click=&quot;scope.next&quot;&gt;Next&lt;/button&gt; &lt;/div&gt; &lt;div class=&quot;slide&quot;&gt; &lt;button @click=&quot;scope.close&quot;&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/my-carousel&gt; </code></pre>
20,906,503
What is the extension of a Android Studio project file?
<p>What is the Android Studio equivalent of Solution file in (.sln) file in Visual Studio ? I created a project in Android studio and closed it. Now I am not sure which file should I open to reload it into Android studio. </p>
20,906,543
10
0
null
2014-01-03 15:02:12.68 UTC
2
2020-06-29 08:57:42.133 UTC
2019-06-14 19:32:43.02 UTC
null
6,296,561
null
1,347,674
null
1
28
android-studio
33,040
<p>Use the <code>import project</code> function on the <code>build.gradle</code> file in your project root (not the folder itself!) to open the project again in Android Studio.</p>
41,743,720
crontab run every 15 minutes between certain hours
<p>Is this correct scheduled to run between 07:00 and 19:00 at every 15 minutes?</p> <pre><code>*/15 07-19 * * * /path/script </code></pre>
41,743,794
2
0
null
2017-01-19 14:05:06.333 UTC
13
2019-12-23 13:40:35.027 UTC
2017-01-19 14:06:54.54 UTC
null
1,983,854
null
5,588,639
null
1
60
linux|cron|crontab|schedule
84,748
<p>Your command is fine!</p> <p>To run from 7.00 until 19.45, every 15 minutes just use <code>*/15</code> as follows:</p> <pre><code>*/15 07-19 * * * /path/script ^^^^ ^^^^^ </code></pre> <p>That is, the content <code>*/15</code> in the minutes column will do something every 15 minutes, while the second column, for hours, will do that thing on the specified range of hours.</p> <p>If you want it to run until 19.00 then you have to write two lines:</p> <pre><code>*/15 07-18 * * * /path/script 0 19 * * * /path/script </code></pre> <p>You can have a full description of the command in crontab.guru: <a href="https://crontab.guru/#*/15_7-19_*_*_*" rel="noreferrer">https://crontab.guru/#<em>/15_7-19_</em>_<em>_</em></a></p>
35,365,545
Calculating cumulative returns with pandas dataframe
<p>I have this dataframe</p> <pre><code>Poloniex_DOGE_BTC Poloniex_XMR_BTC Daily_rets perc_ret 172 0.006085 -0.000839 0.003309 0 173 0.006229 0.002111 0.005135 0 174 0.000000 -0.001651 0.004203 0 175 0.000000 0.007743 0.005313 0 176 0.000000 -0.001013 -0.003466 0 177 0.000000 -0.000550 0.000772 0 178 0.000000 -0.009864 0.001764 0 </code></pre> <p>I'm trying to make a running total of daily_rets in perc_ret </p> <p>however my code just copies the values from daily_rets</p> <pre><code>df['perc_ret'] = ( df['Daily_rets'] + df['perc_ret'].shift(1) ) Poloniex_DOGE_BTC Poloniex_XMR_BTC Daily_rets perc_ret 172 0.006085 -0.000839 0.003309 NaN 173 0.006229 0.002111 0.005135 0.005135 174 0.000000 -0.001651 0.004203 0.004203 175 0.000000 0.007743 0.005313 0.005313 176 0.000000 -0.001013 -0.003466 -0.003466 177 0.000000 -0.000550 0.000772 0.000772 178 0.000000 -0.009864 0.001764 0.001764 </code></pre>
35,365,884
3
0
null
2016-02-12 14:52:13.803 UTC
9
2022-03-29 06:39:19.793 UTC
2016-02-12 15:11:39.833 UTC
null
2,901,002
null
4,019,780
null
1
18
python|pandas|cumsum
40,271
<p>If performance is important, use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumprod.html" rel="nofollow noreferrer"><code>numpy.cumprod</code></a>:</p> <pre><code>np.cumprod(1 + df['Daily_rets'].values) - 1 </code></pre> <p><strong>Timings</strong>:</p> <pre><code>#7k rows df = pd.concat([df] * 1000, ignore_index=True) In [191]: %timeit np.cumprod(1 + df['Daily_rets'].values) - 1 41 µs ± 282 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [192]: %timeit (1 + df.Daily_rets).cumprod() - 1 554 µs ± 3.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) </code></pre>
56,637,973
How to fix selenium "DevToolsActivePort file doesn't exist" exception in Python
<p>When I use both arguments <code>--headless</code> and <code>user-data-dir</code>. Selenium raise <code>selenium.common.exceptions.WebDriverException: Message: unknown error: DevToolsActivePort file doesn't exist</code> exception. If only 1 of them is used, then everything works as needs. </p> <p>I tried to swap arguments and remove some of them. Specified the full path to chromedriver.exe. None of this helped. </p> <p><strong>chromeOptions.add_argument("--disable-dev-shm-using") DIDN'T HELP ME.</strong></p> <pre class="lang-py prettyprint-override"><code>login = "test" chromeOptions = webdriver.ChromeOptions() chromeOptions.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2}) chromeOptions.add_argument("--no-sandbox") chromeOptions.add_argument("--disable-setuid-sandbox") chromeOptions.add_argument("--disable-dev-shm-using") chromeOptions.add_argument("--disable-extensions") chromeOptions.add_argument("--disable-gpu") chromeOptions.add_argument("start-maximized") chromeOptions.add_argument("disable-infobars") chromeOptions.add_argument("--headless") chromeOptions.add_argument(r"user-data-dir=.\cookies\\" + login) b = webdriver.Chrome(chrome_options=chromeOptions) b.get("https://google.com/") b.quit() </code></pre>
56,638,103
1
0
null
2019-06-17 19:47:18.51 UTC
13
2021-02-04 10:30:57.15 UTC
2019-06-26 11:13:40.16 UTC
null
8,224,362
null
8,224,362
null
1
31
python|selenium|selenium-chromedriver
64,634
<p>I solve it by adding an argument <code>--remote-debugging-port=&lt;port&gt;</code></p> <pre class="lang-py prettyprint-override"><code>chromeOptions = webdriver.ChromeOptions() chromeOptions.add_experimental_option(&quot;prefs&quot;, {&quot;profile.managed_default_content_settings.images&quot;: 2}) chromeOptions.add_argument(&quot;--no-sandbox&quot;) chromeOptions.add_argument(&quot;--disable-setuid-sandbox&quot;) chromeOptions.add_argument(&quot;--remote-debugging-port=9222&quot;) # this chromeOptions.add_argument(&quot;--disable-dev-shm-using&quot;) chromeOptions.add_argument(&quot;--disable-extensions&quot;) chromeOptions.add_argument(&quot;--disable-gpu&quot;) chromeOptions.add_argument(&quot;start-maximized&quot;) chromeOptions.add_argument(&quot;disable-infobars&quot;) chromeOptions.add_argument(r&quot;user-data-dir=.\cookies\\test&quot;) b = webdriver.Chrome(chrome_options=chromeOptions) b.get(&quot;https://google.com/&quot;) b.quit() </code></pre>
42,886,931
TypeError: next is not a function
<p>I'm running a Node.js-server and trying to test this Rest API that I made with Express. It's linked up to MongoDB using Mongoose.</p> <p>I'm testing the individual routes using Postman and I get an error when trying to send a PUT-request to this route:</p> <pre><code>// PUT /meetings/:id // Route for editing a specific meeting router.put("/:id", function(req, res, next) { req.meeting.update(req.date, function(err, result) { if(err) return next(err); res.json(result); }); }); </code></pre> <p>The error retrieved is this:</p> <pre><code>events.js:141 throw er; // Unhandled 'error' event ^ TypeError: next is not a function </code></pre> <p>I cannot figure out where exactly this is coming from. I'm using the router.params-method to specify how the :id-parameter should be handled like this:</p> <pre><code>router.param("id", function(req, res, id, next) { Meeting.findById(id, function(err, meeting) { if (err) return next(err); if (!meeting) { err = new Error("Meeting not found"); err.status = 404; return next(err); } req.meeting = meeting; return next(); }); }); </code></pre>
42,886,968
2
0
null
2017-03-19 13:05:24.433 UTC
null
2017-03-19 13:21:59.72 UTC
null
null
null
null
4,612,744
null
1
7
javascript|node.js|mongodb|express|mongoose
38,581
<p>So I figured it out. It was a much smaller error than I thought. I had the parameters to the callback-function in my router.param-method in the wrong sequence. The next-keyword should be where id was. This code fixed the problem:</p> <pre><code>router.param("id", function(req, res, next, id) { Meeting.findById(id, function(err, meeting) { if (err) return next(err); if (!meeting) { err = new Error("Meeting not found"); err.status = 404; return next(err); } req.meeting = meeting; return next(); }); }); </code></pre>
49,582,971
Encoded password does not look like BCrypt
<p>I am using Spring Boot, Spring Security, OAuth2 and JWT to authenticate my application, but I keep getting this nasty error and I don't have any idea what is wrong. My <code>CustomDetailsService</code> class:</p> <pre><code>@Service public class CustomDetailsService implements UserDetailsService { private static final Logger logger = LoggerFactory.getLogger(CustomDetailsService.class); @Autowired private UserBO userBo; @Autowired private RoleBO roleBo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { AppUsers appUsers = null; try { appUsers = this.userBo.loadUserByUsername(username); System.out.println("========|||=========== "+appUsers.getUsername()); }catch(IndexOutOfBoundsException e){ throw new UsernameNotFoundException("Wrong username"); }catch(DataAccessException e){ e.printStackTrace(); throw new UsernameNotFoundException("Database Error"); }catch(Exception e){ e.printStackTrace(); throw new UsernameNotFoundException("Unknown Error"); } if(appUsers == null){ throw new UsernameNotFoundException("Bad credentials"); } logger.info("Username: "+appUsers.getUsername()); return buildUserFromUserEntity(appUsers); } private User buildUserFromUserEntity(AppUsers authUsers) { Set&lt;UserRole&gt; userRoles = authUsers.getUserRoles(); boolean enabled = true; boolean accountNotExpired = true; boolean credentialsNotExpired = true; boolean accountNotLocked = true; if (authUsers.getAccountIsActive()) { try { if(authUsers.getAccountExpired()){ accountNotExpired = true; } else if (authUsers.getAccountIsLocked()) { accountNotLocked = true; } else { if (containsRole((userRoles), roleBo.findRoleByName("FLEX_ADMIN"))){ accountNotLocked = false; } } }catch(Exception e){ enabled = false; e.printStackTrace(); } }else { accountNotExpired = false; } // convert model user to spring security user String username = authUsers.getUsername(); String password = authUsers.getPassword(); List&lt;GrantedAuthority&gt; authorities = buildUserAuthority(userRoles); User springUser = new User(username, password,enabled, accountNotExpired, credentialsNotExpired, accountNotLocked, authorities); return springUser; } } </code></pre> <p><code>OAuth2Config</code>:</p> <pre><code>@Configuration public class OAuth2Config extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Bean public JwtAccessTokenConverter tokenConverter() { JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter(); tokenConverter.setSigningKey(PRIVATE_KEY); tokenConverter.setVerifierKey(PUBLIC_KEY); return tokenConverter; } @Bean public JwtTokenStore tokenStore() { return new JwtTokenStore(tokenConverter()); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpointsConfigurer) throws Exception { endpointsConfigurer.authenticationManager(authenticationManager) .tokenStore(tokenStore()) .accessTokenConverter(tokenConverter()); } @Override public void configure(AuthorizationServerSecurityConfigurer securityConfigurer) throws Exception { securityConfigurer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient(CLIENT_ID) .secret(CLIENT_SECRET) .scopes("read","write") .authorizedGrantTypes("password","refresh_token") .accessTokenValiditySeconds(20000) .refreshTokenValiditySeconds(20000); } } </code></pre> <p><code>SecurityConfig</code>:</p> <pre><code>@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired CustomDetailsService customDetailsService; @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } @Override @Autowired protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(customDetailsService).passwordEncoder(encoder()); System.out.println("Done...finito"); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.authorizeRequests() .anyRequest() .authenticated() .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.NEVER); } @Override @Bean public AuthenticationManager authenticationManager() throws Exception { return super.authenticationManagerBean(); } } </code></pre> <p>No error message except:</p> <pre><code>Hibernate: select appusers0_.id as id1_2_, appusers0_.account_expired as account_2_2_, appusers0_.account_is_active as account_3_2_, appusers0_.account_is_locked as account_4_2_, appusers0_.bank_acct as bank_acc5_2_, appusers0_.branch_id as branch_i6_2_, appusers0_.bvn as bvn7_2_, appusers0_.create_date as create_d8_2_, appusers0_.created_by as created_9_2_, appusers0_.email as email10_2_, appusers0_.email_verified_code as email_v11_2_, appusers0_.gender as gender12_2_, appusers0_.gravatar_url as gravata13_2_, appusers0_.is_deleted as is_dele14_2_, appusers0_.lastname as lastnam15_2_, appusers0_.middlename as middlen16_2_, appusers0_.modified_by as modifie17_2_, appusers0_.modified_date as modifie18_2_, appusers0_.orgnization_id as orgniza19_2_, appusers0_.password as passwor20_2_, appusers0_.phone_no as phone_n21_2_, appusers0_.surname as surname22_2_, appusers0_.token_expired as token_e23_2_, appusers0_.username as usernam24_2_ from users appusers0_ where appusers0_.username=? Tinubu 2018-03-31 01:42:03.255 INFO 4088 --- [nio-8072-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet' 2018-03-31 01:42:03.255 INFO 4088 --- [nio-8072-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2018-03-31 01:42:03.281 INFO 4088 --- [nio-8072-exec-2] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 26 ms 2018-03-31 01:42:03.489 WARN 4088 --- [nio-8072-exec-2] o.s.s.c.bcrypt.BCryptPasswordEncoder : Encoded password does not look like BCrypt </code></pre> <p>My entity model classes are:</p> <pre><code>@Entity @Table(name="USERS") @DynamicUpdate public class AppUsers { @Id @Column(name="ID") @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(notes = "The user auto generated identity", required = true) private Long id; @Column(name="username") @ApiModelProperty(notes = "The username parameter", required = true) private String username; @Column(name="password") @ApiModelProperty(notes = "The password parameter", required = true) private String password; @JsonManagedReference @OneToMany(mappedBy="appUsers") private Set&lt;UserRole&gt; userRoles; '''''' setters and getters } </code></pre> <p><code>Role</code> entity:</p> <pre><code>@Entity @Table(name="ROLE") public class Role { @javax.persistence.Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "role_id", unique = true, nullable = false) private Long Id; @Column(name = "name") private String roleName; @JsonManagedReference @OneToMany(mappedBy="role") private Set&lt;UserRole&gt; userRoles; //getters and setters } </code></pre> <p><code>UserRole</code> entity:</p> <pre><code>@Entity @Table(name="USER_ROLE") @DynamicUpdate public class UserRole implements Serializable { private static final long serialVersionUID = 6128016096756071383L; @Id @Column(name="ID") @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(notes = "The userrole auto generated identity", required = true) private long id; @JsonBackReference @ManyToOne//(fetch=FetchType.LAZY) private AppUsers appUsers; @JsonBackReference @ManyToOne//(fetch=FetchType.LAZY) private Role role; // getters and setters } </code></pre> <p>My password in the database is properly encrypted Spring security BCrypt and it datatype is varchar(255) which is larger than 60.</p>
52,420,168
26
1
null
2018-03-31 00:11:54.12 UTC
8
2022-06-19 09:59:23.68 UTC
2019-04-27 15:40:09.867 UTC
null
1,797,006
null
4,137,085
null
1
44
java|spring|spring-boot|spring-data-jpa
87,188
<p>BCryptPasswordEncoder shows this warning when it fails to match a raw password with an encoded password. </p> <p>The hashed password might be “$2b” or “$2y” now. </p> <p>And there is a bug in Spring Security that has a regex always looking for “$2a”. Put a debug point at the <code>matches()</code> function in the <code>BCryptPasswordEncoder.class</code>.</p>
38,511,743
"Adding missing grouping variables" message in dplyr in R
<p>I have a portion of my script that was running fine before, but recently has been producing an odd statement after which many of my other functions do not work properly. I am trying to select the 8th and 23rd positions in a ranked list of values for each site to find the 25th and 75th percentile values for each day in a year for each site for 30 years. My approach was as follows (adapted for the four line dataset - slice(3) would be slice(23) for my full 30 year dataset usually): </p> <pre><code>library(“dplyr”) mydata structure(list(station_number = structure(c(1L, 1L, 1L, 1L), .Label = "01AD002", class = "factor"), year = 1981:1984, month = c(1L, 1L, 1L, 1L), day = c(1L, 1L, 1L, 1L), value = c(113, 8.329999924, 15.60000038, 149 )), .Names = c("station_number", "year", "month", "day", "value"), class = "data.frame", row.names = c(NA, -4L)) value &lt;- mydata$value qu25 &lt;- mydata %&gt;% group_by(month, day, station_number) %&gt;% arrange(desc(value)) %&gt;% slice(3) %&gt;% select(value) </code></pre> <p>Before, I would be left with a table that had one value per site to describe the 25th percentile (since the arrange function seems to order them highest to lowest). However, now when I run these lines, I get a message: </p> <pre><code>Adding missing grouping variables: `month`, `day`, `station_number` </code></pre> <p>This message doesn’t make sense to me, as the grouping variables are clearly present in my table. Also, again, this was working fine until recently. I have tried: </p> <ul> <li>detatch(“plyr”) – since I have it loaded before dplyr</li> <li>dplyr:: group_by – placing this directly in the group_by line</li> <li>uninstalling and re-intstalling dplyr, although this was for another issue I was having</li> </ul> <p>Any idea why I might be receiving this message and why it may have stopped working? </p> <p>Thanks for any help. </p> <p>Update: Added dput example with one site, but values for January 1st for multiple years. The hope would be that the positional value is returned once grouped, for instance slice(3) would hopefully return the 15.6 value for this smaller subset. </p>
38,512,421
4
9
null
2016-07-21 18:25:23.763 UTC
9
2022-05-14 16:01:44.303 UTC
2016-07-21 18:55:07.213 UTC
null
6,495,544
null
6,495,544
null
1
54
r|dplyr
54,343
<p>For consistency sake the grouping variables should be always present when defined earlier and thus are added when <code>select(value)</code> is executed. <code>ungroup</code> should resolve it:</p> <pre><code>qu25 &lt;- mydata %&gt;% group_by(month, day, station_number) %&gt;% arrange(desc(value)) %&gt;% slice(2) %&gt;% ungroup() %&gt;% select(value) </code></pre> <p>The requested result is without warnings:</p> <pre><code>&gt; mydata %&gt;% + group_by(month, day, station_number) %&gt;% + arrange(desc(value)) %&gt;% + slice(2) %&gt;% + ungroup() %&gt;% + select(value) # A tibble: 1 x 1 value &lt;dbl&gt; 1 113 </code></pre>
7,343,915
SubView slide in animation, iphone
<p>I have a UIview Containing two UIButtons. </p> <pre><code>-(void)ViewDidLoad { geopointView = [[UIView alloc] initWithFrame:CGRectMake(0, 350, 120, 80)]; geopointView.backgroundColor = [UIColor greenColor]; UIButton *showGeoPointButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; showGeoPointButton.frame = CGRectMake(0, 0, 120, 40); showGeoPointButton.titleLabel.font = [UIFont systemFontOfSize:13.0]; [showGeoPointButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [showGeoPointButton addTarget:self action:@selector(showPlaces:) forControlEvents:UIControlEventTouchUpInside]; UIButton *SaveButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain] SaveButton.frame = CGRectMake(0, 40, 120, 40); SaveButton.titleLabel.font = [UIFont systemFontOfSize: 15.0]; [SaveButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [SaveButton addTarget:self action:@selector(savePlacePopUp) forControlEvents:UIControlEventTouchUpInside]; [geopointView addSubview:showGeoPointButton]; [geopointView addSubview:SaveButton]; } </code></pre> <p>I want to animate slide in of UIview when following method is called. </p> <pre><code>-(void) showAnimation </code></pre> <p>I tried to do it by following way but I can see no animation. How can I do it?</p> <pre><code>-(void) showAnimation{ [UIView animateWithDuration:10.0 animations:^{ [self.view addSubview:geopointView]; }]; } </code></pre> <p>Thannks for any help in advance.</p>
7,343,940
1
0
null
2011-09-08 06:20:40.223 UTC
13
2013-10-17 23:37:25.473 UTC
2013-05-13 16:31:34.937 UTC
null
915,497
null
915,497
null
1
15
iphone|ios|uiviewanimation
31,128
<p>You need to add the subview with a frame value that is where you want the animation to begin from (off-screen?) then change the frame value inside your animation block. The frame will change over the duration, causing the appearance of movement. The view must already be a subview - I don't believe adding a subview is something you can animate, it makes no sense.</p> <pre><code>-(void)showAnimation { [self.view addSubview:geopointView] geopointView.frame = // somewhere offscreen, in the direction you want it to appear from [UIView animateWithDuration:10.0 animations:^{ geopointView.frame = // its final location }]; } </code></pre>
22,756,092
What does it mean by cold cache and warm cache concept?
<p>I read a paper and it used terms <strong>cold cache</strong> and <strong>warm cache</strong>. I googled about this terms but I didn't find something useful (only a thread <a href="https://web.archive.org/web/20150420002300/http://help.lockergnome.com/linux/Cold-cache-warm-cache--ftopict414393.html" rel="noreferrer">here</a>). </p> <p>What do these terms mean? </p>
22,756,972
5
0
null
2014-03-31 07:45:45.377 UTC
18
2019-12-30 06:22:12.217 UTC
2019-01-17 15:35:56.61 UTC
null
1,462,770
null
1,462,770
null
1
69
caching|linux-kernel|filesystems|ext2
44,264
<p><strong>TL;DR</strong> There is an analogy with a cold engine and warm engine of the car. Cold cache - doesn't have any values and can't give you any speedup because, well, it's empty. Warm cache has some values and can give you that speedup.</p> <p>A cache is a structure that holds some values (inodes, memory pages, disk blocks, etc.) for faster lookup. </p> <p>Cache works by storing some kind of short references in a fast search data structure (hash table, B+ Tree) or faster access media (RAM memory vs HDD, SSD vs HDD).</p> <p>To be able to do this fast search you need your cache to hold values. Let's look at an example.</p> <p>Say, you have a Linux system with some filesystem. To access files in the filesystem you need to know where your file starts at the disk. This information stored in the inode. For simplicity, we say that the inode table is stored somewhere on disk (so-called "superblock" part).</p> <p>Now imagine, that you need to read file /etc/fstab. To do this you need to read inode table from disk (10 ms) then parse it and get start block of the file and then read the file itself(10ms). Total ~20ms</p> <p>This is way too many operations. So you are adding a cache in form of a hash table in RAM. RAM access is 10ns - that's 1000(!) times faster. Each row in that hash table holds 2 values.</p> <pre><code>(inode number or filename) : (starting disk block) </code></pre> <p>But the problem is that at the start your cache is empty - such cache is called <strong>cold cache</strong>. To exploit the benefits of your cache you need to fill it with some values. How does it happen? When you're looking for some file you look in your inode cache. If you don't find inode in the cache (<em>cache miss</em>) you're saying 'Okay' and do full read cycle with inode table reading, parsing it and reading file itself. But after parsing part you're saving inode number and parsed starting disk block in your cache. And that's going on and on - you try to read another file, you look in cache, you get cache miss (your cache is cold), you read from disk, you add a row in the cache.</p> <p>So cold cache doesn't give you any speedup because you are still reading from disk. In some cases, the cold cache makes your system slower because you're doing extra work (extra step of looking up in a table) to warm up your cache.</p> <p>After some time you'll have some values in your cache, and by some time you try to read the file, you look up in cache and BAM! you have found inode (<em>cache hit</em>)! Now you have starting disk block, so you skip reading superblock and start reading the file itself! You have just saved 10ms!</p> <p>That cache is called <strong>warm cache</strong> - cache with some values that give you cache hits.</p>
39,171,678
"instanceof" equivalent in Golang
<p>I have these structs:</p> <pre><code>type Event interface { Accept(EventVisitor) } type Like struct { } func (l *Like) Accept(visitor EventVisitor) { visitor.visitLike(l) } </code></pre> <p>How can I test that <code>event</code> is a <code>Like</code> instance?</p> <pre><code>func TestEventCreation(t *testing.T) { event, err := New(0) if err != nil { t.Error(err) } if reflect.TypeOf(event) != Like { t.Error(&quot;Assertion error&quot;) } } </code></pre> <p>I get:</p> <blockquote> <p>Type Like is not an expression event Event</p> </blockquote>
39,171,734
4
0
null
2016-08-26 17:24:03.817 UTC
5
2022-05-11 07:54:41.617 UTC
2022-02-19 15:50:51.05 UTC
null
6,367,716
null
3,026,283
null
1
37
go
26,280
<p>You could just do a type assertion and see if it fails:</p> <pre><code>event, err := New(0) if err != nil { t.Error(err) } _, ok := event.(Like) if !ok { t.Error(&quot;Assertion error&quot;) } </code></pre>
50,186,125
How do I parse a yaml string with python?
<p>I see an API and many examples on how to parse a yaml file but what about a string?</p>
50,186,126
2
4
null
2018-05-05 05:40:46.927 UTC
5
2020-01-04 05:47:50.283 UTC
null
null
null
null
718,488
null
1
43
python|python-3.x|yaml|python-2.x
43,253
<p>Here is the best way I have seen so far demonstrated with an example:</p> <pre><code>import yaml dct = yaml.safe_load(''' name: John age: 30 automobiles: - brand: Honda type: Odyssey year: 2018 - brand: Toyota type: Sienna year: 2015 ''') assert dct['name'] == 'John' assert dct['age'] == 30 assert len(dct["automobiles"]) == 2 assert dct["automobiles"][0]["brand"] == "Honda" assert dct["automobiles"][1]["year"] == 2015 </code></pre>
22,009,582
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
<p>While I am trying to insert a row to my table, I'm getting the following errors:</p> <pre><code>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''filename') VALUES ('san', 'ss', 1, 1, 1, 1, 2, 1, 1, 'sment', 'notes','sant' at line 1 </code></pre> <p>please help me out.</p> <pre><code>mysql&gt; desc risks; +-----------------+--------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------+--------------+------+-----+---------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | status | varchar(20) | NO | | NULL | | | subject | varchar(100) | NO | | NULL | | | reference_id | varchar(20) | NO | | | | | location | int(11) | NO | | NULL | | | category | int(11) | NO | | NULL | | | team | int(11) | NO | | NULL | | | technology | int(11) | NO | | NULL | | | owner | int(11) | NO | | NULL | | | manager | int(11) | NO | | NULL | | | assessment | longtext | NO | | NULL | | | notes | longtext | NO | | NULL | | | submission_date | timestamp | NO | | CURRENT_TIMESTAMP | | | last_update | timestamp | NO | | 0000-00-00 00:00:00 | | | review_date | timestamp | NO | | 0000-00-00 00:00:00 | | | mitigation_id | int(11) | NO | | NULL | | | mgmt_review | int(11) | NO | | NULL | | | project_id | int(11) | NO | | 0 | | | close_id | int(11) | NO | | NULL | | | submitted_by | int(11) | NO | | 1 | | | filename | varchar(30) | NO | | NULL | | +-----------------+--------------+------+-----+---------------------+----------------+ 21 rows in set (0.00 sec) **mysql&gt; INSERT INTO risks (`status`, `subject`, `reference_id`, `location`, `category`, `team`, `technology`, `owner`, `manager`, `assessment`, `notes`,'filename') VALUES ('san', 'ss', 1, 1, 1, 1, 2, 1, 1, 'sment', 'notes','santu');** ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''filename') VALUES ('san', 'ss', 1, 1, 1, 1, 2, 1, 1, 'sment', 'notes','sant' at line 1 </code></pre>
22,009,889
12
0
null
2014-02-25 09:18:30.813 UTC
9
2022-05-09 06:14:32.627 UTC
2014-02-25 09:23:21.77 UTC
null
2,134,785
null
2,106,393
null
1
38
mysql
327,971
<p>There are two different types of quotation marks in MySQL. You need to use ` for column names and ' for strings. Since you have used ' for the filename column the query parser got confused. Either remove the quotation marks around all column names, or change 'filename' to `filename`. Then it should work.</p>
2,679,022
Sort a matrix with another matrix
<p>Suppose I have a matrix <code>A</code> and I sort the rows of this matrix. How do I replicate the same ordering on a matrix <code>B</code> (same size of course)?</p> <p>E.g.</p> <pre><code>A = rand(3,4); [val ind] = sort(A,2); B = rand(3,4); %// Reorder the elements of B according to the reordering of A </code></pre> <p>This is the best I've come up with</p> <pre><code>m = size(A,1); B = B(bsxfun(@plus,(ind-1)*m,(1:m)')); </code></pre> <p>Out of curiosity, any alternatives?</p> <p><strong>Update:</strong> <a href="https://stackoverflow.com/questions/2679022/sort-a-matrix-with-another-matrix/2679517#2679517">Jonas' excellent solution</a> profiled on 2008a (XP):</p> <h3>n = n</h3> <pre><code>0.048524 1.4632 1.4791 1.195 1.0662 1.108 1.0082 0.96335 0.93155 0.90532 0.88976 </code></pre> <h3>n = 2m</h3> <pre><code>0.63202 1.3029 1.1112 1.0501 0.94703 0.92847 0.90411 0.8849 0.8667 0.92098 0.85569 </code></pre> <p>It just goes to show that loops aren't anathema to MATLAB programmers anymore thanks to <a href="http://www.mathworks.com/company/newsletters/news_notes/may03/profiler.html" rel="noreferrer">JITA</a> (perhaps).</p>
2,679,517
3
1
null
2010-04-20 22:04:34.527 UTC
9
2016-06-27 07:40:02.733 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
71,131
null
1
22
matlab|bsxfun
11,273
<p>A somewhat clearer way to do this is to use a loop</p> <pre><code>A = rand(3,4); B = rand(3,4); [sortedA,ind] = sort(A,2); for r = 1:size(A,1) B(r,:) = B(r,ind(r,:)); end </code></pre> <p>Interestingly, the loop version is faster for small (&lt;12 rows) and large (>~700 rows) square arrays (r2010a, OS X). The more columns there are relative to rows, the better the loop performs.</p> <p>Here's the code I quickly hacked up for testing:</p> <pre><code>siz = 10:100:1010; tt = zeros(100,2,length(siz)); for s = siz for k = 1:100 A = rand(s,1*s); B = rand(s,1*s); [sortedA,ind] = sort(A,2); tic; for r = 1:size(A,1) B(r,:) = B(r,ind(r,:)); end,tt(k,1,s==siz) = toc; tic; m = size(A,1); B = B(bsxfun(@plus,(ind-1)*m,(1:m).')); tt(k,2,s==siz) = toc; end end m = squeeze(mean(tt,1)); m(1,:)./m(2,:) </code></pre> <p>For square arrays</p> <pre><code>ans = 0.7149 2.1508 1.2203 1.4684 1.2339 1.1855 1.0212 1.0201 0.8770 0.8584 0.8405 </code></pre> <p>For twice as many columns as there are rows (same number of rows)</p> <pre><code>ans = 0.8431 1.2874 1.3550 1.1311 0.9979 0.9921 0.8263 0.7697 0.6856 0.7004 0.7314 </code></pre>
2,529,770
How to use libraries compiled with MingW in MSVC?
<p>I have compiled several libraries with MingW/MSYS... the generated static libraries are always .a files. When I try to link the library with a MSVC project, Visual Studio throws 'unresolved external symbols' ... It means that the .a static library is incompatible with MS C++ Linker. I presume it has to be converted to a MSVC compatible .lib file.</p> <p>Either .a and .lib are just AR archives of .o or .obj files, so is there any way how to use MingW compiled libs in a MSVC project? Or do I have to compile/link everything just in one compiler/linker - MSVC only/MingW only? The MingW compiler is said to be compatible with MSVC.</p> <p>I read a few threads about this topic, but they mostly say that renaming the file to .lib should do the work, but it unfortunately doesn't work for me.</p> <p>The libraries Im trying to link are written in C.</p> <p>MSVC Linker throws errors like: </p> <pre><code>error LNK2019: unresolved external symbol "int __cdecl openssl_call(struct ssl_State *,int,int,int)" (?openssl_call@@YAHPAUssl_State@@HHH@Z) referenced in function _main MyAPP.obj </code></pre> <p>... and 4 more same errors referring to other functions called from my app.</p> <p>Thanks for any advice.</p>
2,529,997
4
3
null
2010-03-27 15:11:58.56 UTC
14
2020-07-14 13:38:46.62 UTC
2010-03-27 16:31:14.343 UTC
anon
null
null
214,914
null
1
22
c++|mingw|visual-c++|compatibility|static-libraries
26,636
<p>Based on this error you put in a comment:</p> <blockquote> <p>error LNK2019: unresolved external symbol "int __cdecl openssl_call(struct ssl_State *,int,int,int)" (?openssl_call@@YAHPAUssl_State@@HHH@Z) referenced in function _main MyAPP.obj all other 4 errors are same only with other functions names</p> </blockquote> <p>Try putting <code>extern "C"</code> around your include files for openssl. For example:</p> <pre><code>extern "C" { include "openssl.h" } </code></pre> <p>using <a href="http://msdn.microsoft.com/en-us/library/0603949d%28VS.80%29.aspx" rel="noreferrer">extern "C"</a> will instruct the compiler that the functions are using C linkage, not C++, which will stop it from performing <a href="http://blogs.msdn.com/vijay/archive/2009/10/02/what-is-name-decoration-or-name-mangling.aspx" rel="noreferrer">name mangling</a> on the functions. So it will look for the function openssl_call in the library rather than ?openssl_call@@YAHPAUssl_State@@HHH@.</p>
2,941,681
How to make "int" parse blank strings?
<p>I have a parsing system for fixed-length text records based on a layout table:</p> <pre><code>parse_table = [\ ('name', type, length), .... ('numeric_field', int, 10), # int example ('textc_field', str, 100), # string example ... ] </code></pre> <p>The idea is that given a table for a message type, I just go through the string, and reconstruct a dictionary out of it, according to entries in the table.</p> <p>Now, I can handle strings and proper integers, but <code>int()</code> will not parse all-spaces fields (for a good reason, of course).</p> <p>I wanted to handle it by defining a subclass of <code>int</code> that handles blank strings. This way I could go and change the type of appropriate table entries without introducing additional kludges in the parsing code (like filters), and it would "just work".</p> <p>But I can't figure out how to override the constructor of a build-in type in a sub-type, as defining constructor in the subclass does not seem to help. I feel I'm missing something fundamental here about how Python built-in types work.</p> <p>How should I approach this? I'm also open to alternatives that don't add too much complexity.</p>
2,941,975
4
4
null
2010-05-31 06:10:48.737 UTC
5
2018-05-28 02:23:56.027 UTC
null
null
null
null
23,643
null
1
31
python
38,374
<p>Use a factory function instead of int or a subclass of int:</p> <pre><code>def mk_int(s): s = s.strip() return int(s) if s else 0 </code></pre>
2,950,505
untar filename.tr.gz to directory "filename"
<p>I would like to untar an archive e.g. "tar123.tar.gz" to directory /myunzip/tar123/" using a shell command.</p> <p>tar -xf tar123.tar.gz will decompress the files but in the same directory as where I'm working in. </p> <p>If the filename would be "tar233.tar.gz" I want it to be decompressed to /myunzip/tar233.tar.gz" so destination directory would be based on the filename.</p> <p>Does anyone know if the tar command can do this?</p>
2,950,578
4
0
null
2010-06-01 14:16:49.483 UTC
5
2019-04-29 09:04:42.087 UTC
null
null
null
null
229,656
null
1
37
shell|tar
39,392
<p>With Bash and GNU tar:</p> <pre><code>file=tar123.tar.gz dir=/myunzip/${file%.tar.gz} mkdir -p $dir tar -C $dir -xzf $file </code></pre>
29,331,499
When should we use .then with Protractor Promise?
<p>I've got many instability with Protractor, and I'm sure there is something I don't understand. Sometimes I need use the .then() when clicking on a button before continuing, sometimes it don't have any impact and I should not use .then() or the test failed.</p> <p>I wonder when should I use the .then() callback when testing in Protractor ? Example :</p> <pre><code>createAccountForm = $('#form-create-account'); submitButton = createAccountForm.$('button[type=submit]'); browser.wait(EC.elementToBeClickable(submitButton), 5000); submitButton.click(); // .then(function(){ &lt;-- uncomment in the .then form // find the confirmation message var message = $('.alert-success'); browser.wait(EC.visibilityOf(message), 5000); log.debug('After visibilityOf'); expect(message.isPresent()).to.be.eventually.true; // }); --&gt; uncomment when in .then form </code></pre> <p>When I use this form of test (without .then()) I see on browser that the <strong>click on the button is not done</strong>, the test continue with the following expect and then stop.</p> <p>If <strong>I use the .then() form, the click on the button is done</strong>, and the test continue without error.</p> <p>On other test, I don't need to use the then() callback when clicking on button.</p> <p>So , when should I use the .then() and when not ?</p> <p>Jean-Marc</p>
29,332,659
2
0
null
2015-03-29 16:11:52.527 UTC
12
2021-02-09 02:09:28.307 UTC
null
null
null
null
1,616,656
null
1
37
promise|protractor
34,475
<p>The answer of this question can be found in this post : <a href="http://spin.atomicobject.com/2014/12/17/asynchronous-testing-protractor-angular/">http://spin.atomicobject.com/2014/12/17/asynchronous-testing-protractor-angular/</a></p> <p>That is :</p> <ol> <li>Protractor enqueue all driver commands in the ControlFlow,</li> <li>when you need the result of a driver command you should use .then,</li> <li>when you don't need the result of a driver you can avoid .then but all following instructions must be enqueued in the ControlFlow else they will be run before commands in the queue leading to unpredictable result. So, if you want to run a non driver tests command, you should add it into the .then callback or wrap the test into a Promise and enqueue the test in the ControlFlow. See example below.</li> </ol> <p>Here is an example of my test working without .then :</p> <pre><code>log.debug('test0'); // enqueue the click submitButton.click(); var message = $('.alert-success'); // enqueue the wait for message to be visible browser.wait(EC.visibilityOf(message), 5000); log.debug('test1'); // enqueue a test expect(message.isPresent()).to.be.eventually.true; log.debug('test2'); // a function returning a promise that does an async test (check in MongoDB Collection) var testAccount = function () { var deferred = protractor.promise.defer(); // Verify that an account has been created accountColl.find({}).toArray(function (err, accs) { log.debug('test5'); expect(err).to.not.exist; log.debug('test6'); expect(accs.length).to.equal(1); return deferred.fulfill(); }); return deferred.promise; }; log.debug('test3'); // Enqueue the testAccount function browser.controlFlow().execute(testAccount); log.debug('test4'); </code></pre> <p>Output is now what we expect :</p> <pre><code>test0 test1 test2 test3 test4 test5 test6 </code></pre>
31,700,691
Convert commas decimal separators to dots within a Dataframe
<p>I am importing a CSV file like the one below, using <code>pandas.read_csv</code>:</p> <pre><code>df = pd.read_csv(Input, delimiter=";") </code></pre> <p>Example of CSV file:</p> <pre><code>10;01.02.2015 16:58;01.02.2015 16:58;-0.59;0.1;-4.39;NotApplicable;0.79;0.2 11;01.02.2015 16:58;01.02.2015 16:58;-0.57;0.2;-2.87;NotApplicable;0.79;0.21 </code></pre> <p>The problem is that when I later on in my code try to use these values I get this error: <code>TypeError: can't multiply sequence by non-int of type 'float'</code> </p> <p><strong>The error is because the number I'm trying to use is not written with a dot (<code>.</code>) as a decimal separator but a comma(<code>,</code>)</strong>. After manually changing the commas to a dots my program works.</p> <p>I can't change the format of my input, and thus have to replace the commas in my DataFrame in order for my code to work, and I want python to do this without the need of doing it manually. Do you have any suggestions?</p>
31,700,780
5
0
null
2015-07-29 12:40:31.513 UTC
12
2022-01-17 22:01:20.093 UTC
2020-03-17 11:29:35.61 UTC
null
202,229
null
5,168,024
null
1
75
python|pandas|csv|delimiter|separator
135,837
<p><code>pandas.read_csv</code> has a <code>decimal</code> parameter for this: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html">doc</a></p> <p>I.e. try with:</p> <pre><code>df = pd.read_csv(Input, delimiter=";", decimal=",") </code></pre>
28,646,572
Faster XML Jackson: Remove double quotes
<p>I have the following json:</p> <pre><code>{"test":"example"} </code></pre> <p>I use the following code from Faster XML Jackson.</p> <pre><code>JsonParser jp = factory.createParser("{\"test\":\"example\"}"); json = mapper.readTree(jp); System.out.println(json.get("test").toString()); </code></pre> <p>It outputs:</p> <pre><code>"example" </code></pre> <p>Is there a setting in Jackson to remove the double quotes?</p>
28,646,734
3
0
null
2015-02-21 13:53:42.433 UTC
4
2021-10-16 18:14:54.193 UTC
null
null
null
null
1,137,669
null
1
51
java|json|jackson
30,613
<p>Well, what you obtain when you <code>.get("test")</code> is a <code>JsonNode</code> and it happens to be a <code>TextNode</code>; when you <code>.toString()</code> it, it will return the string representation of that <code>TextNode</code>, which is why you obtain that result.</p> <p>What you want is to:</p> <pre><code>.get("test").textValue(); </code></pre> <p>which will return the actual content of the JSON String itself (with everything unescaped and so on).</p> <p>Note that this will return null if the <code>JsonNode</code> <em>is not</em> a <code>TextNode</code>.</p>
36,539,650
Display activity indicator inside UIButton
<p>I would like to change the content of a UIButton to an ActivityIndicator after it is pressed.</p> <p>I know buttons have an imageView and a titleLabel, but I don't know how to put an activity indicator in any of them.</p> <p>This is how I create activity indicators:</p> <pre><code>let aiView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) aiView.startAnimating() aiView.center = CGPointMake(0,0) aiView.hidesWhenStopped = false </code></pre>
36,539,725
11
0
null
2016-04-11 04:02:07.693 UTC
12
2021-07-09 07:22:35.65 UTC
2016-04-11 06:20:19.62 UTC
null
2,227,743
null
3,808,402
null
1
32
ios|swift|uibutton
27,586
<pre><code>import UIKit class LoadingButton: UIButton { private var originalButtonText: String? var activityIndicator: UIActivityIndicatorView! func showLoading() { originalButtonText = self.titleLabel?.text self.setTitle(&quot;&quot;, for: .normal) if (activityIndicator == nil) { activityIndicator = createActivityIndicator() } showSpinning() } func hideLoading() { self.setTitle(originalButtonText, for: .normal) activityIndicator.stopAnimating() } private func createActivityIndicator() -&gt; UIActivityIndicatorView { let activityIndicator = UIActivityIndicatorView() activityIndicator.hidesWhenStopped = true activityIndicator.color = .lightGray return activityIndicator } private func showSpinning() { activityIndicator.translatesAutoresizingMaskIntoConstraints = false self.addSubview(activityIndicator) centerActivityIndicatorInButton() activityIndicator.startAnimating() } private func centerActivityIndicatorInButton() { let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: activityIndicator, attribute: .centerX, multiplier: 1, constant: 0) self.addConstraint(xCenterConstraint) let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: activityIndicator, attribute: .centerY, multiplier: 1, constant: 0) self.addConstraint(yCenterConstraint) } } </code></pre>
49,313,485
How to reset Visual Studio Code key bindings?
<p>I have been experimenting with my vs-code key bindings.</p> <p>I would like to reset the key-bindings to the original settings.</p> <p>How do I do that?</p> <p>I am on Linux Mint 18.</p> <p>I tried removing all the records from the keybindings.json </p>
49,313,555
13
0
null
2018-03-16 04:58:23.683 UTC
8
2022-08-19 00:38:11.337 UTC
2019-04-23 17:43:06.47 UTC
null
229,044
null
317,027
null
1
70
visual-studio-code|vscode-settings
82,833
<p>Try this documentation page about key binding in VSCode: <a href="https://code.visualstudio.com/docs/getstarted/keybindings" rel="nofollow noreferrer">https://code.visualstudio.com/docs/getstarted/keybindings</a></p> <p>Open a directory that contains user settings (<a href="https://code.visualstudio.com/docs/getstarted/settings" rel="nofollow noreferrer">https://code.visualstudio.com/docs/getstarted/settings</a>) and try to remove user key bindings file.</p>
778,085
How to name a thread in Linux?
<p>I have a multithreaded Linux application written in C/C++. I have <a href="https://stackoverflow.com/questions/149932/naming-conventions-for-threads">chosen names for my threads</a>. To aid debugging, I would like these names to be visible in GDB, &quot;top&quot;, etc. Is this possible, and if so how?</p> <p>(There are plenty of <a href="https://stackoverflow.com/questions/763041/thread-names-when-do-you-need-to-know-them">reasons to know the thread name</a>. Right now I want to know which thread is taking up 50% CPU (as reported by 'top'). And when debugging I often need to switch to a different thread - currently I have to do &quot;<code>thread apply all bt</code>&quot; then look through pages of backtrace output to find the right thread).</p> <p>The <a href="https://web.archive.org/web/20100322223513/http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.80).aspx" rel="nofollow noreferrer">Windows solution is here</a>; what's the Linux one?</p>
778,124
2
2
null
2009-04-22 16:21:02.463 UTC
24
2020-10-15 15:59:35.723 UTC
2020-10-15 15:59:35.723 UTC
null
420,385
null
37,386
null
1
43
c++|c|linux|multithreading
28,584
<p>Posix Threads?</p> <p>This evidently won't compile, but it will give you an idea of where to go hunting. I'm not even sure its the right <code>PR_</code> command, but i think it is. It's been a while...</p> <pre><code> #include &lt;sys/prctl.h&gt; prctl(PR_SET_NAME,"&lt;null&gt; terminated string",0,0,0) </code></pre>
2,361,499
How to always remove WWW from a url with mod_rewrite?
<p>I'm using the following to try and remove WWW from the url:</p> <pre><code>RewriteCond %{HTTP_HOST} ^example.com$ [NC] RewriteRule (.*) http://example.com$1 [R=301] </code></pre> <p>But for some reason it doesn't work. Any suggestions?</p>
2,361,618
5
0
null
2010-03-02 07:28:26.88 UTC
11
2014-11-20 16:59:22.657 UTC
null
null
null
null
82,985
null
1
20
apache|mod-rewrite
27,719
<p>Here’s a more generalized solution:</p> <pre><code>RewriteCond %{HTTP_HOST} ^www\.(.+) [NC] RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301] </code></pre>
2,968,408
How do i program a simple IRC bot in python?
<p>I need help writing a basic IRC bot that just connects to a channel.. is anyone able to explain me this? I have managed to get it to connect to the IRC server but i am unable to join a channel and log on. The code i have thus far is:</p> <pre><code>import sockethost = 'irc.freenode.org' port = 6667 join_sock = socket.socket() join_sock.connect((host, port)) &lt;code here&gt; </code></pre> <p>Any help would be greatly appreciated.</p>
2,968,416
5
3
null
2010-06-03 17:39:08.43 UTC
20
2017-03-05 11:11:25.507 UTC
null
null
null
null
357,766
null
1
22
python|sockets|irc|connect|bots
70,977
<p>It'd probably be easiest to base it on twisted's implementation of the IRC protocol. Take a look at : <a href="http://github.com/brosner/bosnobot" rel="noreferrer">http://github.com/brosner/bosnobot</a> for inspiration.</p>
2,464,959
What's the u prefix in a Python string?
<p>Like in:</p> <pre><code>u'Hello' </code></pre> <p>My guess is that it indicates &quot;Unicode&quot;, is that correct?</p> <p>If so, since when has it been available?</p>
2,464,968
5
0
null
2010-03-17 18:43:20.663 UTC
48
2021-10-19 16:51:30.45 UTC
2021-10-19 16:51:30.45 UTC
null
20,654
null
20,654
null
1
305
python|syntax
285,475
<p>You're right, see <em><a href="http://docs.python.org/2/tutorial/introduction.html#unicode-strings" rel="noreferrer">3.1.3. Unicode Strings</a></em>.</p> <p>It's been the syntax since Python 2.0. </p> <p>Python 3 made them redundant, as the default string type is Unicode. Versions 3.0 through 3.2 removed them, but they were <a href="https://www.python.org/dev/peps/pep-0414/" rel="noreferrer">re-added in 3.3+</a> for compatibility with Python 2 to aide the 2 to 3 transition.</p>
2,978,405
Writing an app to stream video to iPhone
<p>I'm interested in creating an iPhone app that can stream video from a central server, YouTube style. I was wondering if anyone has ever tried to do this before, what is the path of least resistant, existing APIs, etc? I really know nothing about how this is generally done. Would I be working with sockets? Just looking for some direction here. Thanks!</p>
3,222,822
6
0
null
2010-06-04 23:30:56.513 UTC
21
2018-03-06 06:44:26.897 UTC
null
null
null
null
137,060
null
1
23
iphone|objective-c|video|video-streaming
28,587
<p>If you have the streaming server up and ready, it is quite easy to implement a video controller that pops up youtube-style.</p> <pre><code>NSString *videoURLString = @"http://path-to-iphone-compliant-video-stream"; NSURL *videoURL = [NSURL URLWithString:videoURLString]; MPMoviePlayerController moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL]; [moviePlayer prepareToPlay]; [moviePlayer play]; [self.view addSubview:moviePlayer.view]; </code></pre> <p>You need to handle the controller that display the video player's view (which is <code>self</code> in this case).</p> <p>In iOS 3.2+ MPMoviePlayerViewController make it even easier:</p> <pre><code>NSString *videoURLString = @"http://path-to-iphone-compliant-video-stream"; NSURL *videoURL = [NSURL URLWithString:videoURLString]; MPMoviePlayerViewController *moviePlayerView = [[[MPMoviePlayerViewController alloc] initWithContentURL:videoURL] autorelease]; [self presentMoviePlayerViewControllerAnimated:moviePlayerView]; </code></pre> <p><code>presentMoviePlayerViewControllerAnimated</code> is a MediaPlayer's additional method to <code>FWViewController</code> that you will find in iOS 3.2+ and it takes care of creating a view controller and pushing it on the stack, animating it with a slide-from-bottom animation, as in youtube.app.</p>
2,954,911
How to detect tab key pressing in C#?
<p>I want to detect when tab key is pressed in a textBox and focus the next textbox in the panel.</p> <p>I have tried out keyPressed method and keyDown method. But when I run the program and debug those methods are not calling when the tab key is pressed. Here is my code.</p> <pre><code>private void textBoxName_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Tab) { textBoxUsername.Focus(); } } private void textBoxName_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar==(char)Keys.Tab) { textBoxUsername.Focus(); } } </code></pre> <p>Please correct me.Thank you.</p>
3,933,222
7
2
null
2010-06-02 03:58:20.18 UTC
null
2015-06-02 02:36:02.76 UTC
2012-04-30 08:21:07.493 UTC
null
1,016,716
null
342,325
null
1
4
c#|tabs|key|keypress
40,609
<p>go to the properties of text box and assign correct order of tabindex</p>
2,958,813
How to replicate PS multiply layer mode
<p>Does anybody know of a good way to replicate Photoshop's multiply layer mode using either an image or CSS?</p> <p>I'm working on a project that has thumbnails that get a color overlay when you hover over them, but the designer used a layer set to multiply and I can't figure out how to produce it on the web.</p> <p>The best thing I've come up with is either using rgba or a transparent png, but even then it doesn't look right.</p>
21,011,502
8
10
null
2010-06-02 14:48:25.267 UTC
11
2015-06-30 10:45:06.77 UTC
null
null
null
null
1,824,709
null
1
51
css|image|overlay|photoshop|rgba
51,333
<p>There are new CSS properties being introduced to do just this thing, they are <code>blend-mode</code> and <code>background-blend-mode</code>.</p> <p>Currently, you won't be able to use them in any sort of production environment, as they are very very new, and currently only supported by Chrome Canary (experimental web browser) &amp; Webkit Nightly.</p> <p>These properties are set up to work nearly exactly the same as photoshop's blending modes, and allow for various different modes to be set as values for these properties such as <code>overlay</code>, <code>screen</code>, <code>lighten</code>, <code>color-dodge</code>, and of course <code>multiply</code>.. among others.</p> <p><code>blend-mode</code> would allow images (and possibly content? I haven't heard anything to suggest that at this point though.) layered on top of each other to have this blending effect applied.</p> <p><code>background-blend-mode</code> would be quite similar, but would be intended for background images (set using <code>background</code> or <code>background-image</code>) rather than actual image elements.</p> <hr> <p><strong>EDIT:</strong> The next section is becoming a bit irrelevant as browser support is growing.. Check this chart to see which browsers have support for this: <a href="http://caniuse.com/#feat=css-backgroundblendmode" rel="noreferrer">http://caniuse.com/#feat=css-backgroundblendmode</a></p> <hr> <p>If you've got the latest version of Chrome installed on your computer, you can actually see these styles in use by enabling some flags in your browser (just throw these into your address bar:)</p> <pre><code>chrome://flags/#enable-experimental-web-platform-features chrome://flags/#enable-css-shaders * note that the flags required for this might change at any time </code></pre> <p>Enable those bad boys and then check out this fiddle: <a href="http://jsfiddle.net/cqzJ5/" rel="noreferrer">http://jsfiddle.net/cqzJ5/</a> <em>(If the styles are properly enabled in your browser, the two images should be blended to make the scene look like it is underwater)</em></p> <p>While this may not be the most legitimate answer at the current moment due to the almost entirely nonexistent support for this feature, we can hope that modern browsers will adopt these properties in the near future, giving us a really nice and easy solution to this problem.</p> <p>Some extra reading resources on blending modes and the css properties:</p> <ul> <li><a href="http://blogs.adobe.com/webplatform/2013/06/24/css-background-blend-modes-are-now-available-in-chrome-canary-and-webkit-nightly/" rel="noreferrer">http://blogs.adobe.com/webplatform/2013/06/24/css-background-blend-modes-are-now-available-in-chrome-canary-and-webkit-nightly/</a></li> <li><a href="http://demosthenes.info/blog/707/PhotoShop-In-The-Browser-Understanding-CSS-Blend-Modes" rel="noreferrer">http://demosthenes.info/blog/707/PhotoShop-In-The-Browser-Understanding-CSS-Blend-Modes</a></li> <li><a href="http://html.adobe.com/webplatform/graphics/blendmodes/" rel="noreferrer">http://html.adobe.com/webplatform/graphics/blendmodes/</a></li> </ul>
3,086,068
How do I check whether a jQuery element is in the DOM?
<p>Let's say that I define an element</p> <pre><code>$foo = $('#foo'); </code></pre> <p>and then I call</p> <pre><code>$foo.remove() </code></pre> <p>from some event. My question is, how do I check whether $foo has been removed from the DOM or not? I've found that <code>$foo.is(':hidden')</code> works, but that would of course also return true if I merely called <code>$foo.hide()</code>.</p>
3,086,084
11
0
null
2010-06-21 15:40:07.243 UTC
21
2018-05-24 07:22:45.413 UTC
null
null
null
null
66,226
null
1
156
jquery
60,073
<p>Like this:</p> <pre><code>if (!jQuery.contains(document, $foo[0])) { //Element is detached } </code></pre> <p>This will still work if one of the element's parents was removed (in which case the element itself will still have a parent).</p>
2,446,812
CSS Equivalent of the "if" statement
<p>Is there any way to use conditional statements in CSS?</p>
2,446,829
14
3
null
2010-03-15 11:48:25.86 UTC
7
2022-06-24 15:04:52.473 UTC
2015-09-24 22:37:40.133 UTC
null
1,207,687
null
479,291
null
1
45
css
192,078
<p>No. But can you give an example what you have in mind? What <em>condition</em> do you want to check?</p> <p>Maybe <a href="http://sass-lang.com/" rel="noreferrer">Sass</a> or <a href="http://compass-style.org/" rel="noreferrer">Compass</a> are interesting for you.</p> <p>Quote from Sass:</p> <blockquote> <p>Sass makes CSS fun again. Sass is CSS, plus nested rules, variables, mixins, and more, all in a concise, readable syntax.</p> </blockquote>
2,865,865
Are there equivalents to Ruby's method_missing in other languages?
<p>In Ruby, objects have a handy method called <code>method_missing</code> which allows one to handle method calls for methods that have not even been (explicitly) defined:</p> <blockquote> <p>Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values.</p> </blockquote> <pre><code>class Roman def romanToInt(str) # ... end def method_missing(methId) str = methId.id2name romanToInt(str) end end r = Roman.new r.iv #=&gt; 4 r.xxiii #=&gt; 23 r.mm #=&gt; 2000 </code></pre> <p>For example, Ruby on Rails uses this to allow calls to methods such as <code>find_by_my_column_name</code>.</p> <p>My question is, what other languages support an equivalent to <code>method_missing</code>, and how do you implement the equivalent in your code?</p>
2,866,007
15
0
2010-05-19 13:26:30.313 UTC
2010-05-19 13:26:30.313 UTC
10
2017-09-02 20:57:05.147 UTC
null
null
null
null
101,258
null
1
22
programming-languages|language-features|method-missing
3,613
<p>Some use cases of <code>method_missing</code> can be implemented in Python using <code>__getattr__</code> e.g.</p> <pre><code>class Roman(object): def roman_to_int(self, roman): # implementation here def __getattr__(self, name): return self.roman_to_int(name) </code></pre> <p>Then you can do:</p> <pre><code>&gt;&gt;&gt; r = Roman() &gt;&gt;&gt; r.iv 4 </code></pre>
2,604,435
Fatal error: Call to undefined function mcrypt_encrypt()
<p><strong>NOTE:</strong> The libraries MCrypt support depend on have not been updated in years and MCrypt should no longer be considered a viable or secure method of encrypting data. What's more, MCrypt has been deprecated in PHP 5, and removed entirely in PHP 7. If you have any code that runs MCrypt you should refactor it to use a more modern encryption library. </p> <hr> <p>Does anyone know why this error message: <code>(Call to undefined function mcrypt_encrypt() )</code> displays when I run the following code below?</p> <p>Am I missing some steps perhaps any setting in PHP I have to do before this code can work?</p> <pre class="lang-php prettyprint-override"><code>$key = 'password to (en/de)crypt'; $string = 'string to be encrypted'; $test = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))); </code></pre>
2,604,474
19
4
null
2010-04-09 00:49:39.42 UTC
12
2020-04-27 10:38:44.813 UTC
2017-08-31 07:10:07.687 UTC
null
477,127
null
52,745
null
1
69
php|mcrypt
230,537
<p>What had worked for me with PHP version 5.2.8, was to open up <code>php.ini</code> and allow the <code>php_mcrypt.dll</code> extension by removing the <code>;</code>, i.e. changing:</p> <p><code>;extension=php_mcrypt.dll</code> to <code>extension=php_mcrypt.dll</code></p>
40,622,430
`std::list<>::sort()` - why the sudden switch to top-down strategy?
<p>I remember that since the beginning of times the most popular approach to implementing <code>std::list&lt;&gt;::sort()</code> was the classic Merge Sort algorithm implemented in <a href="https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists" rel="noreferrer">bottom-up fashion</a> (see also <a href="https://stackoverflow.com/questions/6728580/what-makes-the-gcc-stdlist-sort-implementation-so-fast">What makes the gcc std::list sort implementation so fast?</a>). </p> <p>I remember seeing someone aptly refer to this strategy as "onion chaining" approach.</p> <p>At least that's the way it is in GCC's implementation of C++ standard library (see, for example, <a href="https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.6/a00925_source.html#l00355" rel="noreferrer">here</a>). And this is how it was in old Dimkumware's STL in MSVC version of standard library, as well as in all versions of MSVC all the way to VS2013. </p> <p>However, the standard library supplied with VS2015 suddenly no longer follows this sorting strategy. The library shipped with VS2015 uses a rather straightforward recursive implementation of <em>top-down</em> Merge Sort. This strikes me as strange, since top-down approach requires access to the mid-point of the list in order to split it in half. Since <code>std::list&lt;&gt;</code> does not support random access, the only way to find that mid-point is to literally iterate through half of the list. Also, at the very beginning it is necessary to know the total number of elements in the list (which was not necessarily an O(1) operation before C++11).</p> <p>Nevertheless, <code>std::list&lt;&gt;::sort()</code> in VS2015 does exactly that. Here's an excerpt from that implementation that locates the mid-point and performs recursive calls</p> <pre><code>... iterator _Mid = _STD next(_First, _Size / 2); _First = _Sort(_First, _Mid, _Pred, _Size / 2); _Mid = _Sort(_Mid, _Last, _Pred, _Size - _Size / 2); ... </code></pre> <p>As you can see, they just nonchalantly use <code>std::next</code> to walk through the first half of the list and arrive at <code>_Mid</code> iterator.</p> <p>What could be the reason behind this switch, I wonder? All I see is a seemingly obvious inefficiency of repetitive calls to <code>std::next</code> at each level of recursion. Naive logic says that this is <em>slower</em>. If they are willing to pay this kind of price, they probably expect to get something in return. What are they getting then? I don't immediately see this algorithm as having better cache behavior (compared to the original bottom-up approach). I don't immediately see it as behaving better on pre-sorted sequences.</p> <p>Granted, since C++11 <code>std::list&lt;&gt;</code> is basically required to store its element count, which makes the above slightly more efficient, since we always know the element count in advance. But that still does not seem to be enough to justify the sequential scan on each level of recursion.</p> <p>(Admittedly, I haven't tried to race the implementations against each other. Maybe there are some surprises there.)</p>
40,629,882
2
20
null
2016-11-16 01:06:06.95 UTC
6
2022-09-18 23:06:09.893 UTC
2017-05-23 11:53:41.45 UTC
null
-1
null
187,690
null
1
50
c++|algorithm|list|sorting|mergesort
2,082
<p>Note this answer has been updated to address all of the issues mentioned in the comments below and after the question, by making the same change from an array of lists to an array of iterators, while retaining the faster bottom up merge sort algorithm, and eliminating the small chance of stack overflow due to recursion with the top down merge sort algorithm.</p> <p>The reason I didn't originally consider iterators was due to the VS2015 change to top down, leading me to believe there was some issue with trying to change the existing bottom up algorithm to use iterators, requiring a switch to the slower top down algorithm. It was only when I tried to analyze the switch to iterators myself that I realized there was a solution for bottom up algorithm.</p> <p>In @sbi's comment, he asked the author of the top down approach, Stephan T. Lavavej, why the change was made. Stephan's response was &quot;to avoid memory allocation and default constructing allocators&quot;. VS2015 introduced non-default-constructible and stateful allocators, which presents an issue when using the prior version's array of lists, as each instance of a list allocates a dummy node, and a change would be needed to handle no default allocator.</p> <p>Lavavej's solution was to switch to using iterators to keep track of run boundaries within the original list instead of an internal array of lists. The merge logic was changed to use 3 iterator parameters, 1st parameter is iterator to start of left run, 2nd parameter is iterator to end of left run == iterator to start of right run, 3rd parameter is iterator to end of right run. The merge process uses std::list::splice to move nodes within the original list during merge operations. This has the added benefit of being exception safe. If a caller's compare function throws an exception, the list will be re-ordered, but no loss of data will occur (assuming splice can't fail). With the prior scheme, some (or most) of the data would be in the internal array of lists if an exception occurred, and data would be lost from the original list.</p> <p>However the switch to top down merge sort was not needed. Initially, thinking there was some unknown to me reason for VS2015 switch to top down, I focused on using the internal interfaces in the same manner as std::list::splice. I later decided to investigate switching bottom up to use an array of iterators. I realized the order of runs stored in the internal array was newest (array[0] = rightmost) to oldest (array[last] = leftmost), and that it could use the same iterator based merge logic as VS2015's top down approach.</p> <p>For bottom up merge sort, array[i] is an iterator to the start of a sorted sub-list with 2^i nodes, or it is empty (using std::list::end to indicate empty). The end of each sorted sub-list will be the start of a sorted sub-list in the next prior non-empty entry in the array, or if at the start of the array, in a local iterator (it points to end of newest run). Similar to the top down approach, the array of iterators is only used to keep track of sorted run boundaries within the original linked list, while the merge process uses std::list::splice to move nodes within the original linked list.</p> <p>If a linked list is large and the nodes scattered, there will be a lot of cache misses. Bottom up will be about 30% faster than top down (equivalent to stating top down is about 42% slower than bottom up ). Then again, if there's enough memory, it would usually be faster to move the list to an array or vector, sort the array or vector, then create a new list from the sorted array or vector.</p> <p>Example C++ code:</p> <pre><code>#define ASZ 32 template &lt;typename T&gt; void SortList(std::list&lt;T&gt; &amp;ll) { if (ll.size() &lt; 2) // return if nothing to do return; std::list&lt;T&gt;::iterator ai[ASZ]; // array of iterators std::list&lt;T&gt;::iterator mi; // middle iterator (end lft, bgn rgt) std::list&lt;T&gt;::iterator ei; // end iterator size_t i; for (i = 0; i &lt; ASZ; i++) // &quot;clear&quot; array ai[i] = ll.end(); // merge nodes into array for (ei = ll.begin(); ei != ll.end();) { mi = ei++; for (i = 0; (i &lt; ASZ) &amp;&amp; ai[i] != ll.end(); i++) { mi = Merge(ll, ai[i], mi, ei); ai[i] = ll.end(); } if(i == ASZ) i--; ai[i] = mi; } // merge array into single list ei = ll.end(); for(i = 0; (i &lt; ASZ) &amp;&amp; ai[i] == ei; i++); mi = ai[i++]; while(1){ for( ; (i &lt; ASZ) &amp;&amp; ai[i] == ei; i++); if (i == ASZ) break; mi = Merge(ll, ai[i++], mi, ei); } } template &lt;typename T&gt; typename std::list&lt;T&gt;::iterator Merge(std::list&lt;T&gt; &amp;ll, typename std::list&lt;T&gt;::iterator li, typename std::list&lt;T&gt;::iterator mi, typename std::list&lt;T&gt;::iterator ei) { std::list&lt;T&gt;::iterator ni; (*mi &lt; *li) ? ni = mi : ni = li; while(1){ if(*mi &lt; *li){ ll.splice(li, ll, mi++); if(mi == ei) return ni; } else { if(++li == mi) return ni; } } } </code></pre> <hr /> <p>Example replacement code for VS2019's std::list::sort() (the merge logic was made into a separate internal function, since it's now used in two places).</p> <pre><code>private: template &lt;class _Pr2&gt; iterator _Merge(_Pr2 _Pred, iterator _First, iterator _Mid, iterator _Last){ iterator _Newfirst = _First; for (bool _Initial_loop = true;; _Initial_loop = false) { // [_First, _Mid) and [_Mid, _Last) are sorted and non-empty if (_DEBUG_LT_PRED(_Pred, *_Mid, *_First)) { // consume _Mid if (_Initial_loop) { _Newfirst = _Mid; // update return value } splice(_First, *this, _Mid++); if (_Mid == _Last) { return _Newfirst; // exhausted [_Mid, _Last); done } } else { // consume _First ++_First; if (_First == _Mid) { return _Newfirst; // exhausted [_First, _Mid); done } } } } template &lt;class _Pr2&gt; void _Sort(iterator _First, iterator _Last, _Pr2 _Pred, size_type _Size) { // order [_First, _Last), using _Pred, return new first // _Size must be distance from _First to _Last if (_Size &lt; 2) { return; // nothing to do } const size_t _ASZ = 32; // array size iterator _Ai[_ASZ]; // array of iterators to runs iterator _Mi; // middle iterator iterator _Li; // last (end) iterator size_t _I; // index to _Ai for (_I = 0; _I &lt; _ASZ; _I++) // &quot;empty&quot; array _Ai[_I] = _Last; // _Ai[] == _Last =&gt; empty entry // merge nodes into array for (_Li = _First; _Li != _Last;) { _Mi = _Li++; for (_I = 0; (_I &lt; _ASZ) &amp;&amp; _Ai[_I] != _Last; _I++) { _Mi = _Merge(_Pass_fn(_Pred), _Ai[_I], _Mi, _Li); _Ai[_I] = _Last; } if (_I == _ASZ) _I--; _Ai[_I] = _Mi; } // merge array runs into single run for (_I = 0; _I &lt; _ASZ &amp;&amp; _Ai[_I] == _Last; _I++); _Mi = _Ai[_I++]; while (1) { for (; _I &lt; _ASZ &amp;&amp; _Ai[_I] == _Last; _I++); if (_I == _ASZ) break; _Mi = _Merge(_Pass_fn(_Pred), _Ai[_I++], _Mi, _Last); } } </code></pre> <hr /> <p>The remainder of this answer is historical, and only left for the historical comments, otherwise it is no longer relevant.</p> <hr /> <p>I was able to reproduce the issue (old sort fails to compile, new one works) based on a demo from @IgorTandetnik:</p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;memory&gt; template &lt;typename T&gt; class MyAlloc : public std::allocator&lt;T&gt; { public: MyAlloc(T) {} // suppress default constructor template &lt;typename U&gt; MyAlloc(const MyAlloc&lt;U&gt;&amp; other) : std::allocator&lt;T&gt;(other) {} template&lt; class U &gt; struct rebind { typedef MyAlloc&lt;U&gt; other; }; }; int main() { std::list&lt;int, MyAlloc&lt;int&gt;&gt; l(MyAlloc&lt;int&gt;(0)); l.push_back(3); l.push_back(0); l.push_back(2); l.push_back(1); l.sort(); return 0; } </code></pre> <hr /> <p>I noticed this change back in July, 2016 and emailed P.J. Plauger about this change on August 1, 2016. A snippet of his reply:</p> <blockquote> <p>Interestingly enough, our change log doesn't reflect this change. That probably means it was &quot;suggested&quot; by one of our larger customers and got by me on the code review. All I know now is that the change came in around the autumn of 2015. When I reviewed the code, the first thing that struck me was the line:</p> <pre><code> iterator _Mid = _STD next(_First, _Size / 2); </code></pre> <p>which, of course, can take a <em>very</em> long time for a large list.</p> <p>The code looks a bit more elegant than what I wrote in early 1995(!), but definitely has worse time complexity. That version was modeled after the approach by Stepanov, Lee, and Musser in the original STL. They are seldom found to be wrong in their choice of algorithms.</p> <p>I'm now reverting to our latest known good version of the original code.</p> </blockquote> <p>I don't know if P.J. Plauger's reversion to the original code dealt with the new allocator issue, or if or how Microsoft interacts with Dinkumware.</p> <p>For a comparison of the top down versus bottom up methods, I created a linked list with 4 million elements, each consisting of one 64 bit unsigned integer, assuming I would end up with a doubly linked list of nearly sequentially ordered nodes (even though they would be dynamically allocated), filled them with random numbers, then sorted them. The nodes don't move, only the linkage is changed, but now traversing the list accesses the nodes in random order. I then filled those randomly ordered nodes with another set of random numbers and sorted them again. I compared the 2015 top down approach with the prior bottom up approach modified to match the other changes made for 2015 (sort() now calls sort() with a predicate compare function, rather than having two separate functions). These are the results. <em>update</em> - I added a node pointer based version and also noted the time for simply creating a vector from list, sorting vector, copy back.</p> <pre><code>sequential nodes: 2015 version 1.6 seconds, prior version 1.5 seconds random nodes: 2015 version 4.0 seconds, prior version 2.8 seconds random nodes: node pointer based version 2.6 seconds random nodes: create vector from list, sort, copy back 1.25 seconds </code></pre> <p>For sequential nodes, the prior version is only a bit faster, but for random nodes, the prior version is 30% faster, and the node pointer version 35% faster, and creating a vector from the list, sorting the vector, then copying back is 69% faster.</p> <p>Below is the first replacement code for std::list::sort() I used to compare the prior bottom up with small array (_BinList[]) method versus VS2015's top down approach I wanted the comparison to be fair, so I modified a copy of &lt; list &gt;.</p> <pre><code> void sort() { // order sequence, using operator&lt; sort(less&lt;&gt;()); } template&lt;class _Pr2&gt; void sort(_Pr2 _Pred) { // order sequence, using _Pred if (2 &gt; this-&gt;_Mysize()) return; const size_t _MAXBINS = 25; _Myt _Templist, _Binlist[_MAXBINS]; while (!empty()) { // _Templist = next element _Templist._Splice_same(_Templist.begin(), *this, begin(), ++begin(), 1); // merge with array of ever larger bins size_t _Bin; for (_Bin = 0; _Bin &lt; _MAXBINS &amp;&amp; !_Binlist[_Bin].empty(); ++_Bin) _Templist.merge(_Binlist[_Bin], _Pred); // don't go past end of array if (_Bin == _MAXBINS) _Bin--; // update bin with merged list, empty _Templist _Binlist[_Bin].swap(_Templist); } // merge bins back into caller's list for (size_t _Bin = 0; _Bin &lt; _MAXBINS; _Bin++) if(!_Binlist[_Bin].empty()) this-&gt;merge(_Binlist[_Bin], _Pred); } </code></pre> <p>I made some minor changes. The original code kept track of the actual maximum bin in a variable named _Maxbin, but the overhead in the final merge is small enough that I removed the code associated with _Maxbin. During the array build, the original code's inner loop merged into a _Binlist[] element, followed by a swap into _Templist, which seemed pointless. I changed the inner loop to just merge into _Templist, only swapping once an empty _Binlist[] element is found.</p> <p>Below is a node pointer based replacement for std::list::sort() I used for yet another comparison. This eliminates allocation related issues. If a compare exception is possible and occurred, all the nodes in the array and temp list (pNode) would have to be appended back to the original list, or possibly a compare exception could be treated as a less than compare.</p> <pre><code> void sort() { // order sequence, using operator&lt; sort(less&lt;&gt;()); } template&lt;class _Pr2&gt; void sort(_Pr2 _Pred) { // order sequence, using _Pred const size_t _NUMBINS = 25; _Nodeptr aList[_NUMBINS]; // array of lists _Nodeptr pNode; _Nodeptr pNext; _Nodeptr pPrev; if (this-&gt;size() &lt; 2) // return if nothing to do return; this-&gt;_Myhead()-&gt;_Prev-&gt;_Next = 0; // set last node -&gt;_Next = 0 pNode = this-&gt;_Myhead()-&gt;_Next; // set ptr to start of list size_t i; for (i = 0; i &lt; _NUMBINS; i++) // zero array aList[i] = 0; while (pNode != 0) // merge nodes into array { pNext = pNode-&gt;_Next; pNode-&gt;_Next = 0; for (i = 0; (i &lt; _NUMBINS) &amp;&amp; (aList[i] != 0); i++) { pNode = _MergeN(_Pred, aList[i], pNode); aList[i] = 0; } if (i == _NUMBINS) i--; aList[i] = pNode; pNode = pNext; } pNode = 0; // merge array into one list for (i = 0; i &lt; _NUMBINS; i++) pNode = _MergeN(_Pred, aList[i], pNode); this-&gt;_Myhead()-&gt;_Next = pNode; // update sentinel node links pPrev = this-&gt;_Myhead(); // and _Prev pointers while (pNode) { pNode-&gt;_Prev = pPrev; pPrev = pNode; pNode = pNode-&gt;_Next; } pPrev-&gt;_Next = this-&gt;_Myhead(); this-&gt;_Myhead()-&gt;_Prev = pPrev; } template&lt;class _Pr2&gt; _Nodeptr _MergeN(_Pr2 &amp;_Pred, _Nodeptr pSrc1, _Nodeptr pSrc2) { _Nodeptr pDst = 0; // destination head ptr _Nodeptr *ppDst = &amp;pDst; // ptr to head or prev-&gt;_Next if (pSrc1 == 0) return pSrc2; if (pSrc2 == 0) return pSrc1; while (1) { if (_DEBUG_LT_PRED(_Pred, pSrc2-&gt;_Myval, pSrc1-&gt;_Myval)) { *ppDst = pSrc2; pSrc2 = *(ppDst = &amp;pSrc2-&gt;_Next); if (pSrc2 == 0) { *ppDst = pSrc1; break; } } else { *ppDst = pSrc1; pSrc1 = *(ppDst = &amp;pSrc1-&gt;_Next); if (pSrc1 == 0) { *ppDst = pSrc2; break; } } } return pDst; } </code></pre>
10,404,027
Can't compile example from google protocol buffers
<p>I grep for other topics, but they dont help me =(. On my working server, i have no sudo privilegies, so i install PB with</p> <blockquote> <p>./configure --prefix=/home/username/local</p> </blockquote> <p>Then i create source files with "person" example and succesfully compile it with protoc.</p> <p>I have no pkg-info =(. I try to compile it with</p> <blockquote> <p>g++ -I /home/username/local/include -L /home/username/local/lib -lprotobuf -lpthread main.cpp person.pb.cc</p> </blockquote> <p>and then have a billion simular errors i.e. </p> <blockquote> <p>person.pb.cc:(.text+0x4cf): undefined reference to `google::protobuf::internal::kEmptyString'</p> </blockquote> <p>I think, that it is a problem with linking, but how to solve it?</p> <blockquote> <p>echo $LD_LIBRARY_PATH /home/username/local/lib</p> </blockquote> <p>in main.cpp:</p> <pre><code>#include "person.pb.h" ... </code></pre> <p>Thanks.</p>
10,404,243
3
0
null
2012-05-01 20:40:13.823 UTC
4
2020-02-01 09:21:40.18 UTC
null
null
null
null
1,368,572
null
1
12
c++|linux|compiler-errors|g++|protocol-buffers
40,147
<p>Put the library at the end:</p> <blockquote> <p>g++ -I /home/username/local/include -L /home/username/local/lib main.cpp person.pb.cc -lprotobuf -pthread</p> </blockquote> <p>From <a href="http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html" rel="noreferrer">GCC Link Options</a>:</p> <pre> -llibrary -l library Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, `foo.o -lz bar.o' searches library `z' after file foo.o but before bar.o. If bar.o refers to functions in `z', those functions may not be loaded. </pre> <p>Also, use <code>-pthread</code> instead of <code>-lpthread</code> as <code>-pthread</code> may set flags for preprocessor and linker.</p>
10,832,422
TestNG: More than one @DataProvider for one @Test
<p>I'm using <code>TestNG</code> for <code>Eclipse</code>.</p> <p>Is it possible to give two data providers step by step to the <strong>same</strong> test-function?</p> <p>I could put both providers in one, but that is not what I want.</p> <p>I need (not like in this example) to generate independently data.</p> <pre><code>@DataProvider(name = &quot;dataSet1&quot;) public Object[][] createDataX() { return new Object[][] { { 1, 1 }, { 2, 2 } }; } @DataProvider(name = &quot;dataSet2&quot;) public Object[][] createDataY() { return new Object[][] { { 0, 0 }, { 3, 3 } }; } </code></pre> <p>I want to give both providers to the same test. Is this possible?</p> <pre><code>@Test(dataProvider = &quot;dataSet1&quot;) // ??? and &quot;dataSet2&quot; ??? public void testThisFunction(int val1, int val2) { boolean solution = oracle(val1,val2); assert (solution); } </code></pre>
10,839,095
4
0
null
2012-05-31 11:09:17.38 UTC
9
2021-03-26 16:12:53.163 UTC
2021-03-26 16:12:53.163 UTC
null
7,804,477
null
789,111
null
1
28
java|testing|automated-tests|testng|dataprovider
40,874
<p>No, but nothing stops you from merging these two data providers into one and specifying that one as your data provider:</p> <pre><code>public Object[][] dp1() { return new Object[][] { new Object[] { "a", "b" }, new Object[] { "c", "d" }, }; } public Object[][] dp2() { return new Object[][] { new Object[] { "e", "f" }, new Object[] { "g", "h" }, }; } @DataProvider public Object[][] dp() { List&lt;Object[]&gt; result = Lists.newArrayList(); result.addAll(Arrays.asList(dp1())); result.addAll(Arrays.asList(dp2())); return result.toArray(new Object[result.size()][]); } @Test(dataProvider = "dp") public void f(String a, String b) { System.out.println("f " + a + " " + b); } </code></pre>
10,761,551
How do I get the current Url from within a FilterAttribute?
<p>I am writing an Authorize filter attribute adn I'm having trouble figuring out how to get the current url as a string so I can pass it as a parameter to the LogOn action. The goal is that if a user successfully logs on, they will be redirected to the page they were originally trying to access.</p> <pre><code>public override void OnAuthorization(AuthorizeContext filterContext) { base.OnAuthorization(filterContext); ... my auth code ... bool isAuth ; ... my auth code ... if(!isAuth) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "Area", "" }, { "Controller", "Account" }, { "Action", "LogOn" }, { "RedirectUrl", "/Url/String/For/Currnt/Request" } // how do I get this? } ); } } </code></pre> <p>How do I get the full string Url from the current request?</p>
10,761,606
4
0
null
2012-05-25 21:25:42.287 UTC
6
2018-05-04 14:38:48.693 UTC
2013-05-04 08:56:06.92 UTC
null
114,029
null
336,384
null
1
50
asp.net-mvc|url|authorization|action-filter|actionfilterattribute
31,777
<p>Try:</p> <pre><code>var url = filterContext.HttpContext.Request.Url; </code></pre>
5,940,756
Draw a table in vertical display instead of horizontal display
<p>Can Someone tell me by which command I can draw a table in vertical display in LaTex.</p> <p>Thanks.. </p>
5,941,019
2
4
null
2011-05-09 18:12:02.567 UTC
3
2020-03-09 06:09:43.98 UTC
null
null
null
null
616,141
null
1
18
latex
66,342
<p>I think you want the <code>lscape</code> package, can be usefully used for this purpose as follows:</p> <pre> \begin{landscape} \begin{table} \centering \begin{tabular}{....} ....... \end{tabular} \end{table} \end{landscape} </pre> <hr> <p>EDIT 2nd solution: Another possibility is to use the <code>sideways</code> environment from the <code>rotating</code> package:</p> <pre> \begin{sideways} \begin{tabular} ... \end{tabular} \end{sideways} </pre> <p>And for floating tables <code>sidewaystable</code>.</p>
58,600,728
What is the difference between TEST, TEST_F and TEST_P?
<p>I have researched a lot about gtest/gmock but none of them gave me the right answer. I new to C++ so any help would be really appreciated.</p>
58,680,861
1
0
null
2019-10-29 02:29:14.003 UTC
11
2021-09-26 06:18:26.23 UTC
2021-03-19 02:23:53.817 UTC
null
1,076,113
null
11,503,182
null
1
44
googletest|googlemock
51,154
<p>All documentation is covered in the <a href="https://github.com/google/googletest" rel="noreferrer">official github repo</a>. The <a href="https://github.com/google/googletest/blob/master/docs/primer.md" rel="noreferrer">primer documentation</a> also covers a lot of information regarding the test macros. You could use the following summary and the examples linked to choose what you want to use.</p> <p><code>TEST()</code> is useful when you want to write unit tests for static or global functions or simple classes. <a href="https://github.com/google/googletest/blob/565f1b848215b77c3732bca345fe76a0431d8b34/googletest/test/googletest-port-test.cc#L54" rel="noreferrer">Example test</a></p> <p><code>TEST_F()</code> is useful when you need access to objects and subroutines in the unit test. <a href="https://github.com/google/googletest/blob/e8a82dc7ede61c4af3b9d75aa0e953b8cecfc8bb/googletest/test/gtest_unittest.cc#L102" rel="noreferrer">Example test</a></p> <p><code>TEST_P()</code> is useful when you want to write tests with a parameter. Instead of writing multiple tests with different values of the parameter, you can write one test using <code>TEST_P()</code> which uses <code>GetParam()</code> and can be instantiated using <code>INSTANTIATE_TEST_SUITE_P()</code>. <a href="https://github.com/google/googletest/blob/eafd2a91bb0c4fd626aae63ae852812fbd4999f2/googletest/test/googletest-param-test-test.cc#L679" rel="noreferrer">Example test</a></p>
21,319,602
find file with wild card matching
<p>In node.js, can I list files with wild card matching like </p> <pre><code>fs.readdirSync('C:/tmp/*.csv')? </code></pre> <p>I did not find the information on wild card matching from the <a href="http://nodejs.org/docs/v0.3.1/api/fs.html#fs.readFileSync" rel="noreferrer">fs documention</a>.</p>
21,320,251
6
1
null
2014-01-23 21:22:57.88 UTC
12
2021-11-17 11:25:14.203 UTC
2018-10-17 09:03:55.137 UTC
null
863,110
null
305,669
null
1
100
node.js
90,973
<p>This is <em>not</em> covered by Node core. You can check out <a href="https://npmjs.org/package/glob" rel="noreferrer">this module</a> for what you are after.</p> <h3>Setup</h3> <pre class="lang-sh prettyprint-override"><code>npm i glob </code></pre> <h3>Usage</h3> <pre><code>var glob = require(&quot;glob&quot;) // options is optional glob(&quot;**/*.js&quot;, options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is [&quot;**/*.js&quot;] // er is an error object or null. }) </code></pre>
21,058,742
Difference between WSGI utilities and Web Servers
<p>I am new to Python and i am not able to understand the server concepts in Python.</p> <p>First of all what is <strong>WSGI</strong> and what are <strong>Wsgiref</strong> and <strong>Werkzeug</strong> and how are they different from CherryPy WSGI Server, Gunicorn, Tornado (HTTP Server via wsgi.WSGIContainer), Twisted Web, uWSGI, Waitress WSGI Server.</p> <p>If i need to develop a web application from scratch, i mean starting from the beginning, where should i start, my company needs a custom framework and the application is based on critical performance overheads.</p> <p>Please help and explain how they are different.</p> <p>P.S I am not a beginner to programming.</p>
21,058,882
1
1
null
2014-01-11 05:06:34.84 UTC
14
2014-01-11 05:34:32.74 UTC
2014-01-11 05:26:58.277 UTC
null
2,255,305
null
1,112,163
null
1
18
python|wsgi
4,021
<p>WSGI is just a set a rules to help unify and standardize how Python applications communicate with web servers. It defines both how applications should send responses and how servers should communicate with applications and pass along the environment and other details about the request. Any application that needs to communicate with any web server implements WSGI, because its the de-facto standard and recommended method for Python. WSGI came about to unify the other implementations (CGI, mod_python, FastCGI).</p> <p>wsgiref is a <em>reference implementation</em> of the WSGI interface. Its like a blueprint to help developers understand how to implement WSGI in their own applications.</p> <p>The other things you mentioned are all different applications that implement the WSGI standard; with some exceptions:</p> <ol> <li><p>Twisted is a library to create applications that can communicate over a network. <em>Any</em> kind of network, and any kind of applications. Its not limited to the web.</p></li> <li><p>Tornado is similar to Twisted in that it is also a library for network communication; however it is designed for <em>non blocking</em> applications. Things that require a long open connection to the server (like say, an application that displays realtime feeds).</p></li> <li><p>CherryPy is a very minimal Python framework for creating web applications. It <em>implements</em> WSGI.</p></li> <li><p>Werkzeug is a library that implements WSGI. So if you are developing an application that needs to speak WSGI, you would import werkzeug because it provides all various parts of WSGI that you would need.</p></li> <li><p>uWSGI is a project that allows easily hosting of multiple web applications. The fact that it as WSGI in the name is because WSGI was the first plugin that was released with the application. It is perhaps the odd duck in this list because it is not a development framework, but more of a way to manage multiple web applications.</p></li> </ol> <p>Web servers that <em>implement</em> WSGI can talk to any application that also implements WSGI. <a href="http://code.google.com/p/modwsgi/" rel="noreferrer"><code>modwsgi</code></a> is a popular implementation of WSGI for webservers; it is available for both Apache and Nginx and for IIS there is the <a href="http://code.google.com/p/isapi-wsgi/" rel="noreferrer">isapi wsgi module</a>.</p>
21,038,706
PersistenceUnit vs PersistenceContext
<p>In few project I have been successfully using </p> <pre><code>@PersistenceUnit(unitName = "MiddlewareJPA") EntityManagerFactory emf; ... EntityManager entityManager = emf.createEntityManager(); </code></pre> <p>to obtain <code>EntityManager</code> for Database connection, but some days ago I was trying to move my project to <code>Jboss EAP 6.2</code> and it couldn't create <code>EntityManager</code>. I was googling it and I found that I should try change <code>@PersistenceUnit</code> to</p> <pre><code>@PersistenceContext(unitName = "MiddlewareJPA") private EntityManager entityManager; </code></pre> <p>to obtain <em>EntityManager</em>. It worked but I don't know why. What is the difference bettween <code>PersistenceUnit</code> and <code>PersistenceContext</code>? What are pros and cons of each one? Where should we be using one of them? </p>
21,039,700
3
2
null
2014-01-10 07:45:27.987 UTC
20
2019-09-14 12:09:38.46 UTC
2015-03-11 21:07:27.697 UTC
null
814,702
null
2,377,971
null
1
55
java|jakarta-ee|jpa|persistence|entitymanager
33,555
<p>I don't know how it works exactly in the Java EE, but in Spring, when you specify <code>@PersistenceContext</code> annotation, it injects <code>EntityManager</code>. Where does it get <code>EntityManager</code>? It is wrong to create one <code>EntityManager</code> for the whole application lifetime by calling <code>EntityManagerFactory.createEntityManager()</code>. So instead a special implementation of <code>EntityManager</code> interface is used and instantiated directly. It has an internal mutable thread-local reference to a <em>real</em> <code>EntityManager</code>. Implementations of methods just redirect calls to this <em>real</em> <code>EntityManager</code>. And there is a servlet listener, that before each request obtain <code>EM</code> by calling <code>EMF.createEntityManager()</code> and assign it to that inner reference of special <code>EM</code>. Also this listener manages transactions by calling <code>getTransaction().begin()</code>, <code>.commit()</code> and <code>.rollback()</code> on the <em>real</em> <code>EM</code>. It is very simplified description of performed work. And I believe, that JEE container does the same thing, as Spring does.</p> <p>In general case it is better to inject <code>EntityManager</code>, because with <code>EntityManagerFactory</code> and <code>@PersistenceUnit</code> you should create/destroy <code>EntityManager</code> every time by hands and manage transactions too.</p>
21,751,868
Delete a database in phpMyAdmin
<p>By mistake, I have created a duplicate database in the phpMyAdmin page of cPanel. I want to delete this database, but I am not able to find any delete button in the UI.</p> <p>How to delete a database in phpMyAdmin?</p>
21,752,208
17
0
null
2014-02-13 10:42:31.707 UTC
15
2022-06-26 23:33:22.587 UTC
null
null
null
null
3,065,082
null
1
118
phpmyadmin
470,763
<p>After successful login to cPanel, near to the <code>phpMyAdmin</code> icon there is another icon <code>MySQL Databases</code>; click on that.</p> <p><img src="https://i.stack.imgur.com/mqYOT.png" alt="enter image description here"></p> <p>That brings you to the database listing page.</p> <p>In the action column you can find the <code>delete database</code> option click on that to delete your database!</p>
29,870,337
How to take google maps snapshot without actually displaying the map
<p>I want to be able to take a screenshot of a certain location in google maps without actually loading the google map onto the screen, If there is a way google map can take the screenshot in the background that would be great.</p>
29,871,009
1
2
null
2015-04-25 20:24:10.223 UTC
8
2015-04-25 21:36:17.447 UTC
null
null
null
null
4,739,608
null
1
13
android|google-maps|android-googleapiclient
11,966
<p>There is <a href="https://developers.google.com/maps/documentation/android/lite" rel="noreferrer">Lite Mode</a>:</p> <blockquote> <p><strong>The Google Maps Android API can serve a static image as a 'lite mode' map.</strong> </p> <p>A lite mode map is a bitmap image of a map at a specified location and zoom level. Lite mode supports all of the map types (normal, hybrid, satellite, terrain) and a subset of the functionality supplied by the full API. Lite mode is useful when you want to provide a number of maps in a stream, or a map that is too small to support meaningful interaction.</p> </blockquote> <p>Example:</p> <p><strong>As an XML attribute for a MapView or MapFragment</strong></p> <pre><code>&lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:map="http://schemas.android.com/apk/res-auto" android:name="com.google.android.gms.maps.MapFragment" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" map:cameraZoom="13" map:mapType="normal" map:liteMode="true"/&gt; </code></pre> <p><strong>In the GoogleMapOptions object</strong></p> <pre><code>GoogleMapOptions options = new GoogleMapOptions().liteMode(true); </code></pre> <p><a href="https://developers.google.com/maps/documentation/android/lite#supported_api_features" rel="noreferrer">Here</a> You can find supported features.</p> <hr> <p>In addition I recommend reading: <a href="https://stackoverflow.com/questions/26946503/android-google-map-to-show-as-picture">Android Google Map to show as picture</a></p> <blockquote> <p>You can use the Google Maps built-in snapshot method, to capture a preview and display it in an ImageView.</p> </blockquote>
8,369,334
Using Html.ActionLink with RouteValues
<p>I have the following Html:</p> <pre><code>&lt;%: Html.ActionLink(item.ProductName, "Details", "Product", new { item.ProductId }, null)%&gt; </code></pre> <p>This is being rendered as:</p> <pre><code>&lt;a href="/Product/Details?ProductId=1"&gt;My Product Name&lt;/a&gt; </code></pre> <p>However, when I click on this, I get the following error:</p> <blockquote> <p>The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MyProject.Controllers.ProductController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. </p> <p>Parameter name: parameters</p> </blockquote> <p>It appears that my routing doesn't like the "?ProductId=1" query string.</p> <p>If I use instead:</p> <pre><code>&lt;%: Html.ActionLink(item.ProductName, string.Format("Details/{0}", item.ProductId), "Product", null, null)%&gt; </code></pre> <p>I get the following link rendered:</p> <pre><code>&lt;a href="/Product/Details/1"&gt;My Product Name&lt;/a&gt; </code></pre> <p>...and this works correctly when clicked.</p> <p>Am I missing something basic here? I'd like to use RouteValues, but I don't understand why this error is being thrown. How can I get my Controller method to accept query string parameters?</p> <p>The only route mapping I have is:</p> <pre><code> routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); </code></pre>
8,369,355
2
0
null
2011-12-03 17:05:03.583 UTC
2
2011-12-03 17:40:23.337 UTC
2011-12-03 17:21:50.567 UTC
null
601,179
null
632,450
null
1
11
asp.net-mvc|asp.net-mvc-3|model-view-controller|asp.net-mvc-routing
41,563
<p>Change the action parameter to be int ProductId.</p> <pre><code>public ActionResult Details(int productId) { return View(""); } </code></pre> <p>your controller have to get an "id" parameter because you declared it as <strong>not</strong> nullable int so when you send productId it still doesn't match the function signature.<br> when you don't specify the parameter name, the routing defaults in the global.asax change the parameter name to id:</p> <pre><code> routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); </code></pre> <p>see the last line.</p>
8,484,181
How to enable a disabled text field?
<p>I wanna know how do I enable a disabled form text field on submit. Also I wanna make sure if user goes back to form or click reset field will show again as disabled.</p> <p>I tried to use </p> <pre><code>document.pizza.field07.disabled = false ; </code></pre> <p>It does disables the field, by clicking reset or hitting back button still keeps it enable. </p> <p>Please guide.</p>
8,484,196
5
0
null
2011-12-13 04:05:27.66 UTC
4
2020-07-28 11:05:55.14 UTC
null
null
null
null
1,094,741
null
1
16
javascript|html|forms|validation|onsubmit
86,425
<p>To access this element in a more standard way, use <a href="https://developer.mozilla.org/en/DOM/document.getElementById">document.getElementById</a> with <a href="https://developer.mozilla.org/en/DOM/element.setAttribute">setAttribute</a></p> <pre><code>document.getElementById("field07").setAttribute("disabled", false); </code></pre> <p><strong>EDIT</strong></p> <p>Based on your comment, it looks like field07 is a <em>name</em>, not an id. As such, this should be what you want:</p> <pre><code>var allfield7s = document.getElementsByName("field07"); for (var i = 0; i &lt; allfield7s.length; i++) allfield7s[i].setAttribute("disabled", false); </code></pre>
8,592,056
What does IB mean in IBAction, IBOutlet, etc..?
<p>I am very new to iPhone development. I often encounter <code>IBAction</code>, <code>IBOutlet</code> and so on when reading Objective-C and Swift code. What does <code>IB</code> stand for?</p>
8,592,079
3
0
null
2011-12-21 15:15:53.367 UTC
11
2018-10-29 17:51:54.99 UTC
2018-10-29 17:51:54.99 UTC
null
9,763,253
null
969,645
null
1
42
iphone|xcode
13,361
<p>"Interface Builder".</p> <p>Before Xcode 4, the interface files (XIBs and NIBs) were edited in a separate program called Interface Builder, hence the prefix.</p> <p><code>IBAction</code> is defined to <code>void</code>, and <code>IBOutlet</code> to nothing. They are just clues to Interface Builder when parsing files to make them available for connections.</p> <p>Just to add the reference, inside AppKit/NSNibDeclarations.h you'll find these:</p> <pre><code>#ifndef IBOutlet #define IBOutlet #endif #ifndef IBAction #define IBAction void #endif </code></pre> <p>So, actually, code like this:</p> <pre><code>@interface ... { IBOutlet NSTextField *label; } - (IBAction)buttonPressed:(id)sender; @end </code></pre> <p>Will be transformed into:</p> <pre><code>@interface ... { NSTextField *label; } - (void)buttonPressed:(id)sender; @end </code></pre> <p>By the preprocessor, even before the compiler sees it. Those keywords were acting just as clues to Interface Builder.</p>
8,592,289
ARC - The meaning of __unsafe_unretained?
<p>Just want to make sure that I got it right:</p> <ol> <li>Do I need to <code>__unsafe_unretain</code> objects that I don't own?</li> <li>If an object is <code>__unsafe_unretained</code> Do I need to use <code>assign</code> in the <code>@property</code>? Does that mean that the object is not retained, and just refers to the object I assign to?</li> <li>When would I want to use it except of delegates?</li> <li>Is that an ARC thing or was it in use before?</li> </ol>
8,593,731
4
0
null
2011-12-21 15:32:55.31 UTC
64
2013-01-25 09:15:12.65 UTC
2012-08-09 16:17:08.317 UTC
null
766,441
null
358,480
null
1
82
objective-c|ios|macos|xcode4|automatic-ref-counting
42,879
<p>The LLVM Compiler 3.0 introduces four new ownership qualifiers: <code>__strong</code>, <code>__autoreleasing</code>, <code>__unsafe_unretained</code>, and <code>__weak</code>. The first three are available even outside ARC, as per <a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html" rel="noreferrer">the specification</a>.</p> <p>As Joshua indicates, by default all pointers are implied to be <code>__strong</code> under ARC. This means that when an object is assigned to that pointer, it is retained for as long as that pointer refers to it. This is fine for most things, but it opens up the possibility for retain cycles, as I describe in my answer <a href="https://stackoverflow.com/a/6388601/19679">here</a>. For example, if you have an object that contains another object as an instance variable, but that second object has a strong link back to the first one as its delegate, the two objects will never be released.</p> <p>It is for this reason that the <code>__unsafe_unretained</code> and <code>__weak</code> qualifiers exist. Their most common use is for delegates, where you'd define a property for that delegate with the <code>weak</code> or <code>unsafe_unretained</code> attribute (<code>assign</code> is effectively <code>unsafe_unretained</code>), and then match that by marking the respective instance variable with <code>__weak</code> or <code>__unsafe_unretained</code>. This means that the delegate instance variable will still point back at the first object, but it will not cause that object to be retained, thus breaking the retain cycle and allowing both objects to be released.</p> <p>Beyond delegates, this is useful to break any other retain cycles that might form in your code. Helpfully, the Leaks instrument now includes a Cycles view, which shows retain cycles it discovers in your application in a graphical manner.</p> <p>Both <code>__unsafe_unretained</code> and <code>__weak</code> prevent the retention of objects, but in slightly different ways. For <code>__weak</code>, the pointer to an object will convert to <code>nil</code> on the deallocation of the object it points to, which is very safe behavior. As its name implies, <code>__unsafe_unretained</code> will continue pointing to the memory where an object was, even after it was deallocated. This can lead to crashes due to accessing that deallocated object.</p> <p>Why would you ever use <code>__unsafe_unretained</code> then? Unfortunately, <code>__weak</code> is only supported for iOS 5.0 and Lion as deployment targets. If you want to target back to iOS 4.0 and Snow Leopard, you have to use the <code>__unsafe_unretained</code> qualifier, or use something like Mike Ash's <a href="http://www.mikeash.com/pyblog/friday-qa-2010-07-16-zeroing-weak-references-in-objective-c.html" rel="noreferrer">MAZeroingWeakRef</a>.</p>
8,846,173
How to remove the first and last character of a string?
<p>I have worked in a SOAP message to get the LoginToken from a Webservice, and store that LoginToken as a String. U used <code>System.out.println(LoginToken);</code> to print the value. This prints <code>[wdsd34svdf]</code>, but I want only <code>wdsd34svdf</code>. How can I remove these square brackets at the start and end of the output?</p> <p>Example:</p> <pre><code>String LoginToken=getName().toString(); System.out.println(&quot;LoginToken&quot; + LoginToken); </code></pre> <p>The output is: <code>[wdsd34svdf]</code>.</p> <p>I want just <code>wdsd34svdf</code></p>
8,846,218
12
0
null
2012-01-13 05:05:15.863 UTC
12
2022-06-15 10:55:57.04 UTC
2021-12-23 16:52:09.093 UTC
null
2,756,409
null
1,142,914
null
1
100
java|string
235,408
<p>You need to find the index of <code>[</code> and <code>]</code> then <code>substring</code>. (Here <code>[</code> is always at start and <code>]</code> is at end):</p> <pre><code>String loginToken = &quot;[wdsd34svdf]&quot;; System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) ); </code></pre>
27,104,521
How to add a scrollview edge color effect in Android Lollipop?
<p>In my app I change the overscroll glow effect color like this:</p> <pre><code>int glowDrawableId = contexto.getResources().getIdentifier("overscroll_glow", "drawable", "android"); Drawable androidGlow = contexto.getResources().getDrawable(glowDrawableId); assert androidGlow != null; androidGlow.setColorFilter(getResources().getColor(R.color.MyColor), PorterDuff.Mode.SRC_ATOP); </code></pre> <p>But when i updated to lollipop this code crashes. I get following error code:</p> <pre><code>FATAL EXCEPTION: main Process: com.myproject.myapp, PID: 954 android.content.res.Resources$NotFoundException: Resource ID #0x0 at android.content.res.Resources.getValue(Resources.java:1233) at android.content.res.Resources.getDrawable(Resources.java:756) at android.content.res.Resources.getDrawable(Resources.java:724) </code></pre> <p>Seems that overscroll_glow resource is missing in lollipop.</p> <p>How can I achieve this?</p>
27,115,812
6
1
null
2014-11-24 12:07:42.68 UTC
13
2019-09-25 22:07:41.487 UTC
2019-09-25 22:07:41.487 UTC
null
2,756,409
null
3,065,901
null
1
18
android|scrollview|android-5.0-lollipop
17,497
<p>You can specify <code>android:colorEdgeEffect</code> in your theme to change the overscroll glow color within your entire app. By default, this inherits the primary color value set by <code>android:colorPrimary</code>.</p> <p>res/values/themes.xml:</p> <pre><code>&lt;style name="MyAppTheme" parent="..."&gt; ... &lt;item name="android:colorEdgeEffect"&gt;@color/my_color&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Alternatively, you can modify this value for a single view using an inline theme overlay.</p> <p>res/values/themes.xml:</p> <pre><code>&lt;!-- Note that there is no parent style or additional attributes specified. --&gt; &lt;style name="MyEdgeOverlayTheme"&gt; &lt;item name="android:colorEdgeEffect"&gt;@color/my_color&lt;/item&gt; &lt;/style&gt; </code></pre> <p>res/layout/my_layout.xml:</p> <pre><code>&lt;ListView ... android:theme="@style/MyEdgeOverlayTheme" /&gt; </code></pre>
557,052
Exceptions in PHP - Try/Catch or set_exception_handler?
<p>I'm developing some lower end code in my system that uses multiple child classes of the php exception class. Essentially I have the exceptions broken up to a few categories. What I'm wanting to do is two things. </p> <ol> <li>I need all exceptions that are fired in the application to be handled in a single place.</li> <li>I need to be able to log and then handle/generate the view for the user to receive feedback on the apps. error.</li> </ol> <p>What I'm wondering is should I have some sort of try/catch encapsulating the application? I don't like that idea at all, it sounds like a very crappy implementation. I also don't like the idea of set_exception_handler unless i can sett the function to be a method of an object. The reason for this is that if I designate a function to handle the exceptions this will be the first function in the application. Everything else is a method of an object. </p> <p>Hopefully I've provided enough details about the scenario. I'm trying to keep this clean and follow best practices. This code will be going OSS so I don't feel like writing it 10 times :)</p>
557,109
3
1
null
2009-02-17 14:27:55.063 UTC
16
2015-12-02 15:58:27.15 UTC
2012-12-23 21:31:53.623 UTC
null
168,868
Syntax
62,551
null
1
18
php|exception
12,698
<ol> <li>Run your web requests through a <a href="https://stackoverflow.com/questions/20277102/proper-separation-difference-between-index-php-and-front-controller/20299496#20299496">Front Controller script</a></li> <li><p>call <a href="http://www.php.net/set_error_handler" rel="nofollow noreferrer"><code>set_exception_handler</code></a> early in execution (don't forget to account for <code>error_reporting()</code>). <code>set_exception_handler</code> takes as its paramter what php calls a <a href="http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback" rel="nofollow noreferrer">"callback"</a>. You can pass an object method like so:</p> <pre><code>// $object-&gt;methodName() will be called on errors set_exception_handler(array($object, 'methodName')); </code></pre></li> <li><p>Wrap your dispatching code with <code>try/catch</code> to catch any code that DOES throw exceptions. The catch part of your code will catch all your own codes' exceptions, plus <em>some</em> php errors that didn't generate an exception natively (eg <code>fopen</code> or something), thanks to your <code>set_exception_handler</code> call above. The php manual states:</p> <blockquote> <p>The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.</p> </blockquote></li> <li><p>Log errors as necessary.</p></li> <li><p>Create an error page template (the "View") that operates on an Exception object (the "Model") and pretty prints the whole stack trace for you, in development. Create a different template that goes to production. Branch on your environment, for example:</p> <pre><code>catch(Exception $e) { // log error as necessary here. if("in developement") { // $e would be available to your template at this point include "errortemplates/dev.php"; } else { include "errortemplates/prod.php"; } } </code></pre></li> </ol>
834,395
Python ASCII Graph Drawing
<p>I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.</p> <p>I saw NetworkX and igraph, but didn't see a way to output to ascii.</p> <p>Do you have experience in this?</p> <p>Thanks a lot!</p> <p>Patrick</p> <p>EDIT 1: I actually found a library doing what I need, but it's in perl <a href="http://bloodgate.com/perl/graph/manual/output.html" rel="noreferrer">Graph::Easy</a> . I could call the code from python but I don't like the idea too much... still looking for a python solution :)</p>
834,578
3
0
null
2009-05-07 12:33:34.307 UTC
8
2009-12-31 00:47:32.937 UTC
2009-05-07 14:05:58.127 UTC
null
94,404
null
94,404
null
1
29
python|graph|ascii
18,573
<p>When you say 'simple network graph in ascii', do you mean something like this?</p> <pre><code>.===. .===. .===. .===. | a |---| b |---| c |---| d | '===' '===' '---' '===' </code></pre> <p>I suspect there are probably better ways to display whatever information it is that you have than to try and draw it on the console. If it's just a pipeline, why not just print out:</p> <pre><code>a-b-c-d </code></pre> <p>If you're sure this is the route, one thing you could try would be to generate a decent graph using <a href="http://matplotlib.sourceforge.net" rel="nofollow noreferrer">Matplotlib</a> and then post the contents to one of <a href="https://www.ohloh.net/tags/ascii/python" rel="nofollow noreferrer">the many image-to-ascii converters</a> you can find on the web.</p>
493,886
SQL Server Automated Backups
<p>What are the recommendations of software products for creating automated backups of SQL Server 2008 databases?</p> <p>The backup should happen without taking the database offline/detatching.</p>
493,903
3
1
null
2009-01-29 23:03:47.917 UTC
25
2018-01-16 14:51:27.263 UTC
null
null
null
blu
54,612
null
1
30
database|sql-server-2008|backup
47,168
<p>I would recommend just creating a maintenance plan in SQL Server to handle the backups, it can be configured to backup to a specified location at specified times, without taking the databases offline, and will handle your incremental backup cleanup. </p> <p><a href="http://msdn.microsoft.com/en-us/library/ms189715.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms189715.aspx</a></p>
542,895
How to read .rej files, i.e
<p>I'm having trouble applying a patch to my source tree, and it's not the usual <code>-p</code> stripping problem. <code>patch</code> is able to find the file to patch.</p> <p>Specifically, my question is how to read / interpret the <code>.rej</code> files <code>patch</code> creates when it fails on a few hunks. Most discussions of <code>patch</code>/<code>diff</code> I have seen don't include this.</p>
543,045
3
0
null
2009-02-12 19:38:51.627 UTC
11
2016-11-28 01:25:03.38 UTC
2011-08-17 13:11:13.987 UTC
null
341,106
Rudy
null
null
1
30
diff|patch
29,040
<p>A simple example:</p> <pre><code>$ echo -e "line 1\nline 2\nline 3" &gt; a $ sed -e 's/2/b/' &lt;a &gt;b $ sed -e 's/2/c/' &lt;a &gt;c $ diff a b &gt; ab.diff $ patch c &lt; ab.diff $ cat c.rej *************** *** 2 - line 2 --- 2 ----- + line b </code></pre> <p>As you can see: The old file contains line 2 and the new file <em>should</em> contain line b. However, it actually contains line c (that's not visible in the reject file).</p> <p>In fact, the easiest way to resolve such problems is to take the diff fragment from the .diff/.patch file, insert it at the appropriate place in the file to be patched and then compare the code by hand to figure out, what lines actually cause the conflict.</p> <p>Or - alternatively: Get the original file (unmodified), patch it and run a three way merge on the file.</p>
1,162,529
JavaScript replace/regex
<p>Given this function:</p> <pre><code>function Repeater(template) { var repeater = { markup: template, replace: function(pattern, value) { this.markup = this.markup.replace(pattern, value); } }; return repeater; }; </code></pre> <p>How do I make <code>this.markup.replace()</code> replace globally? Here's the problem. If I use it like this:</p> <pre><code>alert(new Repeater("$TEST_ONE $TEST_ONE").replace("$TEST_ONE", "foobar").markup); </code></pre> <p>The alert's value is "foobar $TEST_ONE".</p> <p>If I change <code>Repeater</code> to the following, then nothing in replaced in Chrome:</p> <pre><code>function Repeater(template) { var repeater = { markup: template, replace: function(pattern, value) { this.markup = this.markup.replace(new RegExp(pattern, "gm"), value); } }; return repeater; }; </code></pre> <p>...and the alert is <code>$TEST_ONE $TEST_ONE</code>.</p>
1,162,538
3
0
null
2009-07-22 00:56:48.587 UTC
27
2013-06-30 15:58:59.757 UTC
2013-06-30 15:58:59.757 UTC
null
2,287,470
null
11,574
null
1
139
javascript|regex|replace
393,638
<p>You need to double escape any RegExp characters (once for the slash in the string and once for the regexp):</p> <pre><code> "$TESTONE $TESTONE".replace( new RegExp("\\$TESTONE","gm"),"foo") </code></pre> <p>Otherwise, it looks for the end of the line and 'TESTONE' (which it never finds).</p> <p>Personally, I'm not a big fan of building regexp's using strings for this reason. The level of escaping that's needed could lead you to drink. I'm sure others feel differently though and like drinking when writing regexes.</p>
1,052,148
Group by & count function in sqlalchemy
<p>I want a "group by and count" command in sqlalchemy. How can I do this?</p>
4,086,229
3
1
null
2009-06-27 05:10:43.257 UTC
37
2022-06-24 07:11:18.46 UTC
2019-07-15 17:31:22.467 UTC
null
2,681,632
null
309,111
null
1
163
python|group-by|count|sqlalchemy
171,043
<p>The <a href="http://www.sqlalchemy.org/docs/orm/tutorial.html#counting" rel="noreferrer">documentation on counting</a> says that for <code>group_by</code> queries it is better to use <code>func.count()</code>:</p> <pre><code>from sqlalchemy import func session.query(Table.column, func.count(Table.column)).group_by(Table.column).all() </code></pre>
6,468,896
Why is orig_eax provided in addition to eax?
<p>Why is the <code>orig_eax</code> member included in <code>sys/user.h</code>'s <code>struct user_regs_struct</code>?</p>
6,469,069
1
0
null
2011-06-24 14:02:57.033 UTC
11
2011-06-28 01:06:38.423 UTC
2011-06-24 18:48:59.747 UTC
null
36,723
null
149,482
null
1
20
c|linux|linux-kernel|cpu-registers
7,964
<p>Because it was in <code>struct pt_regs</code>, which is .... <a href="http://tomoyo.sourceforge.jp/cgi-bin/lxr/source/arch/x86/include/asm/user_32.h#L77">http://tomoyo.sourceforge.jp/cgi-bin/lxr/source/arch/x86/include/asm/user_32.h#L77</a></p> <pre><code> 73 * is still the layout used by user mode (the new 74 * pt_regs doesn't have all registers as the kernel 75 * doesn't use the extra segment registers) </code></pre> <p>So, a lot of user-space utilities expect an <code>orig_eax</code> field here, so it is included in <code>user_regs_struct</code> too (to be compatible with older debuggers and <code>ptrace</code>rs)</p> <p>Next question is "Why is the <code>orig_eax</code> member included in <code>struct pt_regs</code>?". </p> <p>It was added in linux 0.95 <a href="http://lxr.linux.no/#linux-old+v0.95/include/sys/ptrace.h#L44">http://lxr.linux.no/#linux-old+v0.95/include/sys/ptrace.h#L44</a>. I suggest this was done after some other unix with <code>pt_regs</code> struct. Comment in 0.95 says</p> <pre><code> 29 * this struct defines the way the registers are stored on the 30 * stack during a system call. </code></pre> <p>So, the place of <code>orig_eax</code> is defined by syscall interface. Here it is <a href="http://lxr.linux.no/#linux-old+v0.95/kernel/sys_call.s">http://lxr.linux.no/#linux-old+v0.95/kernel/sys_call.s</a></p> <pre><code> 17 * Stack layout in 'ret_from_system_call': 18 * ptrace needs to have all regs on the stack. 19 * if the order here is changed, it needs to be 20 * updated in fork.c:copy_process, signal.c:do_signal, 21 * ptrace.c ptrace.h 22 * 23 * 0(%esp) - %ebx ... 29 * 18(%esp) - %eax ... 34 * 2C(%esp) - orig_eax </code></pre> <p>Why do we need to save old <code>eax</code> twice? Because <code>eax</code> will be used for the return value of syscall (same file, a bit below):</p> <pre><code> 96_system_call: 97 cld 98 pushl %eax # save orig_eax 99 push %gs ... 102 push %ds 103 pushl %eax # save eax. The return value will be put here. 104 pushl %ebp ... 117 call _sys_call_table(,%eax,4) </code></pre> <p>Ptrace needs to be able to read both all registers state before syscall and the return value of syscall; but the return value is written to <code>%eax</code>. Then original <code>eax</code>, used before syscall will be lost. To save it, there is a <code>orig_eax</code> field.</p> <p>UPDATE: Thanks to R.. and great LXR, I did a full search of <code>orig_eax</code> in linux 0.95.</p> <p>It is used not only in ptrace, but also in <a href="http://lxr.linux.no/#linux-old+v0.95/kernel/signal.c#L152">do_signal</a> when restarting a syscall (if there is a syscall, ended with <code>ERESTARTSYS</code>)</p> <pre><code> 158 *(&amp;eax) = orig_eax; </code></pre> <p>UPDATE2: Linus <a href="http://lkml.org/lkml/2006/8/29/350">said</a> something interesting about it:</p> <blockquote> <p>It's important that ORIG_EAX be set to some value that is <em>not</em> a valid system call number, so that the system call restart logic (see the signal handling code) doesn't trigger.</p> </blockquote> <p>UPDATE3: <code>ptrace</code>r app (debugger) can change <code>orig_eax</code> to change system call number to be called: <a href="http://lkml.org/lkml/1999/10/30/82">http://lkml.org/lkml/1999/10/30/82</a> (in some versions of kernel, is was EIO to change in ptrace an ORIG_EAX)</p>
28,850,809
Disable deprecated warning in Symfony 2(.7)
<p>Since my <code>Symfony 2</code> update to <code>2.7</code>. I get a lot of deprecated erors in <code>PHPUnit</code> and <code>console</code> (message is clear by now). </p> <pre><code>ProjectX\ApiBundle\Tests\Controller\SectionsControllerTest::testPostDebug() The twig.form.resources configuration key is deprecated since version 2.6 and will be removed in 3.0. Use the twig.form_themes configuration key instead. </code></pre> <p>Any idea how to disable them for now? </p>
28,865,489
5
1
null
2015-03-04 09:28:32.02 UTC
7
2016-06-14 13:28:58.827 UTC
2015-03-04 09:41:49.913 UTC
null
2,270,041
null
897,360
null
1
32
php|symfony|symfony-2.7
32,866
<p>I have the same problem and solved it similar to the below link. Symfony declares to report all errors and overrides what you put in php.ini by design (otherwise it couldn't catch &amp; display nice stack traces for you). </p> <p>So, you'll need to <strong>override Symfony2's built-in error reporting by creating an <code>init()</code> function in your AppKernel.php and setting the error_reporting how you'd like there</strong>, along with (probably) some environment detection to make sure you don't display errors in production, for example:</p> <pre><code>// Add this to app/AppKernel.php public function init() { if ($this-&gt;debug) { ini_set('display_errors', 1); error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_STRICT &amp; ~E_DEPRECATED); } else { ini_set('display_errors', 0); } } </code></pre> <p>More details here (use Google Translate if you do not read Russian :) <a href="http://tokarchuk.ru/2012/12/disable-deprecated-warnings-in-symfony-2/">http://tokarchuk.ru/2012/12/disable-deprecated-warnings-in-symfony-2/</a> </p>
20,660,989
Max double slice sum
<p>Recently, I tried to solve the Max Double Slice Sum problem in codility which is a variant of max slice problem. My Solution was to look for a slice that has maximum value when its minimum value is taken out. So I implemented max slice, but on the current slice took out the minimum number.</p> <p>My score was 61 of 100 as it failed during some of the tests, mainly the tests on array including both negative and position numbers. </p> <p>Could you help me to figure out why the code failed or if there is a better solution for the problem?</p> <p>The problem is as follows:</p> <pre><code>A non-empty zero-indexed array A consisting of N integers is given. A triplet (X, Y, Z), such that 0 ≤ X &lt; Y &lt; Z &lt; N, is called a double slice. The sum of double slice (X, Y, Z) is the total of A[X + 1] + A[X + 2] + ... + A[Y − 1]+ A[Y + 1] + A[Y + 2] + ... + A[Z − 1]. For example, array A such that: A[0] = 3 A[1] = 2 A[2] = 6 A[3] = -1 A[4] = 4 A[5] = 5 A[6] = -1 A[7] = 2 contains the following example double slices: double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17, double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 − 1 = 16, double slice (3, 4, 5), sum is 0. The goal is to find the maximal sum of any double slice. Write a function: class Solution { public int solution(int[] A); } that, given a non-empty zero-indexed array A consisting of N integers, returns the maximal sum of any double slice. For example, given: A[0] = 3 A[1] = 2 A[2] = 6 A[3] = -1 A[4] = 4 A[5] = 5 A[6] = -1 A[7] = 2 the function should return 17, because no double slice of array A has a sum of greater than 17. Assume that: N is an integer within the range [3..100,000]; each element of array A is an integer within the range [−10,000..10,000]. Complexity: expected worst-case time complexity is O(N); expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). Elements of input arrays can be modified. Copyright 2009–2013 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. </code></pre> <p>And my code is as follows:</p> <pre><code>public class Solution { public int solution(int[] A) { int currentSliceTotal=0; Integer currentMin=null, SliceTotalBeforeMin =0; int maxSliceTotal= Integer.MIN_VALUE; for(int i= 1; i&lt;A.length-1; i++){ if( currentMin==null || A[i] &lt; currentMin ){ if(currentMin!=null ){ if(SliceTotalBeforeMin+currentMin &lt;0){ currentSliceTotal-=SliceTotalBeforeMin; } else { currentSliceTotal += currentMin; } } currentMin = A[i]; SliceTotalBeforeMin =currentSliceTotal; if( SliceTotalBeforeMin&lt;0){ SliceTotalBeforeMin = 0; currentMin = null; currentSliceTotal = 0; } } else { currentSliceTotal+= A[i]; } maxSliceTotal = Math.max(maxSliceTotal, currentSliceTotal); } return maxSliceTotal; } } </code></pre>
20,661,624
18
0
null
2013-12-18 14:37:02.843 UTC
10
2022-06-23 16:36:23.573 UTC
2017-11-26 11:58:32.923 UTC
null
2,333,458
null
2,486,546
null
1
19
java|algorithm
20,141
<p>If I have understood the problem correctly, you want to calculate the maximum sum subarray with one element missing.</p> <p>Your algorithm shall not work for the following case:</p> <pre><code> 1 1 0 10 -100 10 0 </code></pre> <p>In the above case, your algorithm shall identify <code>1, 1, 0, 10</code> as the maximum sum sub array and leave out <code>0</code> to give <code>12</code> as the output. However, you can have <code>1, 1, 0, 10, -100, 10</code> as the answer after leaving out <code>-100</code>.</p> <p>You can use a modified form of Kadane's algorithm that calculates the MAX Sum subarray ending at each index.</p> <ol> <li>For each index, calculate the <code>max_sum_ending_at[i]</code> value by using Kadane's algorithm in forward direction. </li> <li>For each index, calculate the <code>max_sum_starting_from[i]</code> value by using Kadane's algorithm in reverse direction. </li> <li><p>Iterate these arrays simultaneously and choose the 'Y' that has the maximum value of </p> <p>max_sum_ending_at[Y-1] + max_sum_starting_from[Y+1]</p></li> </ol>
56,196,973
Invalid value 'armeabi' in $(AndroidSupportedAbis). This ABI is no longer supported. Xamarin.Forms - VS2019
<p>I have a Mobile App built with Xamarin.Forms<br> when I am trying to upgrade my project from VS2017 to VS2019</p> <p>I get this error in <strong>Android Project</strong></p> <blockquote> <p>Invalid value 'armeabi' in $(AndroidSupportedAbis). This ABI is no longer supported. Please update your project properties </p> </blockquote> <p>I tried to delete <strong>bin</strong> and <strong>obj</strong> folders to force the project to rebuild everything, but the error still appears</p> <p><strong>Can I get an explanation about the error above and how to solve it?</strong></p> <p>Note: <strong>the error doesn't appear in VS2017</strong></p>
56,197,862
3
1
null
2019-05-18 07:43:44.85 UTC
3
2020-06-20 06:51:05.977 UTC
null
null
null
null
4,977,870
null
1
30
xamarin|xamarin.forms|xamarin.android|build-error|visual-studio-2019
22,364
<p><code>armeabi</code> is deprecated and your Android project should target <code>armeabi-v7a</code> and <code>arm64-v8a</code> at a minimum in your release builds destined for the Play Store.</p> <p>You can directly edit your <code>.csproj</code> and remove the <code>armeabi</code> from within the <code>AndroidSupportedAbis</code> tags:</p> <pre><code>&lt;AndroidSupportedAbis&gt;armeabi-v7a;arm64-v8a&lt;/AndroidSupportedAbis&gt; </code></pre> <p>Or you can open the Android Build settings in the IDE and it will auto-update it for you:</p> <ul> <li><a href="https://stackoverflow.com/a/54537615/4984832">Targeting 64 bit architectures on Xamarin Android</a></li> </ul>
5,964,661
detach one process from visual studio debugger
<p>My question is somewhat similar to this <a href="https://stackoverflow.com/questions/2671503/how-to-stop-debugging-or-detach-process-without-stopping-the-process">"How to stop debugging (or detach process) without stopping the process?"</a></p> <p>but i want to detach from one process.</p> <p>for instance, I have a windows form app which i also attach to a windows service. I want to detach from only service (detach all will remove debugging from all executions and hence i won't be able to debug other application).</p> <p>P.S: If possible please mention for visual studio 2008 and 2010.</p>
5,964,765
4
0
null
2011-05-11 13:00:09.697 UTC
7
2021-09-28 13:37:46.21 UTC
2017-05-23 11:55:07.73 UTC
null
-1
null
339,995
null
1
62
visual-studio|debugging
18,554
<p>In the Processes window (Debug -> Windows -> Processes), right-click on the name of the process you want to detach, and on the shortcut menu, click Detach Process.</p>
64,005,844
Is it possible to delete a pull-request on BitBucket?
<p>I cannot find an option to delete a PR on BitBucket. Am I overlooking something or it's really not possible?</p>
64,006,136
5
2
null
2020-09-22 08:26:51.587 UTC
1
2021-12-01 13:54:00.623 UTC
null
null
null
null
1,941,537
null
1
26
bitbucket
45,163
<p>As per the link <a href="https://stackoverflow.com/users/3001761/jonrsharpe">jonrsharpe</a> mentioned, to the right of the merge button there are 3 dots. Under that menu you should have a delete option if you have permission to delete.</p> <p>This is available only for BitBucket Server, not on BitBucket.org. In BitBucket.org there is no option to delete the PR.</p> <p><a href="https://i.stack.imgur.com/qYUM3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qYUM3.png" alt="BitBucketDeletePullRequst" /></a></p>
29,442,993
Which are the available domain operators in Openerp / Odoo?
<p>I know few operator in openerp domain. I dont get the details of available domains and their explanation. Particularly for these negation domains. Can anyone tell me the detail list?</p>
29,443,027
2
0
null
2015-04-04 05:14:15.823 UTC
36
2017-11-07 10:38:02.26 UTC
2017-11-07 10:38:02.26 UTC
null
4,891,717
null
4,748,376
null
1
37
openerp|operators|odoo-8
59,270
<p>This gives a overview:</p> <p>List of <strong>Domain</strong> operators: <code>!</code> (Not), <code>|</code> (Or), <code>&amp;</code> (And)</p> <p>List of <strong>Term</strong> operators: <code>'=', '!=', '&lt;=', '&lt;', '&gt;', '&gt;=', '=?', '=like', '=ilike', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of'</code></p> <p><strong>Usage</strong>:</p> <p>Input records:</p> <p>Record 1: <code>Openerp</code></p> <p>Record 2: <code>openerp</code></p> <p>Record 3: <code>Opensource</code></p> <p>Record 4: <code>opensource</code></p> <p>Record 5: <code>Open</code></p> <p>Record 6: <code>open</code></p> <p>Record 7: <code>Odoo</code></p> <p>Record 8: <code>odoo</code></p> <p>Record 9: <code>Odooopenerp</code></p> <p>Record 10: <code>OdooOpenerp</code></p> <p><strong>'like':</strong> <code>[('input', 'like', 'open')]</code> - Returns case sensitive (wildcards - '%open%') search. </p> <p>O/p: open, opensource, openerp, Odooopenerp</p> <p><strong>'not like':</strong> <code>[('input', 'not like', 'open')]</code> - Returns results not matched with case sensitive (wildcards - '%open%') search. </p> <p>O/p: Openerp, Opensource, Open, Odoo, odoo, OdooOpenerp</p> <p><strong>'=like':</strong> <code>[('name', '=like', 'open')]</code> - Returns exact (= 'open') case sensitive search. </p> <p>O/p: open</p> <p><strong>'ilike':</strong> <code>[('name', 'ilike', 'open')]</code> - Returns exact case insensitive (wildcards - '%open%') search. </p> <p>O/p: Openerp, openerp, Opensource, opensource, Open, open, Odooopenerp, OdooOpenerp</p> <p><strong>'not ilike':</strong> <code>[('name', 'not ilike', 'open')]</code> - Returns results not matched with exact case insensitive (wildcards - '%open%') search. </p> <p>O/p: Odoo, odoo</p> <p><strong>'=ilike':</strong> <code>[('name', '=ilike', 'open')]</code> - Returns exact (= 'open' or 'Open') case insensitive search. </p> <p>O/p: Open, open</p> <p><strong>'=?':</strong></p> <p>name = 'odoo' parent_id = False <code>[('name', 'like', name), ('parent_id', '=?', parent_id)]</code> - Returns name domain result &amp; True</p> <p>name = 'odoo' parent_id = 'openerp' <code>[('name', 'like', name), ('parent_id', '=?', parent_id)]</code> - Returns name domain result &amp; parent_id domain result</p> <p><strong>'=?'</strong> is a short-circuit that makes the term TRUE if right is None or False, <code>'=?'</code> behaves like <code>'='</code> in other cases</p> <p><strong>'in':</strong> <code>[('value1', 'in', ['value1', 'value2'])]</code> - in operator will check the value1 is present or not in list of right term</p> <p><strong>'not in':</strong> <code>[('value1', 'not in', ['value2'])]</code> - not in operator will check the value1 is not present in list of right term While these 'in' and 'not in' works with list/tuple of values, the latter <code>'='</code> and <code>'!='</code> works with string</p> <p><strong>'=':</strong> value = 10 <code>[('value','=',value)]</code> - term left side has 10 in db and term right our value 10 will match</p> <p><strong>'!=':</strong> value = 15 <code>[('value','!=',value)]</code> - term left side has 10 in db and term right our value 10 will not match</p> <p><strong>'child_of':</strong> parent_id = '1' #Agrolait 'child_of': <code>[('partner_id', 'child_of', parent_id)]</code> - return left and right list of partner_id for given parent_id</p> <p><strong>'&lt;=', '&lt;', '>', '>=':</strong> These operators are largely used in openerp for comparing dates - <code>[('date', '&gt;=', date_begin), ('date', '&lt;=', date_end)]</code>. You can use these operators to compare int or float also.</p>
50,485,988
Is there a way to keep fragment alive when using BottomNavigationView with new NavController?
<p>I'm trying to use the new navigation component. I use a BottomNavigationView with the navController : <code>NavigationUI.setupWithNavController(bottomNavigation, navController)</code></p> <p>But when I'm switching fragments, they are each time destroy/create even if they were previously used.</p> <p>Is there a way to keep alive our main fragments link to our BottomNavigationView?</p>
51,684,125
10
1
null
2018-05-23 10:28:01.027 UTC
66
2022-07-07 07:38:19.457 UTC
2021-01-25 17:59:33.673 UTC
null
6,138,892
null
9,833,782
null
1
134
android|navigation|bottomnavigationview
44,756
<p>Try this.</p> <h3>Navigator</h3> <p>Create custom navigator.</p> <pre class="lang-kotlin prettyprint-override"><code>@Navigator.Name("custom_fragment") // Use as custom tag at navigation.xml class CustomNavigator( private val context: Context, private val manager: FragmentManager, private val containerId: Int ) : FragmentNavigator(context, manager, containerId) { override fun navigate(destination: Destination, args: Bundle?, navOptions: NavOptions?) { val tag = destination.id.toString() val transaction = manager.beginTransaction() val currentFragment = manager.primaryNavigationFragment if (currentFragment != null) { transaction.detach(currentFragment) } var fragment = manager.findFragmentByTag(tag) if (fragment == null) { fragment = destination.createFragment(args) transaction.add(containerId, fragment, tag) } else { transaction.attach(fragment) } transaction.setPrimaryNavigationFragment(fragment) transaction.setReorderingAllowed(true) transaction.commit() dispatchOnNavigatorNavigated(destination.id, BACK_STACK_DESTINATION_ADDED) } } </code></pre> <h3>NavHostFragment</h3> <p>Create custom NavHostFragment.</p> <pre class="lang-kotlin prettyprint-override"><code>class CustomNavHostFragment: NavHostFragment() { override fun onCreateNavController(navController: NavController) { super.onCreateNavController(navController) navController.navigatorProvider += PersistentNavigator(context!!, childFragmentManager, id) } } </code></pre> <h3>navigation.xml</h3> <p>Use custom tag instead of fragment tag. </p> <pre class="lang-xml prettyprint-override"><code>&lt;navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/navigation" app:startDestination="@id/navigation_first"&gt; &lt;custom_fragment android:id="@+id/navigation_first" android:name="com.example.sample.FirstFragment" android:label="FirstFragment" /&gt; &lt;custom_fragment android:id="@+id/navigation_second" android:name="com.example.sample.SecondFragment" android:label="SecondFragment" /&gt; &lt;/navigation&gt; </code></pre> <h3>activity layout</h3> <p>Use CustomNavHostFragment instead of NavHostFragment.</p> <pre class="lang-xml prettyprint-override"><code>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;fragment android:id="@+id/nav_host_fragment" android:name="com.example.sample.CustomNavHostFragment" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@+id/bottom_navigation" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/navigation" /&gt; &lt;com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottom_navigation" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:menu="@menu/navigation" /&gt; &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt; </code></pre> <hr> <h2>Update</h2> <p>I created sample project. <a href="https://github.com/STAR-ZERO/navigation-keep-fragment-sample" rel="noreferrer">link</a></p> <p>I don't create custom NavHostFragment. I use <code>navController.navigatorProvider += navigator</code>.</p>
6,014,702
How do I detect "shift+enter" and generate a new line in Textarea?
<p>Currently, if the person presses <kbd>enter</kbd> inside the text area, the form will submit.<br> Good, I want that.</p> <p>But when they type <kbd>shift</kbd> + <kbd>enter</kbd>, I want the textarea to move to the next line: <code>\n</code> </p> <p>How can I do that in <code>JQuery</code> or plain JavaScript as simple as possible?</p>
6,014,917
19
6
null
2011-05-16 08:19:13.487 UTC
32
2022-04-28 04:05:15.693 UTC
2011-05-16 08:49:36.78 UTC
null
447,356
null
179,736
null
1
173
javascript|jquery|html|css
143,967
<h1>Better use simpler solution:</h1> <p>Tim's solution below is better I suggest using that: <a href="https://stackoverflow.com/a/6015906/4031815">https://stackoverflow.com/a/6015906/4031815</a></p> <hr> <h1>My solution</h1> <p>I think you can do something like this.. </p> <p><strong>EDIT :</strong> Changed the code to work irrespective of the caret postion</p> <p>First part of the code is to get the caret position.</p> <p>Ref: <a href="https://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea">How to get the caret column (not pixels) position in a textarea, in characters, from the start?</a></p> <pre><code>function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; } </code></pre> <p>And then replacing the textarea value accordingly when <kbd>Shift</kbd> + <kbd>Enter</kbd> together , submit the form if <kbd>Enter</kbd> is pressed alone. </p> <pre><code>$('textarea').keyup(function (event) { if (event.keyCode == 13) { var content = this.value; var caret = getCaret(this); if(event.shiftKey){ this.value = content.substring(0, caret - 1) + "\n" + content.substring(caret, content.length); event.stopPropagation(); } else { this.value = content.substring(0, caret - 1) + content.substring(caret, content.length); $('form').submit(); } } }); </code></pre> <p>Here is a <a href="http://jsfiddle.net/jishnuap/zYEMv/" rel="noreferrer">demo</a></p>
46,305,459
Sequelize model references vs associations
<p>Just starting to use Sequelize and I've setup a bunch of models and seeds, but I can't figure out references vs associations. I don't see the use case for references if they even do what I think they do, but I couldn't find a good explanation in the docs.</p> <p>Is this redundant having references and associations?</p> <pre><code>module.exports = (sequelize, DataTypes) =&gt; { const UserTask = sequelize.define('UserTask', { id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, userId: { type: DataTypes.UUID, references: { // &lt;--- is this redundant to associate model: 'User', key: 'id' } } // ... removed for brevity }, { classMethods: { associate: models =&gt; { &lt;--- makes references redundant? UserTask.belongsTo(models.User, { onDelete: 'CASCADE', foreignKey: { fieldName: 'userId', allowNull: true, require: true }, targetKey: 'id' }); } } } ); return UserTask; }; </code></pre>
49,140,096
1
1
null
2017-09-19 16:27:03.94 UTC
12
2020-12-03 09:06:02.003 UTC
2020-12-03 09:06:02.003 UTC
null
6,463,558
null
1,148,107
null
1
28
node.js|sequelize.js
19,573
<p>Using <code>references</code> you create a reference to another table, without adding any constraints, or associations. Which means that is just a way of <strong>signaling</strong> the database that this table has a reference to another.</p> <p>Creating an <code>association</code> will add a foreign key constraint to the attributes. And the you can perform all the magic behind it the association functions. i.e <code>User.getTasks();</code></p> <p>More info about <code>references</code> here: <a href="https://sequelize.readthedocs.io/en/latest/docs/associations/#foreign-keys_1" rel="noreferrer">https://sequelize.readthedocs.io/en/latest/docs/associations/#foreign-keys_1</a></p> <p>About <code>association</code> here: <a href="http://docs.sequelizejs.com/manual/tutorial/associations.html" rel="noreferrer">http://docs.sequelizejs.com/manual/tutorial/associations.html</a></p>
44,239,822
urllib.request.urlopen(url) with Authentication
<p>I've been playing with beautiful soup and parsing web pages for a few days. I have been using a line of code which has been my saviour in all the scripts that I write. The line of code is : </p> <pre><code>r = requests.get('some_url', auth=('my_username', 'my_password')). </code></pre> <p>BUT ...</p> <p>I want to do the same thing with (OPEN A URL WITH AUTHENTICATION):</p> <pre><code>(1) sauce = urllib.request.urlopen(url).read() (1) (2) soup = bs.BeautifulSoup(sauce,"html.parser") (2) </code></pre> <p>I'm not able to open a url and read, the webpage which needs authentication. How do I achieve something like this :</p> <pre><code> (3) sauce = urllib.request.urlopen(url, auth=(username, password)).read() (3) instead of (1) </code></pre>
44,239,906
4
0
null
2017-05-29 10:07:37.62 UTC
6
2022-05-26 17:06:47.337 UTC
null
null
null
user7800892
null
null
1
35
python|python-3.x|url|beautifulsoup|request
76,462
<p>Have a look at the <a href="https://docs.python.org/3.1/howto/urllib2.html#id6" rel="noreferrer">HOWTO Fetch Internet Resources Using The urllib Package</a> from the official docs:</p> <pre><code># create a password manager password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. # If we knew the realm, we could use it instead of None. top_level_url = "http://example.com/foo/" password_mgr.add_password(None, top_level_url, username, password) handler = urllib.request.HTTPBasicAuthHandler(password_mgr) # create "opener" (OpenerDirector instance) opener = urllib.request.build_opener(handler) # use the opener to fetch a URL opener.open(a_url) # Install the opener. # Now all calls to urllib.request.urlopen use our opener. urllib.request.install_opener(opener) </code></pre>
43,971,138
Python - Plotting colored grid based on values
<p>I have been searching here and on the net. I found somehow close questions/answers to what I want, but still couldn't reach to what I'm looking for.</p> <p>I have an array of for example, 100 values. The values are in the range from 0 to 100. I want to plot this array as a grid, filling the squares according to the values in the array. </p> <p>The solutions I found so far are like the followings: </p> <p><a href="https://stackoverflow.com/questions/19586828/drawing-grid-pattern-in-matplotlib">Drawing grid pattern in matplotlib</a></p> <p>and</p> <p><a href="https://stackoverflow.com/questions/10194482/custom-matplotlib-plot-chess-board-like-table-with-colored-cells">custom matplotlib plot : chess board like table with colored cells</a></p> <p>In the examples I mentioned, the ranges of the colors vary and are not fixed.</p> <p>However, what I am wondering about, is whether I can set the ranges for specific values and colors. For example, if the values are between 10 and 20, let the color of the grid square be red. else if the values are between 20 and 30, let the color be blue. etc.</p> <p>How this could be achieved in python? </p>
43,971,236
2
0
null
2017-05-15 03:19:41.747 UTC
9
2017-11-10 21:47:52.967 UTC
2017-05-23 11:47:24.667 UTC
null
-1
null
6,203,203
null
1
20
python|matplotlib|plot|colors|grid
57,822
<p>You can create a <a href="https://matplotlib.org/devdocs/api/_as_gen/matplotlib.colors.ListedColormap.html" rel="noreferrer">ListedColormap</a> for your custom colors and color <a href="http://matplotlib.org/devdocs/api/_as_gen/matplotlib.colors.BoundaryNorm.html" rel="noreferrer">BoundaryNorms</a> to threshold the values.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib import colors import numpy as np data = np.random.rand(10, 10) * 20 # create discrete colormap cmap = colors.ListedColormap(['red', 'blue']) bounds = [0,10,20] norm = colors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots() ax.imshow(data, cmap=cmap, norm=norm) # draw gridlines ax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2) ax.set_xticks(np.arange(-.5, 10, 1)); ax.set_yticks(np.arange(-.5, 10, 1)); plt.show() </code></pre> <p>Resulting in; <a href="https://i.stack.imgur.com/NOKwp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NOKwp.png" alt="Plot with BoundaryNorms"></a></p> <p>For more, you can check this <a href="http://matplotlib.org/examples/api/colorbar_only.html" rel="noreferrer">matplotlib example</a>.</p>
19,643,234
Fill region between two loess-smoothed lines in R with ggplot
<p>I'd like to know how to fill the area between to loess-smoothed lines in ggplot.</p> <p>The following data frame is used for the pictures:</p> <pre><code> x y ymin ymax grp ydiff 1 1 3.285614 3.285614 10.14177 min 6.8561586 2 1 10.141773 3.285614 10.14177 max 6.8561586 3 2 5.061879 5.061879 11.24462 min 6.1827368 4 2 11.244615 5.061879 11.24462 max 6.1827368 5 3 8.614408 8.614408 13.45030 min 4.8358931 6 3 13.450301 8.614408 13.45030 max 4.8358931 7 4 6.838143 6.838143 12.34746 min 5.5093150 8 4 12.347458 6.838143 12.34746 max 5.5093150 9 5 10.390673 10.390673 14.55314 min 4.1624713 10 5 14.553144 10.390673 14.55314 max 4.1624713 11 6 12.166937 12.166937 15.65599 min 3.4890495 12 6 15.655987 12.166937 15.65599 max 3.4890495 13 7 13.943202 13.943202 16.75883 min 2.8156277 14 7 16.758830 13.943202 16.75883 max 2.8156277 15 8 5.950011 5.950011 11.79604 min 5.8460259 16 8 11.796037 5.950011 11.79604 max 5.8460259 17 9 17.495731 17.495731 18.96452 min 1.4687841 18 9 18.964515 17.495731 18.96452 max 1.4687841 19 10 15.719466 15.719466 17.86167 min 2.1422059 20 10 17.861672 15.719466 17.86167 max 2.1422059 21 11 19.271996 19.271996 20.06736 min 0.7953623 22 11 20.067358 19.271996 20.06736 max 0.7953623 </code></pre> <p>Following source produces a figure with normal lines (not smoothed):</p> <pre><code>ggplot(intdf) + geom_point(aes(x=x, y=y, colour=grp)) + geom_ribbon(aes(x=x, ymin=ymin, ymax=ymax), fill="grey", alpha=.4) + geom_line(aes(x=x, y=y, colour=grp)) </code></pre> <p>where x and y are continuous numeric values. ymin and ymax each contain the y-values from the green and red line at position x.</p> <p><img src="https://i.stack.imgur.com/2fx2M.png" alt="Two normal geom_line lines with geom_ribbon filled area"></p> <p>Now I'd like to smoothen the lines. I simply do this with following code:</p> <pre><code>ggplot(intdf) + stat_smooth(aes(x=x, y=ymin, colour="min"), method="loess", se=FALSE) + stat_smooth(aes(x=x, y=ymax, colour="max"), method="loess", se=FALSE) </code></pre> <p>which gives following plot:</p> <p><img src="https://i.stack.imgur.com/pIiKh.png" alt="Two smoothed lines without filled region"></p> <p>But I did not manage to fill the area between these two lines. I tried to fit a loess-model and use the predicted values, but I guess I completely used the wrong predictors.</p> <p>Who could tell me how to fill the region between the smoothed lines?</p> <p>Thanks in advance Daniel</p>
19,644,663
2
0
null
2013-10-28 19:15:47.807 UTC
8
2021-07-19 06:05:32.783 UTC
2013-10-28 19:27:26.647 UTC
null
2,094,622
null
2,094,622
null
1
22
r|ggplot2|fill|smoothing|loess
11,285
<p>A possible solution where the loess smoothed data is grabbed from the plot object and used for the <code>geom_ribbon</code>:</p> <pre><code># create plot object with loess regression lines g1 &lt;- ggplot(df) + stat_smooth(aes(x = x, y = ymin, colour = "min"), method = "loess", se = FALSE) + stat_smooth(aes(x = x, y = ymax, colour = "max"), method = "loess", se = FALSE) g1 # build plot object for rendering gg1 &lt;- ggplot_build(g1) # extract data for the loess lines from the 'data' slot df2 &lt;- data.frame(x = gg1$data[[1]]$x, ymin = gg1$data[[1]]$y, ymax = gg1$data[[2]]$y) # use the loess data to add the 'ribbon' to plot g1 + geom_ribbon(data = df2, aes(x = x, ymin = ymin, ymax = ymax), fill = "grey", alpha = 0.4) </code></pre> <p><img src="https://i.stack.imgur.com/WgFqc.png" alt="enter image description here"> </p>
41,111,227
How can a Slack bot detect a direct message vs a message in a channel?
<p>TL;DR: Via the Slack APIs, how can I differentiate between a message in a channel vs a direct message?</p> <p>I have a working Slack bot using the RTM API, let's call it Edi. And it works great as long as all commands start with "@edi"; e.g. "@edi help". It currently responses to any channel it's a member of and direct messages. However, I'd like to update the bot so that when it's a direct message, there won't be a need to start a command with "@edi"; e.g. "@edi help" in a channel, but "help" in a direct message. I don't see anything specific to differentiate between the two, but I did try using the channel.info endpoint and counting the number of people in "members"; however, this method only works on public channel. For private channels and direct messages, the endpoint returns an "channel_not_found" error.</p> <p>Thanks in advance.</p>
42,013,042
4
0
null
2016-12-12 23:11:24.66 UTC
5
2019-01-23 20:30:08.793 UTC
null
null
null
null
1,521,963
null
1
28
slack-api
13,089
<p>I talked to James at Slack and he gave me a simply way to determine if a message is a DM or not; if a channel ID begins with a:</p> <ul> <li>C, it's a public channel</li> <li>D, it's a DM with the user</li> <li>G, it's either a private channel or multi-person DM</li> </ul> <p>However, these values aren't set in stone and could change at some point, or be added to.</p> <p>So if that syntax goes away, another way to detect a DM to use both channels.info and groups.info. If they both return “false” for the “ok” field, then you know it’s a DM.</p> <p>Note:</p> <ul> <li>channels.info is for public channels only</li> <li>groups.info is for private channels and multi-person DMs only</li> </ul> <p>Bonus info: Once you detect a that a message is a DM, use either the user ID or channel ID and search for it in the results of im.list; if you find it, then you’ll know it’s a DM to the bot.</p> <ul> <li>“id” from im.list is the channel ID</li> <li>“user” from im.list is the user ID from the person DM’ing with the bot</li> <li>You don’t pass in the bot’s user ID, because it’s extracted from the token</li> </ul>
33,382,925
What is the difference between data-sly-use, data-sly-resource, data-sly-include, and data-sly-template?
<p>What is the difference between: <code>data-sly-use</code>, <code>data-sly-resource</code>, <code>data-sly-include</code>, and <code>data-sly-template</code>? I am reading the doc on <code>Sightly</code> <code>AEM</code> and I am super confused.</p> <p>As far as I can see:</p> <ul> <li><code>data-sly-use</code> is used to add <code>js/java</code> files to render with the doc</li> <li><code>data-sly-resource</code> is used to inject components</li> <li><code>data-sly-include</code> is used to include other html files (?***?)</li> </ul> <p>And, data-sly-template is confusing, as in:</p> <pre><code>&lt;div data-sly-use.nav="navigation.js"&gt;${nav.foo}&lt;/div&gt; &lt;section data-sly-include="path/to/template.html"&gt;&lt;/section&gt; &lt;template data-sly-template.one&gt;blah&lt;/template&gt; &lt;div data-sly-call="${one}"&gt;&lt;/div&gt; </code></pre>
33,395,263
2
0
null
2015-10-28 04:29:00.6 UTC
8
2019-01-23 09:08:56.377 UTC
2016-10-05 22:58:21.557 UTC
null
1,314,132
null
1,887,791
null
1
19
aem|sightly
39,453
<p>As you already said: </p> <ul> <li><em>data-sly-use</em> "is used to add js/java". You declare component-beans with this statement for instance. </li> <li><em>data-sly-resource</em> you can override a resource-type for a included file.</li> <li><em>data-sly-include</em> includes other html files as the name suggests. </li> <li><em>data-sly-template</em> you declare templates which can later be 'called' with <em>data-sly-call</em>.</li> </ul> <p>Please refere to the official specs for more informations. there are several examples for each tag:</p> <p><a href="https://github.com/Adobe-Marketing-Cloud/sightly-spec/blob/master/SPECIFICATION.md">https://github.com/Adobe-Marketing-Cloud/sightly-spec/blob/master/SPECIFICATION.md</a></p>
31,140,590
How to line left justify label and entry boxes in Tkinter grid
<p>I'm still pretty new to Tkinter and Classes, but I am trying to left justify labels and entry boxes each within their own column of a Tkinter grid. I am using <code>Justify=LEFT</code>, but it seems to have no impact as the labels look centered and the entry boxes start where the label ends.</p> <pre><code>from Tkinter import * class LabeledEntry(Frame): def __init__(self, parent, *args, **kargs): text = kargs.pop("text") Frame.__init__(self, parent) Label(self, text=text, justify=LEFT).grid(column=0,row=0) Entry(self, justify=LEFT, *args, **kargs).grid(column=1, row=0) class User_Input: def __init__(self, parent): fields = ['Text Label 1', 'This is the text Label 2'] GUIFrame =Frame(parent) GUIFrame.pack(expand=True, anchor=NW) parent.minsize(width=350, height=325) field_index = 1 for field in fields: self.field = LabeledEntry(GUIFrame, text=field) self.field.grid(column=0, row=field_index) field_index += 1 self.Button2 = Button(parent, text='exit', command= parent.quit) self.Button2.place(x=25, y=300) root = Tk() MainFrame =User_Input(root) root.mainloop() </code></pre>
31,142,512
2
0
null
2015-06-30 14:07:42.583 UTC
1
2019-07-25 16:13:31.017 UTC
null
null
null
null
2,242,044
null
1
9
python|python-2.7|tkinter
41,791
<p>I think your problem lies in the fact that each time you create a new instance of <code>LabeledFrame</code>, you are placing both the <code>Entry</code> &amp; <code>Label</code> within the same <code>Frame</code>. </p> <p>The <code>grid</code> settings for this <code>Frame</code> are separate from any other <code>Frame</code>, so it is impossible for <code>LabeledFrame</code>s to align columns as they do not have the same values for column widths. </p> <p>Normally to accomplish what you are after you would simply put <code>sticky = W</code> in the <code>grid</code> options for the <code>Entry</code> widget to left-justify the contents of the cell. However, this will only work for each individual <code>Frame</code>, leaving the contents of each separate <code>LabeledFrame</code> out of alignment.</p> <p>Easiest way to fix this without changing much code:</p> <p>You'll want to add a line to your <code>for</code> loop. If you specify a large minimum-width of the column that <code>self.field</code>'s <code>Frame</code> is inserted into, you can be sure that things will align how you want them to. I've also added config options to the <code>grid</code> calls within the <code>LabeledEntry</code> class: <code>sticky = W</code> for the <code>Label</code> &amp; <code>sticky = E</code> for the <code>Entry</code>. </p> <p>Try this out and see if it solves your problem. If you would like the column to take less space simply reduce <code>minsize</code>.</p> <pre><code>from Tkinter import * class LabeledEntry(Frame): def __init__(self, parent, *args, **kargs): text = kargs.pop("text") Frame.__init__(self, parent) Label(self, text=text, justify=LEFT).grid(sticky = W, column=0,row=0) Entry(self, *args, **kargs).grid(sticky = E, column=1, row=0) class User_Input: def __init__(self, parent): fields = ['Text Label 1', 'This is the text Label 2'] GUIFrame =Frame(parent) GUIFrame.pack(expand=True, anchor=NW) parent.minsize(width=350, height=325) field_index = 1 for field in fields: self.field = LabeledEntry(GUIFrame, text=field) self.field.grid(column=0, row=field_index) self.field.grid_columnconfigure(index = 0, minsize = 150) field_index += 1 self.Button2 = Button(parent, text='exit', command= parent.quit) self.Button2.place(x=25, y=300) root = Tk() MainFrame =User_Input(root) root.mainloop() </code></pre>
18,952,479
How to exclude multiple SLF4J bindings to LOG4J
<p>I am getting the error </p> <pre><code>SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/george/.gradle/caches/artifacts-26/filestore/org.apache.logging.log4j/log4j-slf4j-impl/2.0-beta8/jar/15984318e95b9b0394e979e413a4a14f322401c1/log4j-slf4j-impl-2.0-beta8.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/C:/Users/george/.gradle/caches/artifacts-26/filestore/org.slf4j/slf4j-log4j12/1.5.0/jar/aad1074d37a63f19fafedd272dc7830f0f41a977/slf4j-log4j12-1.5.0.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. </code></pre> <p>In my build.gradle file I have the following line to include the jar log4j-slf4j-impl-2.0-beta8.jar (which I want to bind to LOG4J2)</p> <pre><code> compile 'org.apache.logging.log4j:log4j-slf4j-impl:2.0-beta8' </code></pre> <p>In another build.gradle file in a dependent project I have multiple lines similar to the following:</p> <pre><code> compile 'dcm4che:dcm4che-core:2.0.23' </code></pre> <p>Now dcm4che includes a dependency on log4j version 1 (slf4j-log4j12) and this is therefore being included in the overall project.</p> <p>Here is a snippet from the Gradle dependency tree:</p> <pre><code>| +--- dcm4che:dcm4che-core:2.0.23 | | \--- org.slf4j:slf4j-log4j12:1.5.0 | | +--- org.slf4j:slf4j-api:1.5.0 -&gt; 1.7.5 | | \--- log4j:log4j:1.2.13 -&gt; 1.2.14 </code></pre> <p>I have read the link <a href="http://www.slf4j.org/codes.html#multiple_bindings">suggested in the warning</a> but I cannnot figure out how to make my app bind to log4j2 using the jar that I want. The Gradle documentation on dependency management has not really made it any clearer.</p>
19,417,373
3
0
null
2013-09-23 05:48:13.957 UTC
5
2017-04-13 03:21:26.907 UTC
null
null
null
null
986,820
null
1
22
java|logging|gradle|slf4j|log4j2
44,374
<p>The solution is to add the following in the build.gradle.</p> <pre><code>configurations.all { resolutionStrategy.eachDependency { DependencyResolveDetails details -&gt; if (details.requested.name == 'log4j') { details.useTarget "org.slf4j:log4j-over-slf4j:1.7.5" } } </code></pre> <p>The result is that anything that normally requires log4j will use log4j-over-slf4j instead.</p> <p>I also added:</p> <pre><code>if (details.requested.name == 'commons-logging') { details.useTarget "org.slf4j:jcl-over-slf4j:1.7.5" } </code></pre> <p>for completeness to cover commons logging.</p>
24,130,004
Adding http headers to window.location.href in Angular app
<p>I have a angular app that I needed to redirect outside to a non angular html page, so I thought I could just use the <code>$window.location.href</code>to redirect the angular app to my external site. This actually works fine, however, I have a nodejs/express backend that checks for auth token before serving up any content(even static content). </p> <p>This requires a auth token to be sent in the header of the http request. Now the question: </p> <p>Can/How do you add an auth token to the request that is made by changing the <code>$window.location.href</code> before it is sent off?</p>
26,373,493
2
0
null
2014-06-09 22:22:29.053 UTC
7
2020-05-05 18:15:32.04 UTC
2016-03-13 17:34:48.733 UTC
null
22,514
null
2,697,567
null
1
30
angularjs|http|oauth-2.0|http-headers|window.location
52,500
<p>When you use <code>$window.location.href</code> the browser is making the HTTP request and not your JavaScript code. Therefore, you cannot add a custom header like <code>Authorization</code> with your token value.</p> <p>You could add a cookie via JavaScript and put your auth token there. The cookies will automatically be sent from the browser. However, you will want to review the security implications of using a cookie vs. a header. Since both are accessible via JavaScript, there is no additional attack vector there. Unless you remove the cookie after the new page loads, there may be a CSRF exploit available.</p>
43,701,748
React pseudo selector inline styling
<p>What do you think are good ways to handle styling pseudo selectors with React inline styling? What are the gains and drawbacks?</p> <p>Say you have a styles.js file for each React component. You style your component with that styles file. But then you want to do a hover effect on a button (or whatever). </p> <p>One way is to have a global CSS file and handle styling pseudo selectors that way. Here, the class 'label-hover' comes from a global CSS file and styles.label comes from the components style file.</p> <pre><code>&lt;ControlLabel style={styles.label} className='label-hover'&gt; Email &lt;/ControlLabel&gt; </code></pre> <p>Another way is to style the components based on certain conditions (that might be triggered by state or whatever). Here, if hovered state is true, use styles.button and styles.buttonHover otherwise just use styles.button.</p> <pre><code>&lt;section style={(hovered !== true) ? {styles.button} : {...styles.button, ...styles.buttonHover }&gt; &lt;/section&gt; </code></pre> <p>Both approaches feels kind of hacky. If anyone has a better approach, I'd love to know. Thanks!</p>
43,707,118
2
0
null
2017-04-30 00:29:12.323 UTC
8
2019-05-10 03:55:37.16 UTC
null
null
null
null
6,636,554
null
1
40
css|reactjs
69,638
<p>My advice to anyone wanting to do inline styling with React is to use <a href="https://github.com/FormidableLabs/radium" rel="noreferrer">Radium</a> as well.</p> <p>It supports <a href="https://github.com/FormidableLabs/radium/tree/master/docs/guides#browser-states" rel="noreferrer"><code>:hover</code>, <code>:focus</code> and <code>:active</code> pseudo-selectors</a> with minimal effort on your part</p> <pre><code>import Radium from 'radium' const style = { color: '#000000', ':hover': { color: '#ffffff' } }; const MyComponent = () =&gt; { return ( &lt;section style={style}&gt; &lt;/section&gt; ); }; const MyStyledComponent = Radium(MyComponent); </code></pre> <hr> <h2>Update 04/03/2018</h2> <p>This has been getting a few upvotes lately so I feel like I should update it as I've stopped using Radium. I'm not saying Radium isn't still good and great for doing psuedo selectors, just that it's not the only option.</p> <p>There has been a large number of css-in-js libraries since Radium came out which are worth considering. My current pick of the bunch is <a href="https://emotion.sh/" rel="noreferrer">emotion</a>, but I encourage you to try a few out and find the one that fits you best.</p> <ul> <li><a href="https://emotion.sh/" rel="noreferrer">emotion</a> - ‍ The Next Generation of CSS-in-JS</li> <li><a href="https://github.com/rofrischmann/fela/" rel="noreferrer">fela</a> - Universal, Dynamic &amp; High-Performance Styling in JavaScript</li> <li><a href="https://github.com/cssinjs/styled-jss" rel="noreferrer">styled-jss</a> - Styled Components on top of JSS</li> <li><a href="https://github.com/cssinjs/react-jss" rel="noreferrer">react-jss</a> - JSS integration for React</li> <li><a href="https://github.com/cssinjs/jss" rel="noreferrer">jss</a> - JSS is a CSS authoring tool which uses JavaScript as a host language</li> <li><a href="https://github.com/tuchk4/rockey" rel="noreferrer">rockey</a> - Stressless CSS for components using JS. Write Component Based CSS with functional mixins.</li> <li><a href="https://github.com/styled-components/styled-components" rel="noreferrer">styled-components</a> - Universal, Dynamic &amp; High-Performance Styling in JavaScript</li> <li><a href="https://github.com/Khan/aphrodite" rel="noreferrer">aphrodite</a> - It's inline styles, but they work! Also supports styling via CSS</li> <li><a href="https://github.com/cxs-css/cxs" rel="noreferrer">csx</a> - ϟ A CSS-in-JS solution for functional CSS in functional UI components</li> <li><a href="https://github.com/zeit/styled-jsx" rel="noreferrer">styled-jsx</a> - Full CSS support for JSX without compromises</li> <li><a href="https://github.com/threepointone/glam" rel="noreferrer">glam</a> - crazy good css in your js</li> <li><a href="https://github.com/threepointone/glamor" rel="noreferrer">glamor</a> - css in your javascript</li> <li><a href="https://github.com/paypal/glamorous" rel="noreferrer">glamorous</a> - React component styling solved with an elegant API, small footprint, and great performance (via glamor)</li> <li><a href="https://github.com/rtsao/styletron" rel="noreferrer">styletron</a> - ⚡️ Universal, high-performance JavaScript styles</li> <li><a href="https://github.com/FormidableLabs/radium" rel="noreferrer">radium</a> - Set of tools to manage inline styles on React elements.</li> <li><a href="https://github.com/milesj/aesthetic" rel="noreferrer">aesthetic</a> - Aesthetic is a powerful React library for styling components, whether it be CSS-in-JS using objects, importing stylesheets, or simply referencing external class names.</li> <li><a href="https://github.com/j2css/j2c" rel="noreferrer">j2c</a> - CSS in JS library, tiny yet featureful</li> </ul> <p>(<a href="https://github.com/tuchk4/awesome-css-in-js" rel="noreferrer">Source</a>)</p>
27,792,508
Ruby backslash to continue string on a new line?
<p>I'm reviewing a line of Ruby code in a pull request. I'm not sure if this is a bug or a feature that I haven't seen before:</p> <pre><code>puts "A string of Ruby that"\ "continues on the next line" </code></pre> <p>Is the backslash a valid character to concatenate these strings? Or is this a bug?</p>
27,792,546
3
1
null
2015-01-06 05:19:18.417 UTC
3
2020-01-28 08:43:14.693 UTC
null
null
null
null
48,523
null
1
36
ruby
21,301
<p>That is valid code. </p> <p>The backslash is a line continuation. Your code has two quoted runs of text; the runs appear like two strings, but are really just one string because Ruby concatenates whitespace-separated runs.</p> <p>Example of three quoted runs of text that are really just one string:</p> <pre><code>"a" "b" "c" =&gt; "abc" </code></pre> <p>Example of three quoted runs of text that are really just one string, using <code>\</code> line continuations:</p> <pre><code>"a" \ "b" \ "c" =&gt; "abc" </code></pre> <p>Example of three strings, using <code>+</code> line continuations and also concatenations:</p> <pre><code>"a" + "b" + "c" =&gt; "abc" </code></pre> <p>Other line continuation details: "Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, -, or backslash at the end of a line, they indicate the continuation of a statement." - <a href="http://www.tutorialspoint.com/ruby/ruby_quick_guide.htm" rel="noreferrer">Ruby Quick Guide</a></p>
27,594,541
Export a list into a CSV or TXT file in R
<p>I understand that we cannot export a table if one of its elements is a list. I got a list in R and I want to export it into a CSV or TXT file. Here is the error message that I get when I execute this <code>write.table</code> command :</p> <pre><code>write.table(mylist,&quot;test.txt&quot;,sep=&quot;;&quot;) Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol, : unimplemented type 'list' in 'EncodeElement' </code></pre> <p>Here is the first element of my list :</p> <pre><code>$f10010_1 $f10010_1$mots [1] X16 ESPRESSO TDISC TASSIMO [5] CARTE NOIRE A LAVAZZA [9] MALONGO MIO MODO 123 [13] CAPSULES DOSES 78G LONG [17] SPRESSO CAFE 120G CLASSIC [21] 104G 128G AROMATIQUE INTENSE [25] 112G 156G 520G 5X16 [29] PROMO TRIPACK X24 126G [33] 16 4X16 APPASSIONATAMENTE APPASSIONATEMENTE [37] BRESIL CAPSUL COLOMBIE CORSE [41] CREMOSAMENTE DELICATI DELIZIOSAMENTE DIVINAMENTE [45] DOLCEMENTE EQI GRAND GRANDE [49] GT GUATEMALA HAITI INTENSAMENTE [53] ITALIAN MAGICAMENTE MERE MOKA78G [57] PETITS PRODUCT PURSMATIN RESERVE [61] RISTRETO SOAVEMENTE STYLE X36 64 Levels: 104G 112G 120G 123 126G 128G 156G 16 4X16 520G 5X16 78G ... X36 $f10010_1$nblabel [1] 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 [27] 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 [53] 32 32 32 32 32 32 32 32 32 32 32 32 Levels: 32 $f10010_1$Freq [1] 18 16 16 15 14 14 9 9 9 9 9 8 8 8 7 7 7 6 5 5 3 3 3 3 2 2 [27] 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 [53] 1 1 1 1 1 1 1 1 1 1 1 1 $f10010_1$pct [1] 0.56250 0.50000 0.50000 0.46875 0.43750 0.43750 0.28125 0.28125 0.28125 [10] 0.28125 0.28125 0.25000 0.25000 0.25000 0.21875 0.21875 0.21875 0.18750 [19] 0.15625 0.15625 0.09375 0.09375 0.09375 0.09375 0.06250 0.06250 0.06250 [28] 0.06250 0.06250 0.06250 0.06250 0.03125 0.03125 0.03125 0.03125 0.03125 [37] 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 [46] 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 [55] 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 0.03125 [64] 0.03125 </code></pre>
27,594,769
8
1
null
2014-12-21 22:41:42.607 UTC
21
2022-01-16 09:57:31.387 UTC
2022-01-16 09:57:31.387 UTC
null
792,066
null
4,383,566
null
1
58
r
150,417
<p>So essentially you have a list of lists, with mylist being the name of the main list and the first element being <code>$f10010_1</code> which is printed out (and which contains 4 more lists).</p> <p>I think the easiest way to do this is to use <code>lapply</code> with the addition of <code>dataframe</code> (assuming that each list inside each element of the main list (like the lists in <code>$f10010_1</code>) has the same length):</p> <pre><code>lapply(mylist, function(x) write.table( data.frame(x), 'test.csv' , append= T, sep=',' )) </code></pre> <p>The above will convert <code>$f10010_1</code> into a dataframe then do the same with every other element and append one below the other in 'test.csv'</p> <p>You can also type <code>?write.table</code> on your console to check what other arguments you need to pass when you write the table to a csv file e.g. whether you need row names or column names etc. </p>
27,647,749
How to test ActionMailer deliver_later with rspec
<p>trying to upgrade to Rails 4.2, using delayed_job_active_record. I've not set the delayed_job backend for test environment as thought that way jobs would execute straight away.</p> <p>I'm trying to test the new 'deliver_later' method with RSpec, but I'm not sure how.</p> <p>Old controller code:</p> <pre><code>ServiceMailer.delay.new_user(@user) </code></pre> <p>New controller code:</p> <pre><code>ServiceMailer.new_user(@user).deliver_later </code></pre> <p>I USED to test it like so:</p> <pre><code>expect(ServiceMailer).to receive(:new_user).with(@user).and_return(double(&quot;mailer&quot;, :deliver =&gt; true)) </code></pre> <p>Now I get errors using that. (Double &quot;mailer&quot; received unexpected message :deliver_later with (no args))</p> <p>Just</p> <pre><code>expect(ServiceMailer).to receive(:new_user) </code></pre> <p>fails too with 'undefined method `deliver_later' for nil:NilClass'</p> <p>I've tried some examples that allow you to see if jobs are enqueued using test_helper in ActiveJob but I haven't managed to test that the correct job is queued.</p> <pre><code>expect(enqueued_jobs.size).to eq(1) </code></pre> <p>This passes if the test_helper is included, but it doesn't allow me to check it is the correct email that is being sent.</p> <p>What I want to do is:</p> <ul> <li>test that the correct email is queued (or executed straight away in test env)</li> <li>with the correct parameters (@user)</li> </ul> <p>Any ideas?? thanks</p>
27,653,104
13
1
null
2014-12-25 13:45:12.653 UTC
13
2021-05-13 19:47:07.837 UTC
2021-05-13 19:47:07.837 UTC
null
74,089
null
1,007,594
null
1
85
ruby-on-rails|rspec|actionmailer|delayed-job|rails-activejob
38,907
<p>If I understand you correctly, you could do:</p> <pre><code>message_delivery = instance_double(ActionMailer::MessageDelivery) expect(ServiceMailer).to receive(:new_user).with(@user).and_return(message_delivery) allow(message_delivery).to receive(:deliver_later) </code></pre> <p>The key thing is that you need to somehow provide a double for <code>deliver_later</code>.</p>
32,618,216
Override S3 endpoint using Boto3 configuration file
<h3>OVERVIEW:</h3> <p>I'm trying to override certain variables in <code>boto3</code> using the configuration file (<code>~/aws/confg</code>). In my use case I want to use <code>fakes3</code> service and send S3 requests to the localhost.</p> <h3>EXAMPLE:</h3> <p>In <code>boto</code> (not <code>boto3</code>), I can create a config in <code>~/.boto</code> similar to this one:</p> <pre><code>[s3] host = localhost calling_format = boto.s3.connection.OrdinaryCallingFormat [Boto] is_secure = False </code></pre> <p>And the client can successfully pick up desired changes and instead of sending traffic to the real S3 service, it will send it to the localhost.</p> <pre><code>&gt;&gt;&gt; import boto &gt;&gt;&gt; boto.connect_s3() S3Connection:localhost &gt;&gt;&gt; </code></pre> <h3>WHAT I TRIED:</h3> <p>I'm trying to achieve a similar result using <code>boto3</code> library. By looking at the source code I found that I can use <code>~/aws/config</code> location. I've also found an example config in <code>unittests</code> folder of <code>botocore</code>.</p> <p>I tried to modify the config to achieve the desired behaviour. But unfortunately, it doesn't work.</p> <p>Here is the config:</p> <pre><code>[default] aws_access_key_id = XXXXXXXXX aws_secret_access_key = YYYYYYYYYYYYYY region = us-east-1 is_secure = False s3 = host = localhost </code></pre> <h3>QUESTION:</h3> <ol> <li>How to overwrite <code>clients</code> variables using config file?</li> <li>Where can I find a complete list of allowed variables for the configuration?</li> </ol>
41,327,767
6
1
null
2015-09-16 20:36:48.917 UTC
20
2021-11-30 00:38:36.14 UTC
2021-11-30 00:38:36.14 UTC
null
33,264
null
1,516,286
null
1
44
python|amazon-web-services|boto|boto3|botocore
58,459
<p>You cannot set host in config file, however you can override it from your code with boto3.</p> <pre><code>import boto3 session = boto3.session.Session() s3_client = session.client( service_name='s3', aws_access_key_id='aaa', aws_secret_access_key='bbb', endpoint_url='http://localhost', ) </code></pre> <p>Then you can interact as usual.</p> <pre><code>print(s3_client.list_buckets()) </code></pre>
9,129,802
Exception from HRESULT: 0x80131040
<pre><code>Warning 1 D:\MyPath\SomeAscx.cs: ASP.NET runtime error: Could not load file or assembly 'HtmlAgilityPack, Version=1.4.0.0, Culture=neutral, PublicKeyToken=bd319b19eaf3b43a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) </code></pre> <p>I have removed the reference and am not using it in code why would this still be an issue. I have tried cleaning solution, rebuilding, open and closing solution but still no success. Has anyone come across this issue before?</p>
9,129,917
2
0
null
2012-02-03 14:01:09.61 UTC
2
2015-03-07 14:46:58.43 UTC
null
null
null
null
199,640
null
1
9
c#|asp.net|visual-studio-2010|exception
48,254
<p>Even if you removed direct references, something else might still require that dll.</p> <p>I'd suggest:</p> <ol> <li>Recycle your IIS application pool (or run IISRESET from the command prompt to reset the entire web server)</li> <li>turn on <a href="http://msdn.microsoft.com/en-us/library/e74a18c4%28v=VS.100%29.aspx" rel="noreferrer">FusLog</a> and check who is the real "offender"</li> </ol>
9,032,655
Check if a string within a list contains a specific string with Linq
<p>I have a <code>List&lt;string&gt;</code> that has some items like this:</p> <pre><code>{"Pre Mdd LH", "Post Mdd LH", "Pre Mdd LL", "Post Mdd LL"} </code></pre> <p>Now I want to perform a condition that checks if an item in the list contains a specific string. something like:</p> <p><code>IF list contains an item that contains this_string</code></p> <p>To make it simple I want to check in one go if the list at least! contains for example an item that has <code>Mdd LH</code> in it.</p> <p>I mean something like:</p> <pre><code>if(myList.Contains(str =&gt; str.Contains("Mdd LH)) { //Do stuff } </code></pre> <p>Thanks.</p>
9,032,686
5
0
null
2012-01-27 11:31:03.247 UTC
4
2018-12-04 20:17:57.463 UTC
null
null
null
null
658,031
null
1
23
c#|linq
128,209
<p>I think you want <a href="http://msdn.microsoft.com/en-us/library/bb534972.aspx" rel="noreferrer"><code>Any</code></a>:</p> <pre><code>if (myList.Any(str =&gt; str.Contains("Mdd LH"))) </code></pre> <p>It's well worth becoming familiar with the <a href="http://msdn.microsoft.com/en-us/library/bb394939.aspx" rel="noreferrer">LINQ standard query operators</a>; I would usually use those rather than implementation-specific methods (such as <code>List&lt;T&gt;.ConvertAll</code>) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)</p>
9,185,630
Find out the 'line' (row) number of the cursor in a textarea
<p>I would like to find out and keep track of the 'line number' (rows) of the cursor in a textarea. (The 'bigger picture' is to parse the text on the line every time a new line is created/modified/selected, if of course the text was not pasted in. This saves parsing the whole text un-necessarily at set intervals.)</p> <p>There are a couple of posts on StackOverflow however none of them specifically answer my question, most questions are for cursor position in pixels or displaying lines numbers besides the textarea.</p> <p>My attempt is below, it works fine when starting at line 1 and not leaving the textarea. It fails when clicking out of the textarea and back onto it on a different line. It also fails when pasting text into it because the starting line is not 1. </p> <p>My JavaScript knowledge is pretty limited.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;DEVBug&lt;/title&gt; &lt;script type="text/javascript"&gt; var total_lines = 1; // total lines var current_line = 1; // current line var old_line_count; // main editor function function code(e) { // declare some needed vars var keypress_code = e.keyCode; // key press var editor = document.getElementById('editor'); // the editor textarea var source_code = editor.value; // contents of the editor // work out how many lines we have used in total var lines = source_code.split("\n"); var total_lines = lines.length; // do stuff on key presses if (keypress_code == '13') { // Enter current_line += 1; } else if (keypress_code == '8') { // Backspace if (old_line_count &gt; total_lines) { current_line -= 1; } } else if (keypress_code == '38') { // Up if (total_lines &gt; 1 &amp;&amp; current_line &gt; 1) { current_line -= 1; } } else if (keypress_code == '40') { // Down if (total_lines &gt; 1 &amp;&amp; current_line &lt; total_lines) { current_line += 1; } } else { //document.getElementById('keycodes').innerHTML += keypress_code; } // for some reason chrome doesn't enter a newline char on enter // you have to press enter and then an additional key for \n to appear // making the total_lines counter lag. if (total_lines &lt; current_line) { total_lines += 1 }; // putput the data document.getElementById('total_lines').innerHTML = "Total lines: " + total_lines; document.getElementById('current_line').innerHTML = "Current line: " + current_line; // save the old line count for comparison on next run old_line_count = total_lines; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;textarea id="editor" rows="30" cols="100" value="" onkeydown="code(event)"&gt;&lt;/textarea&gt; &lt;div id="total_lines"&gt;&lt;/div&gt; &lt;div id="current_line"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
9,185,820
3
0
null
2012-02-07 23:24:16.037 UTC
9
2020-05-07 13:17:14.747 UTC
2013-12-08 21:29:41.397 UTC
null
759,866
null
510,238
null
1
30
javascript|textarea
32,439
<p>You would want to use <code>selectionStart</code> to do this.</p> <pre><code>&lt;textarea onkeyup="getLineNumber(this, document.getElementById('lineNo'));" onmouseup="this.onkeyup();"&gt;&lt;/textarea&gt; &lt;div id="lineNo"&gt;&lt;/div&gt; &lt;script&gt; function getLineNumber(textarea, indicator) { indicator.innerHTML = textarea.value.substr(0, textarea.selectionStart).split("\n").length; } &lt;/script&gt; </code></pre> <p>This works when you change the cursor position using the mouse as well.</p>
9,467,093
How to add a tooltip to a cell in a jtable?
<p>I have a table where each row represents a picture. In the column Path I store its absolute path. The string being kinda long, I would like that when I hover the mouse over the specific cell, a tooltip should pop-up next to the mouse containing the information from the cell.</p>
9,467,372
3
0
null
2012-02-27 14:56:07.947 UTC
5
2018-05-09 20:31:01.437 UTC
2012-02-27 15:08:57.217 UTC
null
418,556
null
1,065,207
null
1
30
java|swing|jtable|tooltip|listener
41,384
<p>I assume you didn't write a custom <code>CellRenderer</code> for the path but just use the <code>DefaultTableCellRenderer</code>. You should subclass the <code>DefaultTableCellRenderer</code> and set the tooltip in the <code>getTableCellRendererComponent</code>. Then set the renderer for the column.</p> <pre><code>class PathCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel c = (JLabel)super.getTableCellRendererComponent( /* params from above (table, value, isSelected, hasFocus, row, column) */ ); // This... String pathValue = &lt;getYourPathValue&gt;; // Could be value.toString() c.setToolTipText(pathValue); // ...OR this probably works in your case: c.setToolTipText(c.getText()); return c; } } ... pathColumn.setCellRenderer(new PathCellRenderer()); // If your path is of specific class (e.g. java.io.File) you could set the renderer for that type ... </code></pre> <ul> <li><a href="http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#celltooltip" rel="noreferrer">Oracle JTable tutorial on tooltips</a></li> </ul>
10,413,350
Date Conversion from String to sql Date in Java giving different output?
<p>I have a string form of Date. I have to change it to Sql Date. so for that i have used the following code. </p> <pre><code>String startDate="01-02-2013"; SimpleDateFormat sdf1 = new SimpleDateFormat("dd-mm-yyyy"); java.util.Date date = sdf1.parse(startDate); java.sql.Date sqlStartDate = new java.sql.Date(date.getTime()); </code></pre> <p>when i used the above code and run that. I got the following output. </p> <pre><code>2013-01-01. </code></pre> <p>Here Month is not converted correctly.<br> Please tell me where is the problem and provide sample code to get correct result?</p>
10,413,391
5
1
null
2012-05-02 12:03:40.757 UTC
5
2018-07-23 14:44:19.497 UTC
2014-01-21 07:33:29.03 UTC
null
1,506,203
null
1,324,419
null
1
30
java|date|type-conversion
131,125
<p><code>mm</code> is <em>minutes</em>. You want <code>MM</code> for <em>months</em>:</p> <pre><code>SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); </code></pre> <p>Don't feel bad - this exact mistake comes up a lot.</p>
10,419,747
TaskCompletionSource - Trying to understand threadless async work
<p>I'm trying to understand the purpose of <code>TaskCompletionSource</code> and its relation to async/threadless work. I think I have the general idea but I want to make sure my understanding is correct. </p> <p>I first started looking into the Task Parallel Library (TPL) to figure out if there was a good way to create your own threadless/async work (say you're trying to improve scalability of your ASP.NET site) plus understanding of the TPL looks like it will be very important in the future (<code>async</code>/<code>await</code>). Which led me to the <code>TaskCompletionSource</code>.</p> <p>From my understanding it looks like adding <code>TaskCompletionSource</code> to a one of your classes doesn't really do much in as making your coding async; if you're still executing sync code then the call to your code will block. I think this is even true of microsoft APIs. For example, say in <code>DownloadStringTaskAsync</code> off of <code>WebClient</code> class, any setup / sync code they are doing initially will block. The code you're executing has to run on some thread, either the current thread or you will have to spin off a new one. </p> <p>So you use <code>TaskCompletionSource</code> in your own code when you're calling other <code>async</code> calls from Microsoft so the client of your classes doesn't have to create a new thread for your class to not block.</p> <p>Not sure how Microsoft does their async APIs internally. For example, there is a new <code>async</code> method off of the <code>SqlDataReader</code> for .Net 4.5. I know there is IO Completion Ports. I think it's a lower level abstraction (C++?) that probably most C# developers won't use. Not sure if IO completion Ports will work for Database or network calls (HTTP) or if its just used for file IO.</p> <p>So the question is, am I correct in my understanding correct? Are there certain things I've represented incorrectly?</p>
10,420,085
2
1
null
2012-05-02 18:40:04.227 UTC
25
2020-04-09 06:52:42.553 UTC
2017-01-28 17:19:48.437 UTC
null
1,438,397
null
127,954
null
1
36
asynchronous|task-parallel-library
21,278
<p><code>TaskCompletionSource</code> is used to create <code>Task</code> objects that don't execute code.</p> <p>They're used quite a bit by Microsoft's new async APIs - any time there's I/O-based asynchronous operations (or other non-CPU-based asynchronous operations, like a timeout). Also, any <code>async Task</code> method you write will use TCS to complete its returned <code>Task</code>.</p> <p>I have a blog post <a href="http://blog.stephencleary.com/2012/02/creating-tasks.html" rel="nofollow noreferrer">Creating Tasks</a> that discusses different ways to create <code>Task</code> instances. It's written from an <code>async</code>/<code>await</code> perspective (not a TPL perspective), but it still applies here.</p> <p>Also see Stephen Toub's excellent posts:</p> <ul> <li><a href="https://devblogs.microsoft.com/pfxteam/the-nature-of-taskcompletionsourcetresult/" rel="nofollow noreferrer">The Nature of TaskCompletionSource</a></li> <li><a href="https://devblogs.microsoft.com/pfxteam/mechanisms-for-creating-tasks/" rel="nofollow noreferrer">Mechanisms for Creating Tasks</a></li> <li><a href="https://devblogs.microsoft.com/pfxteam/await-anything/" rel="nofollow noreferrer">await anything;</a> (using <code>TaskCompletionSource</code> to <code>await</code> anything).</li> <li><a href="https://devblogs.microsoft.com/pfxteam/using-tasks-to-implement-the-apm-pattern/" rel="nofollow noreferrer">Using Tasks to implement the APM Pattern</a> (creating <code>Begin</code>/<code>End</code> using <code>TaskCompletionSource</code>).</li> </ul>
22,922,155
PostgreSQL/JDBC and TIMESTAMP vs. TIMESTAMPTZ
<p>I've been going through a lot of pain dealing with Timestamps lately with JPA. I have found that a lot of my issues have been cleared up by using TIMESTAMPTZ for my fields instead of TIMESTAMP. My server is in UTC while my JVM is in PST. It seems almost impossible with JPA to normalize on UTC values in the database when using TIMESTAMP WITHOUT TIMEZONE.</p> <p>For me I use these fields for stuff like "when was the user created", "when did they last use their device", "when was the last time they got an alert", etc. These are typically events so they are instance in time sorts of values. And because they will now by TIMESTAMPTZ I can always query them for a particular zone if I don't want them UTC. </p> <p>So my question is, for a Java/JPA/PostgreSQL server, when WOULD I want to use TIMESTAMP over TIMESTAMPTZ? What are the use cases for it? Right now I have a hard time seeing why I'd ever want to use TIMESTAMP and because of that I'm concerned that I'm not grasping its value. </p>
22,922,391
4
1
null
2014-04-07 20:14:19.663 UTC
11
2021-08-03 20:29:05.71 UTC
null
null
null
null
1,888,440
null
1
28
postgresql|jpa|jdbc
17,601
<p>You could use it to represent what Joda-Time and the new Java 8 time APIs call a <code>LocalDateTime</code>. A <code>LocalDateTime</code> doesn't represent a precise point on the timeline. It's just a set of fields, from year to nanoseconds. It is "a description of the date, as used for birthdays, combined with the local time as seen on a wall clock". </p> <p>You could use it to represent, for example, the fact that your precise birth date is 1975-07-19 at 6 PM. Or that, all across the world, the next new year is celebrated on 2015-01-01 at 00:00.</p> <p>To represent precise moments, like the moment Armstrong walked on the moon, a timestamp with timezone is indeed more appropriate. Regardless of the timezone of the JVM and the timezone of the database, it should return you the correct moment.</p>
22,989,339
multiple worker/web processes on a single heroku app
<p>Is there some way to configure multiple worker and/or web processes to run in the single Heroku app container? Or does this have to be broken up into multiple Heroku apps?</p> <p>For example:</p> <pre><code>worker: node capture.js worker: node process.js worker: node purge.js web: node api.js web: node web.js </code></pre>
22,991,644
1
1
null
2014-04-10 13:22:39.33 UTC
14
2014-04-10 17:19:51.813 UTC
null
null
null
null
877,151
null
1
44
node.js|heroku|multiple-instances|worker
22,569
<p>All processes must have unique names. <strike>Additionally, the names <code>web</code> and <code>worker</code> are insignificant and carry no special meaning.</strike> The only process that carries a significant name is the <code>web</code> process, as stated in the Heroku docs:</p> <blockquote> <p>The web process type is special as it’s the only process type that will receive HTTP traffic from Heroku’s routers. Other process types can be named arbitrarily. -- (<a href="https://devcenter.heroku.com/articles/procfile">https://devcenter.heroku.com/articles/procfile</a>)</p> </blockquote> <p>So you want a <code>Procfile</code> like so:</p> <pre><code>capture: node capture.js process: node process.js purge: node purge.js api: node api.js web: node web.js </code></pre> <p>You can then scale each process separately:</p> <pre><code>$ heroku ps:scale purge=4 </code></pre>
31,296,545
Correct handling of NSJSONSerialization (try catch) in Swift (2.0)?
<p>arowmy init works fine in Swift &lt; 2 but in Swift 2 I get a error message from Xcode <code>Call can throw, but it is not marked with 'try' and the error is not handled</code> at <code>let anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]</code>. I think in my case I can´t use a try catch block because super is not initialized at this time. "Try" need a function that throws. </p> <p>here is my function:</p> <pre><code>required init(coder aDecoder : NSCoder) { self.name = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("name") as! String!) self.number = Int(aDecoder.decodeIntegerForKey("number")) self.img = String(stringInterpolationSegment: aDecoder.decodeObjectForKey("image") as! String!) self.fieldproperties = [] var tmpArray = [String]() tmpArray = aDecoder.decodeObjectForKey("properties") as! [String] let c : Int = tmpArray.count for var i = 0; i &lt; c; i++ { let data : NSData = tmpArray[i].dataUsingEncoding(NSUTF8StringEncoding)! // Xcode(7) give me error: 'CAll can thorw, but it is not marked with 'try' and the error is not handled' let anyObj = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject] let label = anyObj["label"] as AnyObject! as! String let value = anyObj["value"] as AnyObject! as! Int let uprate = anyObj["uprate"] as AnyObject! as! Int let sufix = anyObj["sufix"] as AnyObject! as! String let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix) self.fieldproperties.append(props) } } </code></pre> <p>Xcode mean that: <code>let anyObj = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]</code></p> <p>but I have no idea to do here the right think according to this document <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html" rel="nofollow noreferrer">https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html</a></p>
31,296,955
3
4
null
2015-07-08 15:03:16.623 UTC
7
2017-07-06 16:02:45.18 UTC
2017-06-29 17:11:27.207 UTC
null
1,033,581
null
982,011
null
1
30
ios|swift
31,541
<p>The <code>jsonObject</code> can <code>throw</code> errors, so put it within <code>do</code> block, use <code>try</code>, and <code>catch</code> any errors thrown. In Swift 3:</p> <pre><code>do { let anyObj = try JSONSerialization.jsonObject(with: data) as! [String: Any] let label = anyObj["label"] as! String let value = anyObj["value"] as! Int let uprate = anyObj["uprate"] as! Int let sufix = anyObj["sufix"] as! String let props = Fieldpropertie(label: label, value: value, uprate: uprate, sufix: sufix) // etc. } catch { print("json error: \(error.localizedDescription)") } </code></pre> <p>Or, in Swift 4, you can simplify your code by making your <code>struct</code> conform to <code>Codable</code>:</p> <pre><code>struct Fieldpropertie: Codable { let label: String let value: Int let uprate: Int let suffix: String } </code></pre> <p>Then</p> <pre><code>do { let props = try JSONDecoder().decode(Fieldpropertie.self, from: data) // use props here; no manual parsing the properties is needed } catch { print("json error: \(error.localizedDescription)") } </code></pre> <p>For Swift 2, see <a href="https://stackoverflow.com/revisions/31296955/5">previous revision of this answer</a>.</p>
36,876,770
CSS - What is best to use for this case (px, %, vw, wh or em)?
<p>I am using Ionic 2 for the development of an app and I need to preview the app in different sizes.</p> <p>Currently, I am using <code>vw</code> in all the sizes including <code>font-size</code>, <code>padding</code> and so on, but when resizing the font it sometimes becomes a bit small and even sometimes the text is not readable.</p> <p>For that reason, I would like to know what is best to use in this case:</p> <ul> <li><code>px</code></li> <li><code>%</code></li> <li><code>vw</code></li> <li><code>wh</code></li> <li><code>em</code></li> </ul> <p>Or do I need to use also the <code>@media</code> and support different font sizes?</p> <p>Any thoughts?</p>
36,876,937
3
2
null
2016-04-26 22:15:36.96 UTC
12
2020-06-17 07:17:34.727 UTC
2020-06-17 07:17:34.727 UTC
null
12,860,895
null
6,101,493
null
1
19
html|css|ionic2
41,682
<p>Note that I only mentioned the ones you asked about.</p> <p>Here you can see the full list of CSS measurement units: <a href="http://www.w3schools.com/cssref/css_units.asp" rel="noreferrer">CSS Units in W3Schools</a></p> <p>Rather than telling you which one is the "right one", I would rather want you to understand what each one actually is.</p> <p><strong>Pixels (<code>px</code>):</strong> Absolute pixels. So for example, <code>20px</code> will be literally 20 pixels on any screen. If a monitor is of 1980x1200, and you set an element's height to <code>200px</code>, the element will take 200 pixels out of that.</p> <p><strong>Percentage (<code>%</code>):</strong> Relative to the parent value.</p> <p>So for this example:</p> <pre><code>&lt;div style="width: 200px;"&gt; &lt;div style="width: 50%;"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>The inner div will have a width of 100 pixels.</p> <p><strong>Viewport height/width (<code>vw</code>/<code>vh</code>):</strong> Size relative to the viewport (browser window, basically).</p> <p>Example:</p> <pre><code>.myDiv { width: 100vw; height: 100vh; background-color: red; } </code></pre> <p>Will make an cover the whole browser in red. This is very common among <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" rel="noreferrer">flexboxes</a> as it's naturally responsive.</p> <p><strong>Emeters (<code>em</code>) and Root Emeters (<code>rem</code>):</strong> <code>em</code> is relative to the parent element's font size. <code>rem</code> will be relative to the <code>html</code> font-size (mostly 16 pixels). This is very useful if you want to keep an "in mind relativity of sizes" over your project, and not using variables by pre-processors like Sass and Less. Just easier and more intuitive, I guess.</p> <p>Example:</p> <pre><code>.myDiv { font-size: 0.5rem; } </code></pre> <p>Font size will be 8 pixels.</p> <p>Now that you know, choose the right one for the right purpose.</p>
3,815,447
Does rake db:schema:dump recreate schema.rb from migrations or the database itself?
<p>Does</p> <pre><code>rake db:schema:dump </code></pre> <p>recreate <code>schema.rb</code> from migrations or the database itself?</p>
3,815,807
1
0
null
2010-09-28 17:30:12.327 UTC
16
2020-03-19 14:32:28.68 UTC
2014-10-28 21:21:18.367 UTC
null
2,202,702
null
341,878
null
1
68
ruby-on-rails|schema|migration|rake
52,287
<p>The answer is simple: from the database.</p> <p>By the way - when you <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/railties/databases.rake" rel="noreferrer">take a look into the source code of db:* tasks</a> you can see that migration tasks calls schema:dump after the run</p> <pre><code>desc "Migrate the database (options: VERSION=x, VERBOSE=false)." task :migrate =&gt; :environment do ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby end </code></pre> <p>So the migration works in the way that it change the database and <strong>then</strong> generate schema.rb file. </p>
21,203,402
CSS not loading in Spring Boot
<p>I am new to spring frame work and spring boot.I am trying to add the static html file with CSS,javascript,js. the file structure is</p> <p><img src="https://i.stack.imgur.com/bNei4.png" alt="PROJECT STRUCTURE"></p> <p>and my html file head looks like this </p> <pre><code>&lt;html xmlns:th="http://www.thymeleaf.org"&gt; &lt;head&gt; &lt;title&gt;HeavyIndustry by HTML5Templates.com&lt;/title&gt; &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt; &lt;meta name="description" content="" /&gt; &lt;meta name="keywords" content="" /&gt; &lt;link rel="stylesheet" type="text/css" media="all" href="css/5grid/core.css" th:href="@{css/5grid/core}" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/5grid/core-desktop.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/5grid/core-1200px.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/5grid/core-noscript.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/style.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="css/style-desktop.css" /&gt; &lt;script src="css/5grid/jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="css/5grid/init.js?use=mobile,desktop,1000px&amp;amp;mobileUI=1&amp;amp;mobileUI.theme=none" type="text/javascript"&gt;&lt;/script&gt; &lt;!--[if IE 9]&gt;&lt;link rel="stylesheet" href="css/style-ie9.css" /&gt;&lt;![endif]--&gt; &lt;/head&gt; </code></pre> <p>when i run the spring project only the content is shown and the CSS is not applied.then the browser show the following error in the console <strong>404 Not Found error for the .css,.js files</strong> </p> <p>some body help me to sort out this issue.Thanks in Advance.</p>
22,951,140
8
2
null
2014-01-18 11:22:51.437 UTC
13
2021-04-13 03:41:22.647 UTC
null
null
null
null
2,018,328
null
1
29
spring|spring-mvc|spring-boot
87,444
<p>You need to put your css in <code>/resources/static/css</code>. This change fixed the problem for me. Here is my current directory structure.</p> <pre><code>src main java controller WebAppMain.java resources views index.html static css index.css bootstrap.min.css </code></pre> <p>Here is my template resolver:</p> <pre><code>public class WebAppMain { public static void main(String[] args) { SpringApplication app = new SpringApplication(WebAppMain.class); System.out.print("Starting app with System Args: [" ); for (String s : args) { System.out.print(s + " "); } System.out.println("]"); app.run(args); } @Bean public ViewResolver viewResolver() { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setTemplateMode("XHTML"); templateResolver.setPrefix("views/"); templateResolver.setSuffix(".html"); SpringTemplateEngine engine = new SpringTemplateEngine(); engine.setTemplateResolver(templateResolver); ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(engine); return viewResolver; } } </code></pre> <p>And just in case, here is my index.html:</p> <pre><code>&lt;!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd"&gt; &lt;html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"&gt; &lt;head&gt; &lt;title&gt;Subscribe&lt;/title&gt; &lt;meta charset="utf-8" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt; &lt;!-- Bootstrap --&gt; &lt;link type="text/css" href="css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;link type="text/css" href="css/index.css" rel="stylesheet" /&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; Hello&lt;/h1&gt; &lt;p&gt; Hello World!&lt;/p&gt; &lt;!-- jQuery (necessary for Bootstrap's JavaScript plugins) --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Include all compiled plugins (below), or include individual files as needed --&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1,754,315
How to create custom exceptions in Java?
<p>How do we create custom exceptions in Java?</p>
1,754,473
3
3
null
2009-11-18 07:59:37.657 UTC
35
2016-09-10 18:07:14.117 UTC
2016-09-10 18:07:14.117 UTC
null
4,922,375
null
96,180
null
1
153
java|exception
271,065
<p>To define a <strong>checked</strong> exception you create a subclass (or hierarchy of subclasses) of <a href="http://java.sun.com/javase/7/docs/api/java/lang/Exception.html" rel="noreferrer"><code>java.lang.Exception</code></a>. For example:</p> <pre><code>public class FooException extends Exception { public FooException() { super(); } public FooException(String message) { super(message); } public FooException(String message, Throwable cause) { super(message, cause); } public FooException(Throwable cause) { super(cause); } } </code></pre> <p>Methods that can potentially throw or propagate this exception must declare it:</p> <pre><code>public void calculate(int i) throws FooException, IOException; </code></pre> <p>... and code calling this method must either handle or propagate this exception (or both):</p> <pre><code>try { int i = 5; myObject.calculate(5); } catch(FooException ex) { // Print error and terminate application. ex.printStackTrace(); System.exit(1); } catch(IOException ex) { // Rethrow as FooException. throw new FooException(ex); } </code></pre> <p>You'll notice in the above example that <a href="https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html" rel="noreferrer"><code>IOException</code></a> is caught and rethrown as <code>FooException</code>. This is a common technique used to encapsulate exceptions (typically when implementing an API).</p> <p>Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an <strong>unchecked</strong> exception. An unchecked exception is any exception that extends <a href="http://java.sun.com/javase/7/docs/api/java/lang/RuntimeException.html" rel="noreferrer"><code>java.lang.RuntimeException</code></a> (which itself is a subclass of <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html" rel="noreferrer"><code>java.lang.Exception</code></a>):</p> <pre><code>public class FooRuntimeException extends RuntimeException { ... } </code></pre> <p>Methods can throw or propagate <code>FooRuntimeException</code> exception without declaring it; e.g.</p> <pre><code>public void calculate(int i) { if (i &lt; 0) { throw new FooRuntimeException("i &lt; 0: " + i); } } </code></pre> <p>Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.</p> <p>The <a href="http://java.sun.com/javase/7/docs/api/java/lang/Throwable.html" rel="noreferrer"><code>java.lang.Throwable</code></a> class is the root of all errors and exceptions that can be thrown within Java. <a href="http://java.sun.com/javase/7/docs/api/java/lang/Exception.html" rel="noreferrer"><code>java.lang.Exception</code></a> and <a href="http://java.sun.com/javase/7/docs/api/java/lang/Error.html" rel="noreferrer"><code>java.lang.Error</code></a> are both subclasses of <a href="http://java.sun.com/javase/7/docs/api/java/lang/Throwable.html" rel="noreferrer"><code>Throwable</code></a>. Anything that subclasses <a href="http://java.sun.com/javase/7/docs/api/java/lang/Throwable.html" rel="noreferrer"><code>Throwable</code></a> may be thrown or caught. However, it is typically bad practice to catch or throw <a href="http://java.sun.com/javase/7/docs/api/java/lang/Error.html" rel="noreferrer"><code>Error</code></a> as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. <a href="http://java.sun.com/javase/7/docs/api/java/lang/OutOfMemoryError.html" rel="noreferrer"><code>OutOfMemoryError</code></a>). Likewise you should avoid catching <a href="http://java.sun.com/javase/7/docs/api/java/lang/Throwable.html" rel="noreferrer"><code>Throwable</code></a>, which could result in you catching <a href="http://java.sun.com/javase/7/docs/api/java/lang/Error.html" rel="noreferrer"><code>Error</code></a>s in addition to <a href="http://java.sun.com/javase/7/docs/api/java/lang/Exception.html" rel="noreferrer"><code>Exception</code></a>s.</p>
19,606,275
IPython: How to wipe IPython's history selectively & securely?
<p>I have been learning how to use the <code>paramiko</code> package only to discover that all I stored passwords in plain text in IPython's <code>%hist</code>. Not so good.</p> <p>I therefore need to get rid of particular parts of what is stored in <code>%hist</code>. Saying that, I do not want to wipe the <em>whole history</em>. - Only the parts where I have been careless enough to type <code>password =</code> or similar chosen terms.</p> <p><em>Thanks</em></p> <hr> <p>Comments I don't need:</p> <ul> <li><code>%clear</code> only clears the session. It does not wipe the history.</li> <li>Yes. I will only use xSA_keys from now on.</li> </ul>
19,606,820
6
1
null
2013-10-26 11:43:03.783 UTC
8
2019-12-02 17:40:17.127 UTC
null
null
null
null
1,186,019
null
1
40
ipython|ipython-notebook
18,260
<p>History is store on <code>$(ipython locate)/profile_default/history.sqlite</code> by default. You can remove the file, and or do any operation you want on it (secure erase, etc..). It's an sqlite file so you can load it with any sqlite program and do query on it.</p> <p>Check in <code>$(ipython locate)/profile_default/</code> and other <code>$(ipython locate)/profile_xxx</code> that you do not have any other history files. <code>$(ipython locate)</code> is usually <code>~/.ipython/</code> but can vary:</p> <pre><code>ls $(ipython locate)/profile_*/*.sqlite </code></pre>
87,892
What is the status of POSIX asynchronous I/O (AIO)?
<p>There are pages scattered around the web that describe POSIX AIO facilities in varying amounts of detail. None of them are terribly recent. It's not clear what, exactly, they're describing. For example, the "official" (?) <a href="http://lse.sourceforge.net/io/aio.html" rel="noreferrer">web site for Linux kernel asynchronous I/O support here</a> says that sockets don't work, but the "aio.h" manual pages on my Ubuntu 8.04.1 workstation all seem to imply that it works for arbitrary file descriptors. Then there's <a href="http://www.bullopensource.org/posix/" rel="noreferrer">another project that seems to work at the library layer</a> with even less documentation.</p> <p>I'd like to know:</p> <ul> <li>What is the purpose of POSIX AIO? Given that the most obvious example of an implementation I can find says it doesn't support sockets, the whole thing seems weird to me. Is it just for async disk I/O? If so, why the hyper-general API? If not, why is disk I/O the first thing that got attacked?</li> <li>Where are there example <em>complete</em> POSIX AIO programs that I can look at?</li> <li>Does anyone actually use it, for real?</li> <li>What platforms support POSIX AIO? What parts of it do they support? Does anyone really support the implied "Any I/O to any FD" that <code>&lt;aio.h&gt;</code> seems to promise?</li> </ul> <p>The other multiplexing mechanisms available to me are perfectly good, but the random fragments of information floating around out there have made me curious.</p>
88,607
4
0
null
2008-09-17 21:32:25.49 UTC
57
2018-05-03 19:51:18.14 UTC
2018-05-03 19:51:18.14 UTC
null
13,564
Glyph
13,564
null
1
99
linux|asynchronous|posix|bsd|aio
26,264
<p>Network I/O is not a priority for AIO because everyone writing POSIX network servers uses an event based, non-blocking approach. The old-style Java "billions of blocking threads" approach sucks horribly.</p> <p>Disk write I/O is already buffered and disk read I/O can be prefetched into buffer using functions like posix_fadvise. That leaves direct, unbuffered disk I/O as the only useful purpose for AIO. </p> <p>Direct, unbuffered I/O is only really useful for transactional databases, and those tend to write their own threads or processes to manage their disk I/O.</p> <p>So, at the end that leaves POSIX AIO in the position of not serving <strong>any</strong> useful purpose. Don't use it.</p>
22,155,882
PHP CURL Download File
<p>im trying to download a file from a url, when I use the browser the download dialog works but when I use this code the new file on my server stay empty.</p> <pre><code>$ch = curl_init(); $source = "https://myapps.gia.edu/ReportCheckPortal/downloadReport.do?reportNo=$row['certNo']&amp;weight=$row['carat']"; curl_setopt($ch, CURLOPT_URL, $source); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec ($ch); curl_close ($ch); $destination = "./files/certs/$row['certNo'].pdf"; $file = fopen($destination, "w+"); fputs($file, $data); fclose($file); </code></pre> <p>example of url: <a href="https://myapps.gia.edu/ReportCheckPortal/downloadReport.do?reportNo=1152872617&amp;weight=1.35">https://myapps.gia.edu/ReportCheckPortal/downloadReport.do?reportNo=1152872617&amp;weight=1.35</a></p>
22,165,451
4
1
null
2014-03-03 19:46:05.487 UTC
2
2021-03-25 01:10:09.58 UTC
2014-08-14 04:40:28.72 UTC
null
14,966
null
3,376,311
null
1
17
php|file|curl|download
80,469
<p>I solved this problem using this:</p> <pre><code>curl_setopt($ch, CURLOPT_SSLVERSION,3); </code></pre> <p>This is the final code:</p> <pre><code>$source = "https://myapps.gia.edu/ReportCheckPortal/downloadReport.do?reportNo=1152872617&amp;weight=1.35"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $source); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSLVERSION,3); $data = curl_exec ($ch); $error = curl_error($ch); curl_close ($ch); $destination = "./files/test.pdf"; $file = fopen($destination, "w+"); fputs($file, $data); fclose($file); </code></pre>