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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9,138,857 | In neo4j, how can I index by date and search in a date range? | <p>In neo4j, how can I index by date and search in a date range. Also for times, I would like to search between 8am and 9am in a date range as well.</p> | 9,147,388 | 4 | 2 | null | 2012-02-04 06:16:04.563 UTC | 11 | 2014-07-11 20:32:25.823 UTC | null | null | null | null | 78,000 | null | 1 | 16 | java|search|indexing|neo4j | 10,575 | <p>Index the dates and times as integer timestamps. Then you can easily search in an index for dates between other timestamps. You can also index the time part of the timestamp separately as another integer, allowing you to query for specific times between given dates.</p>
<p>Example:
The date and time to store is "2012-02-05 8:15 AM"
So in your index, store "timestamp=1328447700" and "time=815"</p>
<p>Now you want to query the index for all events between 2012-02-01 and 2012-02-10 that occurred from 8:00 am to 9:00 am. You do that by querying the index for
"timestamp>=1328072400 and timestamp<=1328936399 and time>=800 and time<=900"</p>
<p>The exact syntax for doing this depends on how you are connecting to Neo4j (REST or embedded) and which programming language you are using. But the idea is the same in any case.</p> |
29,625,813 | How to make azure webjob run continuously and call the public static function without automatic trigger | <p>I am developing a azure webjob which should run continuously. I have a public static function. I want this function to be automatically triggered without any queue. Right now i am using while(true) to run continuously. Is there any other way to do this?</p>
<p>Please find below my code</p>
<pre><code> static void Main()
{
var host = new JobHost();
host.Call(typeof(Functions).GetMethod("ProcessMethod"));
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
[NoAutomaticTriggerAttribute]
public static void ProcessMethod(TextWriter log)
{
while (true)
{
try
{
log.WriteLine("There are {0} pending requests", pendings.Count);
}
catch (Exception ex)
{
log.WriteLine("Error occurred in processing pending altapay requests. Error : {0}", ex.Message);
}
Thread.Sleep(TimeSpan.FromMinutes(3));
}
}
</code></pre>
<p>Thanks</p> | 30,552,529 | 2 | 3 | null | 2015-04-14 11:08:49.593 UTC | 13 | 2016-01-23 21:39:58.273 UTC | null | null | null | null | 4,717,427 | null | 1 | 26 | c#|azure|azure-webjobs | 23,145 | <p>These steps will get you to what you want:</p>
<ol>
<li>Change your method to async</li>
<li>await the sleep</li>
<li>use host.CallAsync() instead of host.Call()</li>
</ol>
<p>I converted your code to reflect the steps below.</p>
<pre><code>static void Main()
{
var host = new JobHost();
host.CallAsync(typeof(Functions).GetMethod("ProcessMethod"));
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
[NoAutomaticTriggerAttribute]
public static async Task ProcessMethod(TextWriter log)
{
while (true)
{
try
{
log.WriteLine("There are {0} pending requests", pendings.Count);
}
catch (Exception ex)
{
log.WriteLine("Error occurred in processing pending altapay requests. Error : {0}", ex.Message);
}
await Task.Delay(TimeSpan.FromMinutes(3));
}
}
</code></pre> |
16,449,728 | Eclipse: change vertical bar color | <p>trying to deal with a minor issue here: I want to make my eclipse as distraction free as possible. So far I'm satisfied, except for one thing that I've not been able to figure out how to change:</p>
<p><img src="https://i.stack.imgur.com/gwRWA.png" alt="eclipse screenshot with white annoying bars"></p>
<p>the white vertical bars are ... annoying. How can I change their color? </p>
<p>Please note that the left ruler is not the code folding bar (which is on the right side of the line numbers), but the so called "vertical ruler" which shows line annotations (eg errors and stuff), to be found in Preferences > General > Editors > Text Editors > Annotations. This bar can not be deactivated (which I don"t want because i find it useful), I just want its color changed. Don't know what the right ruler is though.</p>
<p>not a duplicate of <a href="https://stackoverflow.com/questions/12490672/vertical-white-line-on-eclipse">Vertical white line on eclipse</a> or <a href="https://stackoverflow.com/questions/1041760/is-it-possible-to-make-eclipses-code-folding-gutter-black">Is it possible to make Eclipse's code-folding gutter black?</a></p>
<p>edit: but indeed a (partial) duplicate of <a href="https://stackoverflow.com/questions/204548/change-overview-ruler-color-in-eclipse?rq=1">Change overview ruler color in Eclipse</a>. Problem not solved: changing the system theme (mine is mediterranean dark) did not change the color of the bar.</p>
<p>Thank you</p> | 16,452,619 | 4 | 2 | null | 2013-05-08 20:34:55.68 UTC | 13 | 2016-11-27 20:31:35.623 UTC | 2017-05-23 12:24:28.467 UTC | null | -1 | null | 774,679 | null | 1 | 12 | eclipse | 21,147 | <p>Found it myself, sharing it for others who want to customize their bar color:</p>
<pre><code>#org-eclipse-e4-ui-compatibility-editor * { background-color: #002b36; }
</code></pre>
<p>change the hex value to anything you like. This css snippet has to be added to eclipse in some way (I did it with eclipse Chrome Theme <a href="http://marketplace.eclipse.org/content/eclipse-4-chrome-theme#.UYrzEkAW1J0" rel="noreferrer">http://marketplace.eclipse.org/content/eclipse-4-chrome-theme#.UYrzEkAW1J0</a>)</p>
<p>FYI: I found the css id with the "css spy" from the eclipse tooling collection (<a href="http://marketplace.eclipse.org/content/eclipse-4-tools-css-spy#.UYrzSkAW1J0" rel="noreferrer">http://marketplace.eclipse.org/content/eclipse-4-tools-css-spy#.UYrzSkAW1J0</a>)</p>
<p>result:</p>
<p><img src="https://i.stack.imgur.com/D3b6N.png" alt="styled eclipse"></p> |
11,126,060 | Is there a way to check AD group membership for a computer? | <p>I am trying to check computer group membership through Powershell. I want to be able to specify a certain computer name and find which groups that computer is in but from a Powershell script. I am planning on running the script on a computer, grabbing the hostname, and then printing out what AD groups that computer is in. Is there an easy way to do this?</p>
<p>EDIT:
So the plan here is to have a computer check to see what groups it is in, then assign a printer based on which group it is in. We have many printers that only 3 to 4 people use but due to the spread out nature of the users cannot downsize the amount of printers. I was looking at group policy but did not want to create 20 different GPOs. I wanted to do this with a logon/startup script. I'm not sure if this is doable or feasible.</p>
<p>Edit #2:
This edit it really late to the party but I figured if anyone found this it could help. We ended up using item level targeting on User>Preferences>Control Panel>Printers objects. We made an account in AD for each group of users needing access to the printers. This worked although it did create a long logon process for the first logon of the computer. We also enabled Point-to-Print restrictions so the drivers were loaded from the servers quietly.</p> | 11,127,856 | 7 | 5 | null | 2012-06-20 18:40:36.88 UTC | 2 | 2022-01-09 15:25:19.173 UTC | 2017-12-01 03:24:25.583 UTC | null | 1,905,949 | null | 1,470,158 | null | 1 | 3 | windows|powershell|active-directory|active-directory-group | 63,694 | <p>This will give you the group membership (group names) of the local computer (requires powershell 2.0):</p>
<pre><code>([adsisearcher]"(&(objectCategory=computer)(cn=$env:COMPUTERNAME))").FindOne().Properties.memberof -replace '^CN=([^,]+).+$','$1'
</code></pre> |
15,200,548 | codeigniter join 2 table data | <p>hi everyone i am new to codeigniter and currently working on a small project in the project i am trying to join two tables and display there data in single table. i looked at the user guide that codeigniter has an i am not sure how this work</p>
<p><code>$this->db->join();</code></p>
<p>what table should be first and what id key should be firs. Can someone explain me more in detail about this please use examples if u can. I am trying to join credential table and tblanswers. Tnx for answering.</p>
<p>i have tried to code a function using this example:</p>
<pre><code>$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
</code></pre>
<p><strong>EDIT:</strong>
instead of using join method in codeigniter is it possible to use a simple function to retrieve the two table data separately? all i want is to echo the data from database table on to a html table in my website page to be displayed is it possible to write two get functions to retrieve two tables separately ?</p> | 15,200,609 | 5 | 1 | null | 2013-03-04 11:31:44.683 UTC | 2 | 2019-11-04 12:27:51.71 UTC | 2013-03-04 11:49:24.56 UTC | null | 2,071,072 | null | 2,071,072 | null | 1 | 9 | php|codeigniter|join | 69,637 | <p>It doesn't matter what table is first... Simply:</p>
<pre><code><?php
$this->db->select('t1.name, t2.something, t3.another')
->from('table1 as t1')
->where('t1.id', $id)
->join('table2 as t2', 't1.id = t2.id', 'LEFT')
->join('table3 as t3', 't1.id = t3.id', 'LEFT')
->get();
?>
</code></pre> |
24,504,582 | How to test whether stringstream operator>> has parsed a bad type and skip it | <p>I am interested in discussing methods for using <code>stringstream</code> to parse a line with multiple types. I would begin by looking at the following line:</p>
<pre><code>"2.832 1.3067 nana 1.678"
</code></pre>
<p>Now lets assume I have a long line that has multiple <code>strings</code> and <code>doubles</code>. The obvious way to solve this is to tokenize the string and then check converting each one. I am interested in skipping this second step and using <code>stringstream</code> directly to only find the numbers. </p>
<p>I figured a good way to approach this would be to read through the string and check if the <code>failbit</code> has been set, which it will if I try to parse a string into a double. </p>
<p>Say I have the following code:</p>
<pre><code>string a("2.832 1.3067 nana 1.678");
stringstream parser;
parser.str(a);
for (int i = 0; i < 4; ++i)
{
double b;
parser >> b;
if (parser.fail())
{
std::cout << "Failed!" << std::endl;
parser.clear();
}
std::cout << b << std::endl;
}
</code></pre>
<p>It will print out the following: </p>
<pre><code>2.832
1.3067
Failed!
0
Failed!
0
</code></pre>
<p>I am not surprised that it fails to parse a string, but <strong>what is happening internally such that it fails to clear its <code>failbit</code> and parse the next number?</strong></p> | 24,520,662 | 5 | 5 | null | 2014-07-01 07:22:16.173 UTC | 15 | 2015-03-31 11:31:28.103 UTC | 2014-07-01 23:56:20.197 UTC | null | 1,413,395 | null | 1,294,207 | null | 1 | 34 | c++|stringstream | 34,636 | <p>The following code works well to skip the <em>bad word</em> and collect the valid <code>double</code> values</p>
<pre><code>istringstream iss("2.832 1.3067 nana 1.678");
double num = 0;
while(iss >> num || !iss.eof()) {
if(iss.fail()) {
iss.clear();
string dummy;
iss >> dummy;
continue;
}
cout << num << endl;
}
</code></pre>
<p>Here's a <a href="http://ideone.com/BhVxSp" rel="noreferrer">fully working sample</a>.</p>
<hr>
<p>Your sample almost got it right, it was just missing to consume the invalid input field from the stream after detecting it's wrong format </p>
<pre><code> if (parser.fail()) {
std::cout << "Failed!" << std::endl;
parser.clear();
string dummy;
parser >> dummy;
}
</code></pre>
<p>In your case the extraction will try to read again from <code>"nana"</code> for the last iteration, hence the last two lines in the output.</p>
<p>Also note the trickery about <code>iostream::fail()</code> and how to actually test for <code>iostream::eof()</code> in my 1st sample. <a href="https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong">There's a well known Q&A</a>, why simple testing for EOF as a loop condition is considered wrong. And it answers well, how to break the input loop when unexpected/invalid values were encountered. But just how to skip/ignore invalid input fields isn't explained there (and wasn't asked for).</p> |
24,534,782 | How do (*SKIP) or (*F) work on regex? | <p>I'm learning an advanced usage of regex and noticed that many posts use <code>(*SKIP)</code> or <code>(*F)</code> in it.</p>
<p>I posted a question where the idea was to match lines that don't have <code>yellow</code> but has <code>blue</code> only if <code>brown</code> exists after blue. And the right answer was:</p>
<pre><code>.*yellow.*(*SKIP)(*F)|^.*\bblue\b(?=.*brown).*$
</code></pre>
<p>I also have tried lookaround expressions like below but haven't worked for all the cases:</p>
<pre><code>^((?!yellow).)*blue(?=.*brown).*$
</code></pre>
<p>I had no idea about these <code>(*SKIP)(*F)</code> flags, so the question is, how do these flag works? What do they do? And are there other flags like these?</p>
<p>Thanks.</p> | 24,535,912 | 2 | 5 | null | 2014-07-02 15:11:41.467 UTC | 21 | 2020-03-15 23:10:42.61 UTC | 2014-07-02 15:17:04.043 UTC | null | 2,193,767 | null | 710,099 | null | 1 | 33 | regex | 9,415 | <p>These two backtracking control verbs are implemented only in Perl, PCRE and the <a href="https://pypi.python.org/pypi/regex" rel="noreferrer">pypi regex module</a>.</p>
<p>The idea of the <code>(*SKIP)(*FAIL)</code> trick is to consume characters that you want to avoid, and that must not be a part of the match result.</p>
<p>A classical pattern that uses of this trick looks like that:</p>
<pre><code>What_I_want_to_avoid(*SKIP)(*FAIL)|What_I_want_to_match
</code></pre>
<p>A regex engine processes a string like that:</p>
<ul>
<li><p>the first token of the pattern is tested on each character from left to right <em>(by default most of the time, but some regex engines can be set to work from right to left, .net can do this if I remember well)</em></p></li>
<li><p>if the first token matches, then the regex engine tests the next token of the pattern with the next characters <em>(after the first token match)</em> etc.</p></li>
<li><p>when a token fails, the regex engine gets the characters matched by the last token back and tries another way to make the pattern succeed <em>(if it doesn't work too, the regex engine do the same with the previous token etc.)</em></p></li>
</ul>
<p>When the regex engine meets the <code>(*SKIP)</code> verb <em>(in this case all previous tokens have obviously succeeded)</em>, it has no right anymore to go back to all the previous tokens on the left and has no right anymore to retry all the matched characters with another branch of the pattern or at the next position in the string until the last matched character <em>(included)</em> if the pattern fails later on the right of the <code>(*SKIP)</code> verb.</p>
<p>The role of <code>(*FAIL)</code> is to force the pattern to fail. Thus all the characters matched on the left of <code>(*SKIP)</code> are skipped and the regex engine continues its job after these characters.</p>
<p>The only possibility for the pattern to succeed in the example pattern is that the first branch fails before <code>(*SKIP)</code> to allow the second branch to be tested.</p>
<p>You can find another kind of explanation <a href="https://stackoverflow.com/questions/19992984/verbs-that-act-after-backtracking-and-failure/20008790#20008790">here</a>.</p>
<h3>About Java <sup> <sub> and other regex engines that don't have these two features</sub></sup></h3>
<p>Backtracking control verbs are not implemented in other regex engines and there are no equivalent.</p>
<p>However, you can use several ways to do the same <em>(to be more clear, to avoid something that can be possibly matched by an other part of the pattern)</em>.</p>
<p><strong>The use of capture groups:</strong></p>
<p>way 1:</p>
<pre><code>What_I_want_to_avoid|(What_I_want_to_match)
</code></pre>
<p>You only need to extract the capture group 1 <em>(or to test if it exists)</em>, since it is what you are looking for. If you use the pattern to perform a replacement, you can use the properties of the match result (offset, length, capture group) to make the replacement with classical string functions. Other language like javascript, ruby... allows to use a callback function as replacement.</p>
<p>way 2:</p>
<pre><code>((?>To_avoid|Other_things_that_can_be_before_what_i_want)*)(What_I_want)
</code></pre>
<p>It's the more easy way for the replacement, no need to callback function, the replacement string need only to begin with <code>\1</code> <em>(or <code>$1</code>)</em></p>
<p><strong>The use of lookarounds:</strong></p>
<p>example, you want to find a word that is not embedded between two other words (lets say <code>S_word</code> and <code>E_word</code> that are different <em>(see Qtax comment)</em>):</p>
<p><em>(the edge cases <code>S_word E_word word E_word</code> and <code>S_word word S_word E_word</code> are allowed in this example.)</em></p>
<p>The backtracking control verb way will be:</p>
<pre><code>S_word not_S_word_or_E_word E_word(*SKIP)(*F)|word
</code></pre>
<p>To use this way the regex engine needs to allow variable length lookbehinds to a certain extent. With .net or the new regex module, no problems, lookbehinds can have a totally variable length. It is possible with Java too but the size must be limited <em>(example: <code>(?<=.{1,1000})</code>)</em>.</p>
<p>The Java equivalent will be:</p>
<pre><code>word(?:(?!not_S_word_or_E_word E_word)|(?<!S_word not_E_word{0,1000} word))
</code></pre>
<p>Note that in some cases, only the lookahead is necessary. Note too that starting a pattern with literal character is more efficient than starting with a lookbehind, that's why I putted it after the word <em>(even if I need to rewrite the word one more time in the assertion.)</em></p> |
11,843,677 | sum of two different columns (with additions) of different tables and multiple table joining in Oracle | <p>I have three tables.</p>
<p>SCHOOL: schoolcode(PK), year, schoolname.<br/>
ENROLMENT: schoolcode, year, caste, c1, c2, c3, c4, c5, c6, c7, c8 <br/>
CLASS: schoolcode, year, classid, rooms<br/></p>
<p>Now, I want to find the list of schools with enrolment in class-1 to 4 and number of classrooms used by class 1-4 (CLASSID is defined as: 7 for class-1&2, 8 for class-3&4, 9 for class-5&6, 10 for class-7&8; and caste is defined as 1 for general, 2 for sc, 3 for st, 4 for others).</p>
<p>I used the following query:</p>
<pre><code>select m.schoolcode, m.schoolname, sum(e.c1+e.c2+e.c3+e.c4), sum(c.rooms)
from dise2k_enrolment09 e,
dise2k_master m ,
dise2k_clsbycondition c
where m.schoolcode=e.schoolcode and
m.schoolcode=c.schoolcode and
e.year='2011-12' and
m.year='2011-12' and
c.year='2011-12' and
c.classid in(7,8) and
e.caste in(1,2,3,4)
group by m.schoolcode, m.schoolname
</code></pre>
<p>But the result showing is not correct. Enrolment is showing much higher than actual, same in case of classrooms.</p> | 11,844,187 | 1 | 2 | null | 2012-08-07 10:11:06.533 UTC | null | 2012-08-07 10:45:04.553 UTC | 2012-08-07 10:45:04.553 UTC | null | 330,315 | null | 1,579,132 | null | 1 | 3 | sql|oracle11g|sum | 48,412 | <p>Ok, try this to see if your problem arises from duplicating records in join:</p>
<pre><code>select m.schoolcode, m.schoolname, e_sum, c_sum
from dise2k_master m
inner join
(
select schoolcode,
sum(c1 + c2 + c3 + c4) e_sum
from dise2k_enrolment09
where year='2011-12'
and caste in(1,2,3,4)
group by schoolcode
) e
on m.schoolcode=e.schoolcode
inner join
(
select schoolcode,
sum(rooms) c_sum
from dise2k_clsbycondition
where year='2011-12'
and classid in(7,8)
group by schoolcode
) c
on m.schoolcode=c.schoolcode
where m.year='2011-12'
</code></pre> |
37,555,403 | Android BottomSheetDialogFragment does not expand completely | <p>I have the following test bottom sheet implementation. </p>
<p>When I set the peekHeight to a value less than 500, it works. After some value, any increase in peek height will not change how the bottom sheet is expanded. It Just remains there to only drag manually. How do we set the peekHeight programmatically to ensure that the bottom sheet is auto expanded to the peek height.</p>
<p><a href="https://i.stack.imgur.com/C3OgV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/C3OgV.png" alt="enter image description here"></a></p>
<p><strong>bottom_sheet_dialog_main</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/locUXCoordinatorLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/locUXView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:orientation="vertical"
app:behavior_hideable="false"
app:behavior_peekHeight="0dp"
app:layout_behavior="@string/bottom_sheet_behavior">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="1 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="2 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="3 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="4 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="5 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="6 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="7 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="8 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="9 Value" />
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="First Value" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</code></pre>
<p><strong>Java code</strong></p>
<pre><code>public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
private static BottomSheetBehavior bottomSheetBehavior;
private static View bottomSheetInternal;
private static MyBottomSheetDialogFragment INSTANCE;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
BottomSheetDialog d = (BottomSheetDialog) dialog;
CoordinatorLayout coordinatorLayout = (CoordinatorLayout)d.findViewById(R.id.locUXCoordinatorLayout);
bottomSheetInternal = d.findViewById(R.id.locUXView);
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetInternal);
bottomSheetBehavior.setPeekHeight(bottomSheetInternal.getHeight());
bottomSheetInternal.requestLayout();
coordinatorLayout.getLayoutParams().height = bottomSheetInternal.getHeight();
Toast.makeText(getActivity(), "Height is" + bottomSheetInternal.getHeight() + " " + coordinatorLayout.getLayoutParams().height, Toast.LENGTH_LONG).show();
}
});
INSTANCE = this;
return inflater.inflate(R.layout.bottom_sheet_dialog_main, container, false);
}
}
</code></pre> | 37,782,673 | 10 | 3 | null | 2016-05-31 20:52:04.573 UTC | 11 | 2022-06-26 07:30:56.827 UTC | 2016-06-17 04:30:55.407 UTC | null | 651,714 | null | 651,714 | null | 1 | 30 | java|android|android-support-library|android-support-design|bottom-sheet | 41,089 | <p>By deeper UI inspection, we find that there is another <code>CoordinatorLayout</code> that wraps our coordinator layout. The parent <code>CoordinatorLayout</code> has a <code>FrameLayout</code> with a <code>BottomSheetBehavior</code>with the id <code>design_bottom_sheet</code>. The peek height set from our code above was getting constrained due the <code>match_parent</code> height of the <code>FrameLayout</code> with the id <code>design_bottom_sheet</code></p>
<p>By setting the peek height of the <code>FrameLayout</code> with the id design_bottom_sheet , this issue was resolved</p>
<pre><code> public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
BottomSheetDialog d = (BottomSheetDialog) dialog;
coordinatorLayout = (CoordinatorLayout) d.findViewById(R.id.locUXCoordinatorLayout);
bottomSheetInternal = d.findViewById(R.id.locUXView);
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetInternal);
bottomSheetBehavior.setHidable(false);
BottomSheetBehavior.from((View)coordinatorLayout.getParent()).setPeekHeight(bottomSheetInternal.getHeight());
bottomSheetBehavior.setPeekHeight(bottomSheetInternal.getHeight());
coordinatorLayout.getParent().requestLayout();
}
});
</code></pre> |
21,525,282 | For else loop in Javascript? | <p>Is there a Javascript equivalent of the python 'for-else' loop, so something like this:</p>
<pre><code>searched = input("Input: ");
for i in range(5):
if i==searched:
print("Search key found: ",i)
break
else:
print("Search key not found")
</code></pre>
<p>Or do I just have to resort to a flag variable, so something like this:</p>
<pre><code>var search = function(num){
found = false;
for(var i in [0,1,2,3,4]){
if(i===num){
console.log("Match found: "+ i);
found = true;
}
}
if(!found){
console.log("No match found!");
}
};
</code></pre> | 21,525,388 | 8 | 5 | null | 2014-02-03 10:48:15.413 UTC | 8 | 2021-03-30 11:35:06.667 UTC | 2016-05-26 19:07:57.343 UTC | user2664110 | 1,577,850 | user2664110 | null | null | 1 | 51 | javascript | 31,200 | <p>Working example (you need to use the flag):</p>
<pre><code>var search = function(num){
var found = false;
for(var i=0; i<5; i++){
if(i===num){
console.log("Match found: "+ i);
found = true;
break;
}
}
if(!found){
console.log("No match found!");
}
};
</code></pre> |
19,622,572 | How to generate maximally unbalanced AVL trees | <p>I have written a <a href="https://github.com/waltertross/avl">C language library of AVL trees as general purpose sorted containers</a>. For testing purposes, I would like to have a way to fill a tree so that it is maximally unbalanced, i.e., so that it has the maximum height for the number of nodes it contains.</p>
<p>AVL trees have the nice property that if, starting from the empty tree, you insert nodes in ascending (or descending) order, the tree is always exactly balanced (i.e., it has its minimum height for a given number of nodes). One sequence of integer keys that generates an exactly balanced AVL tree T<sub>n</sub> for every number of nodes n, starting from the empty tree T<sub>0</sub>, is simply</p>
<ul>
<li>k<sub>1</sub> = 0</li>
<li>k<sub>n+1</sub> = k<sub>n</sub>+1 , i.e., k<sub>n</sub> = n-1</li>
</ul>
<p>I'm looking for a (hopefully simple) sequence of integer keys that, when inserted in the initially empty tree T<sub>0</sub>, generates AVL trees T<sub>0</sub>, ..., T<sub>n</sub> that are all maximally <b>un</b>balanced.</p>
<p>I would also be interested in a solution where only the last tree, T<sub>n</sub>, is maximally unbalanced (the number of nodes n would be a parameter of the algorithm).</p>
<p>A solution satisfying the constraint</p>
<ul>
<li>max(k<sub>1</sub>, ..., k<sub>n</sub>) - min(k<sub>1</sub>, ..., k<sub>n</sub>) + 1 ≤ 2 n</li>
</ul>
<p>is preferrable, but not strictly required. A key range of 4 n instead of 2 n may be a reasonable target.</p>
<p>I've not been able to find anything on the Internet regarding the generation, by insertion, of AVL trees of maximal height. Of course, the sequence of generated trees I'm looking for will include all so-called Fibonacci-trees, which are the AVL trees of a given depth with the minimal number of nodes. Funnily, the English Wikipedia does not even mention Fibonacci trees (nor Fibonacci numbers!) in the article on AVL trees, while the German Wikipedia has a very good <a href="http://de.wikipedia.org/wiki/Fibonacci-Baum">article</a> completely dedicated to them. But I'm still in the dark regarding my question.</p>
<p>C language bit twiddling hacks are welcome.</p> | 19,682,662 | 3 | 6 | null | 2013-10-27 19:39:44.86 UTC | 9 | 2013-11-07 08:42:40.587 UTC | 2013-10-30 12:46:44.743 UTC | null | 1,046,007 | null | 1,046,007 | null | 1 | 23 | c|algorithm|data-structures|tree|avl-tree | 3,038 | <p><strong>Basic Solution</strong></p>
<p>Fibonacci trees have several properties that can be used to form a compact Fibonacci tree:</p>
<ol>
<li>Every node in a Fibonacci tree is itself a Fibonacci tree.</li>
<li>The number of nodes in a Fibonacci tree of height n is equal to F<sub>n+2</sub> - 1.</li>
<li>The number of nodes in between a node and its left child is equal to the number of nodes in the node's left child's right child.</li>
<li>The number of nodes in between a node and its right child is equal to the number of nodes in the node's right child's left child.</li>
</ol>
<p>Without loss of generality, we will assume our Fibonacci tree has the following additional property:</p>
<ol>
<li>If a node has height n, then the left child has height n-2, and the right child has height n-1.</li>
</ol>
<p>Combining these properties, we find that the number of nodes in between a node of height n and its left and right children is equal to F<sub>n-1</sub> - 1, and we can use this fact to generate a compact Fibonacci tree:</p>
<pre><code>static int fibs[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170};
void fibonacci_subtree(int root, int height, int *fib)
{
if (height == 1) {
insert_into_tree(root);
} else if (height == 2) {
insert_into_tree(root + *fib);
} else if (height >= 3) {
fibonacci_subtree(root - *fib, height - 2, fib - 2);
fibonacci_subtree(root + *fib, height - 1, fib - 1);
}
}
...
for (height = 1; height <= max_height; height++) {
fibonacci_subtree(0, height, fibs + max_height - 1);
}
</code></pre>
<p>This algorithm generates the minimum number of nodes possible for a given height, and it also produces the minimum possible range. You can shift the range around by making the root node something other than zero.</p>
<p><strong>Compact Fill Algorithm</strong></p>
<p>The basic solution only produces Fibonacci trees, which always have F<sub>n+2</sub> - 1 nodes. What if you want to generate an unbalanced tree with a different number of nodes while still minimizing the range?</p>
<p>In that case, you need to generate the next larger Fibonacci tree with a few modifications:</p>
<ul>
<li>Some number of elements at the end of the sequence will not be inserted.</li>
<li>Those elements will create gaps, and the location of those gaps need to be tracked.</li>
<li>The difference between nodes needs to be reduced appropriately.</li>
</ul>
<p>Here's one approach that still takes advantage of the recursive nature of the solution:</p>
<pre><code>void fibonacci_subtree(int root, int height, int *fib, int num_gaps, bool prune_gaps)
{
if(height < 1)
return;
if(prune_gaps && height <= 2) {
if(!num_gaps) {
if(height == 1) {
insert_into_tree(root);
} else if(height == 2) {
insert_into_tree(root + *fib);
}
}
return;
}
if(height == 1) {
insert_into_tree(root);
} else {
int max_rr_gaps = *(fib - 1);
int rr_gaps = num_gaps > max_rr_gaps ? max_rr_gaps : num_gaps;
num_gaps -= rr_gaps;
int max_rl_gaps = *(fib - 2);
int rl_gaps = num_gaps > max_rl_gaps ? max_rl_gaps : num_gaps;
num_gaps -= rl_gaps;
int lr_gaps = num_gaps > max_rl_gaps ? max_rl_gaps : num_gaps;
num_gaps -= lr_gaps;
int ll_gaps = num_gaps;
fibonacci_subtree(root - *fib + lr_gaps, height - 2, fib - 2, lr_gaps + ll_gaps, prune_gaps);
fibonacci_subtree(root + *fib - rl_gaps, height - 1, fib - 1, rr_gaps + rl_gaps, prune_gaps);
}
}
</code></pre>
<p>The main loop is slightly more complicated to accommodate an arbitrary range of keys:</p>
<pre><code>void compact_fill(int min_key, int max_key)
{
int num_nodes = max_key - min_key + 1;
int *fib = fibs;
int max_height = 0;
while(num_nodes > *(fib + 2) - 1) {
max_height++;
fib++;
}
int num_gaps = *(fib + 2) - 1 - num_nodes;
int natural_max = *(fib + 1) - 1;
int max_r_gaps = *(fib - 1);
int r_gaps = num_gaps > max_r_gaps ? max_r_gaps : num_gaps;
natural_max -= r_gaps;
int root_offset = max_key - natural_max;
for (int height = 1; height <= max_height; height++) {
fibonacci_subtree(root_offset, height, fibs + max_height - 1, num_gaps, height == max_height);
}
}
</code></pre>
<p><strong>Closed Form Solution</strong></p>
<p>If you look at the differences between every pair of words generated by the basic solution, you find that they alternate between two sequential elements of the Fibonacci sequence. This alternating pattern is defined by the <a href="http://en.wikipedia.org/wiki/Fibonacci_word" rel="noreferrer">Fibonacci word</a>:</p>
<blockquote>
<p>A Fibonacci word is a specific sequence of binary digits (or symbols from any two-letter alphabet). The Fibonacci word is formed by repeated concatenation in the same way that the Fibonacci numbers are formed by repeated addition.</p>
</blockquote>
<p>It turns out there's a <a href="http://en.wikipedia.org/wiki/Fibonacci_word#Closed-form_expression_for_individual_digits" rel="noreferrer">closed-form solution for the Fibonacci word</a>:</p>
<pre><code>static double phi = (1.0 + sqrt(5.0)) / 2.0;
bool fibWord(int n)
{
return 2 + floor(n * phi) - floor((n + 1) * phi);
}
</code></pre>
<p>You can use this closed-form solution to solve the problem using two nested loops:</p>
<pre><code>// Used by the outer loop to calculate the first key of the inner loop
int outerNodeKey = 0;
int *outerFib = fibs + max_height - 1;
for(int height = 1; height <= max_height; height++) {
int innerNodeKey = outerNodeKey;
int *smallFib = fibs + max_height - height + 3; // Hat tip: @WalterTross
for(int n = fibs[height] - 1; n >= 0; n--) {
insert_into_tree(innerNodeKey);
// Use closed-form expression to pick between two elements of the Fibonacci sequence
bool smallSkip = 2 + floor(n * phi) - floor((n + 1) * phi);
innerNodeKey += smallSkip ? *smallFib : *(smallFib + 1);
}
if(height & 0x1) {
// When height is odd, add *outerFib.
outerNodeKey += *outerFib;
} else {
// Otherwise, backtrack and reduce the gap for next time.
outerNodeKey -= (*outerFib) << 1;
outerFib -= 2;
}
}
</code></pre> |
45,086,981 | What are the vim commands that start with g? | <p><code>g</code> is a prefix to several commands. e.g. goto to move the cursor, but also <code>gqip</code> to format a paragraph. Where is the reference for all commands that are prefixed with <code>g</code>?</p> | 45,087,113 | 2 | 5 | null | 2017-07-13 17:02:14.453 UTC | 7 | 2017-07-13 17:31:34.797 UTC | null | null | null | null | 331,858 | null | 1 | 36 | vim | 23,455 | <p>Vim's documentation is <a href="http://vimdoc.sourceforge.net/" rel="noreferrer">http://vimdoc.sourceforge.net/</a>. If you go for the HTML docs, you will find <a href="http://vimdoc.sourceforge.net/htmldoc/help.html#reference_toc" rel="noreferrer"><code>|reference_toc| More detailed information for all commands</code></a>, which includes <code>|index.txt| alphabetical index of all commands</code>, which -- due to an unfortunate quirk with the doc file named <code>index.txt</code> and linked as <code>index.html</code> -- doesn't actually lead to where you would expect it to lead.</p>
<p>Long story short, <a href="http://vimdoc.sourceforge.net/htmldoc/vimindex.html#g" rel="noreferrer">http://vimdoc.sourceforge.net/htmldoc/vimindex.html#g</a> is the documentation you are looking for ("Commands starting with 'g'").</p>
<p>Alternatively, type <code>:help *g*</code> in Vim.</p>
<p>(Sorry merlin2011 but your list is somewhat incomplete...)</p>
<hr>
<p>Some reformatting applied:</p>
<pre><code>2.4 Commands starting with 'g'
char note action in Normal mode
------------------------------------------------------------------
g CTRL-A only when compiled with MEM_PROFILE
defined: dump a memory profile
g CTRL-G show information about current cursor
position
g CTRL-H start Select block mode
g CTRL-] |:tjump| to the tag under the cursor
g# 1 like "#", but without using "\<" and "\>"
g$ 1 when 'wrap' off go to rightmost character of
the current line that is on the screen;
when 'wrap' on go to the rightmost character
of the current screen line
g& 2 repeat last ":s" on all lines
g'{mark} 1 like |'| but without changing the jumplist
g`{mark} 1 like |`| but without changing the jumplist
g* 1 like "*", but without using "\<" and "\>"
g0 1 when 'wrap' off go to leftmost character of
the current line that is on the screen;
when 'wrap' on go to the leftmost character
of the current screen line
g8 print hex value of bytes used in UTF-8
character under the cursor
g< display previous command output
g? 2 Rot13 encoding operator
g?? 2 Rot13 encode current line
g?g? 2 Rot13 encode current line
gD 1 go to definition of word under the cursor
in current file
gE 1 go backwards to the end of the previous
WORD
gH start Select line mode
gI 2 like "I", but always start in column 1
gJ 2 join lines without inserting space
["x]gP 2 put the text [from register x] before the
cursor N times, leave the cursor after it
gQ switch to "Ex" mode with Vim editing
gR 2 enter Virtual Replace mode
gU{motion} 2 make Nmove text uppercase
gV don't reselect the previous Visual area
when executing a mapping or menu in Select
mode
g] :tselect on the tag under the cursor
g^ 1 when 'wrap' off go to leftmost non-white
character of the current line that is on
the screen; when 'wrap' on go to the
leftmost non-white character of the current
screen line
ga print ascii value of character under the
cursor
gd 1 go to definition of word under the cursor
in current function
ge 1 go backwards to the end of the previous
word
gf start editing the file whose name is under
the cursor
gF start editing the file whose name is under
the cursor and jump to the line number
following the filename.
gg 1 cursor to line N, default first line
gh start Select mode
gi 2 like "i", but first move to the |'^| mark
gj 1 like "j", but when 'wrap' on go N screen
lines down
gk 1 like "k", but when 'wrap' on go N screen
lines up
gm 1 go to character at middle of the screenline
go 1 cursor to byte N in the buffer
["x]gp 2 put the text [from register x] after the
cursor N times, leave the cursor after it
gq{motion} 2 format Nmove text
gr{char} 2 virtual replace N chars with {char}
gs go to sleep for N seconds (default 1)
gu{motion} 2 make Nmove text lowercase
gv reselect the previous Visual area
gw{motion} 2 format Nmove text and keep cursor
gx execute application for file name under the
cursor (only with |netrw| plugin)
g@{motion} call 'operatorfunc'
g~{motion} 2 swap case for Nmove text
g<Down> 1 same as "gj"
g<End> 1 same as "g$"
g<Home> 1 same as "g0"
g<LeftMouse> same as <C-LeftMouse>
g<MiddleMouse> same as <C-MiddleMouse>
g<RightMouse> same as <C-RightMouse>
g<Up> 1 same as "gk"
note: 1 = cursor movement command; 2 = can be undone/redone
</code></pre> |
30,334,216 | dd($request->all()); gives back empty array | <p>I am trying to upload a photo from my Laravel 5 app to be stored in AWS. I am using the Postman REST client to test. When I upload a photo, the request returns an empty array. Does anyone know why this might be? Here's the code for my Avatar Controller: </p>
<pre><code>class AvatarController extends Controller
{
public function __construct(AWS $aws)
{
$this->aws = $aws;
}
/**
* Store a new avatar for a user.
* POST northstar.com/users/{id}/avatar
*/
public function store(User $user, Request $request)
{
dd($request->all());
// dd($request->file('photo'));
$file = $request->file('photo');
// $file = Request::file('photo');
// $file = Input::file('photo');
$v = Validator::make(
$request->all(),
['photo' => 'required|image|mimes:jpeg,jpg|max:8000']
);
if($v->fails())
return Response::json(['error' => $v->errors()]);
$filename = $this->aws->storeImage('avatars', $file);
// Save filename to User model
$user->avatar = $filename;
$user->save();
// Respond to user with success
return response()->json('Photo uploaded!', 200);
}
}
</code></pre> | 30,463,600 | 10 | 4 | null | 2015-05-19 19:11:34.05 UTC | 3 | 2021-12-16 14:51:11.56 UTC | null | null | null | null | 4,422,345 | null | 1 | 23 | php|laravel | 43,176 | <p>Found the answer - looks like there was an issue with my headers in Postman. I had both Accept application/json and Content-Type application/json. Once I removed Content-Type, all is fixed. Thanks! </p> |
18,287,960 | Signing Windows application on Linux-based distros | <p>I have prepared an application and website where the customer can set several options for this application before he downloads it. Settings are stored in binary format on the end of the file (appended), then the edited file is sent to the end user. The problem is that the change of "contents" of the file will break the file signature - is there any chance to re-sign this changed file with any command line tools? I've tried to use Microsoft's SignTool, but it does not work properly on Linux.</p> | 18,288,049 | 3 | 0 | null | 2013-08-17 10:52:51.663 UTC | 27 | 2021-02-23 16:24:22.74 UTC | null | null | null | null | 669,357 | null | 1 | 34 | linux|windows|certificate|exe|sign | 22,489 | <p>It's actually <a href="https://developer.mozilla.org/en-US/docs/Signing_an_executable_with_Authenticode" rel="nofollow noreferrer">quite straight forward</a> to do using <code>Mono</code>'s signtool; the tricky part (described in more detail in the linked Mozilla article) is copying the certificate in the correct format from Windows to Linux.</p>
<p>Converting the Windows PFX certificate file to PVK and SPC files, only needs to be done once when copying the certificate from Windows to Linux;</p>
<pre><code>openssl pkcs12 -in authenticode.pfx -nocerts -nodes -out key.pem
openssl rsa -in key.pem -outform PVK -pvk-strong -out authenticode.pvk
openssl pkcs12 -in authenticode.pfx -nokeys -nodes -out cert.pem
openssl crl2pkcs7 -nocrl -certfile cert.pem -outform DER -out authenticode.spc
</code></pre>
<p>Actually signing the exe is straight forward;</p>
<pre><code>signcode \
-spc authenticode.spc \
-v authenticode.pvk \
-a sha1 -$ commercial \
-n My\ Application \
-i http://www.example.com/ \
-t http://timestamp.digicert.com/scripts/timstamp.dll \
-tr 10 \
MyApp.exe
</code></pre> |
26,202,568 | Android: pass function reference to AsyncTask | <p>I'm new to android and very used to web developing. in javascript when you want to perform an asynchronous task you pass a function as an argument (a callback):</p>
<pre><code>http.get('www.example.com' , function(response){
//some code to handle response
});
</code></pre>
<p>I was wondering if we can do the same with android's <code>AsyncTask</code> , pass a function reference to the <code>onPostExecute()</code> method , and it will run it.</p>
<p>any suggestions ?</p> | 26,202,602 | 4 | 2 | null | 2014-10-05 12:27:46.163 UTC | 11 | 2021-04-02 20:26:32.04 UTC | null | null | null | null | 3,794,544 | null | 1 | 18 | java|android|android-asynctask | 15,237 | <p>Yes the concept of callbacks also very much exists in Java. In Java you define a callback like this:</p>
<pre><code>public interface TaskListener {
public void onFinished(String result);
}
</code></pre>
<p>One would often nest these kind of listener definitions inside the <code>AsyncTask</code> like this:</p>
<pre><code>public class ExampleTask extends AsyncTask<Void, Void, String> {
public interface TaskListener {
public void onFinished(String result);
}
...
}
</code></pre>
<p>And a complete implementation of the callback in the <code>AsyncTask</code> would look like this:</p>
<pre><code>public class ExampleTask extends AsyncTask<Void, Void, String> {
public interface TaskListener {
public void onFinished(String result);
}
// This is the reference to the associated listener
private final TaskListener taskListener;
public ExampleTask(TaskListener listener) {
// The listener reference is passed in through the constructor
this.taskListener = listener;
}
@Override
protected String doInBackground(Void... params) {
return doSomething();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// In onPostExecute we check if the listener is valid
if(this.taskListener != null) {
// And if it is we call the callback function on it.
this.taskListener.onFinished(result);
}
}
}
</code></pre>
<p><code>onPostExecute()</code> is called as soon as the background task finishes. You can use the whole thing like this:</p>
<pre><code>ExampleTask task = new ExampleTask(new ExampleTask.TaskListener() {
@Override
public void onFinished(String result) {
// Do Something after the task has finished
}
});
task.execute();
</code></pre>
<p>Or you can define the <code>TaskListener</code> completely separately like this:</p>
<pre><code>ExampleTask.TaskListener listener = new ExampleTask.TaskListener() {
@Override
public void onFinished(String result) {
// Do Something after the task has finished
}
};
ExampleTask task = new ExampleTask(listener);
task.execute();
</code></pre>
<p>Or you can subclass <code>TaskListener</code> like this:</p>
<pre><code>public class ExampleTaskListener implements TaskListener {
@Override
public void onFinished(String result) {
}
}
</code></pre>
<p>And then use it like this:</p>
<pre><code>ExampleTask task = new ExampleTask(new ExampleTaskListener());
task.execute();
</code></pre>
<hr>
<p>You can of course just override the <code>onPostExecute()</code> method of the <code>AsyncTask</code>, but that is not recommended and in most cases actually pretty bad practice. For example you could do this:</p>
<pre><code>ExampleTask task = new ExampleTask() {
@Override
public void onPostExecute(String result) {
super.onPostExecute(result);
// Your code goes here
}
};
</code></pre>
<p>This will work just as well as the implementation above with a separate listener interface, but there are a few problems with this:</p>
<p>First and foremost you can actually break the <code>ExampleTask</code> all together. It all comes down to the <code>super.onPostExecute()</code> call above. If you as a developer override <code>onPostExecute()</code> like above and forget to include the super call or simply delete it for whatever reason that the original <code>onPostExecute()</code> method in the <code>ExampleTask</code> will not be called anymore. For example the whole listener implementation with the <code>TaskListener</code> would suddenly not work anymore since the call to the callback is implemented in <code>onPostExecute()</code>. You can also break the <code>TaskListener</code> in many other ways by unknowingly or unwittingly influencing the state of the <code>ExampleTask</code> so it won't work anymore.</p>
<p>If you look at what's actually happening when you override a method like this than it becomes much more clear what's going on. By overriding <code>onPostExecute()</code> you are creating a new subclass of <code>ExampleTask</code>. It would be the exact same thing as doing this:</p>
<pre><code>public class AnotherExampleTask extends ExampleTask {
@Override
public void onPostExecute(String result) {
super.onPostExecute(result);
// Your code goes here
}
}
</code></pre>
<p>All this is just hidden behind a language feature called anonymous classes. Suddenly overriding a method like this doesn't seem so clean and quick anymore does it?</p>
<p>To summarise: </p>
<ul>
<li>Overriding a method like this actually creates a new subclass. You are not just adding a callback, you are modifying how this class works and can unknowingly break oh so many things.</li>
<li>Debugging errors like this can be much more than just a pain in the a**. Because suddenly <code>ExampleTask</code> could throw <code>Exceptions</code> or simply not work anymore for no apparent reason, because you never actually modified its code.</li>
<li>Each class has to provide listener implementations at places where it is appropriate and intended. Sure you can just add them later on by overriding <code>onPostExecute()</code> but that is always very dangerous. Even @flup with his 13k reputation has forgotten to include the <code>super.onPostExecute()</code> call in his answer, imagine what some other not as experienced developer might do! </li>
<li>A little abstraction never hurt anybody. Writing specific listeners might be slightly more code, but it is a much better solution. The code will be cleaner, more readable and a lot more maintainable. Using shortcuts like overriding <code>onPostExecute()</code> essentially sacrifices code quality for a little bit convenience. That is never a good idea an will just cause problems in the long run.</li>
</ul> |
5,199,256 | Using middle-dot ASCII with proper support? | <p>I'm using the middle dot - <code>·</code> - a lot in my website. The ASCII is <code>&#183;</code>, which works fine. However, there are still some problems with some users not seeing the symbol. Is there a very close but more widely supported symbol like this, or is there a way to output the symbol to ensure full support?</p> | 5,202,860 | 3 | 4 | null | 2011-03-04 21:06:27.76 UTC | 2 | 2018-10-19 16:12:30.843 UTC | 2018-10-19 16:12:30.843 UTC | null | 416,314 | null | 361,883 | null | 1 | 12 | html|unicode|ascii|special-characters | 70,107 | <p>Whether you use the actual <code>·</code> character or the HTML <code>&#183;</code> entity, make sure <code>ISO-8859-1</code> is being reported to the browser correctly, either in the <code>charset</code> attribute of the HTTP <code>Content-Type</code> response header, or in a <code><meta http-equiv="Content-Type" value="text/html; charset=ISO-8859-1"></code> tag (HTML 4 and earlier) or <code><meta charset="ISO-8859-1"></code> tag (HTML 5) inside the HTML itself.</p> |
9,515,630 | lldb fails to print variable values with "error: reference to 'id' is ambiguous" | <p>Since I updated to xcode 4.3 and let it switch my debugger over to lldb, any request to print a member variable fails with this error message:</p>
<pre><code>(lldb) print request
error: error: reference to 'id' is ambiguous
note: candidate found by name lookup is 'id'
note: candidate found by name lookup is 'id'
error: 1 errors parsing expression
</code></pre>
<p>'self' is ok:</p>
<pre><code>(lldb) print self
(LoginViewController *) $6 = 0x1cd54d50
</code></pre>
<p>And other forms of printing the member variable also fail:</p>
<pre><code>(lldb) print self.request
error: property 'request' not found on object of type 'LoginViewController *'; did you mean to access ivar 'request'?
error: 1 errors parsing expression
(lldb) print self->request
error: error: reference to 'id' is ambiguous
note: candidate found by name lookup is 'id'
note: candidate found by name lookup is 'id'
error: 1 errors parsing expression
</code></pre>
<p>Everything else otherwise seems to be working fine. Xcode's variable window can correctly retrieve the value. I've tried a clean build and deleting ~/Library/Developer/Xcode/DerivedData/. Googling hasn't revealed any other instances of the same problem.</p>
<p>I found one thread on Apple's dev forum but no solution:</p>
<p><a href="https://devforums.apple.com/message/623694" rel="noreferrer">https://devforums.apple.com/message/623694</a></p>
<p>I've reported this to Apple as Bug ID# 11029004.</p> | 9,516,032 | 5 | 5 | null | 2012-03-01 11:48:57.353 UTC | 6 | 2015-07-22 12:11:59.427 UTC | 2012-05-01 06:24:22.023 UTC | null | 411,807 | null | 292,166 | null | 1 | 46 | objective-c|ios|xcode4.3|lldb | 18,945 | <p>I found one workaround:</p>
<p>Use 'Edit scheme' under the 'Product' menu, select 'Run' in the left bar, the 'Info' tab, and change the Debugger to gdb (this does not apply to xcode 5, which no longer has gdb).</p>
<p>Apparently Apple thought they'd fixed this bug in xcode 4.3.1, but it still happens. I submitted some extra debug information they requested, so I'm hoping it'll be fixed for the next release of xcode. It's still failing in 4.3.2. See <a href="https://devforums.apple.com/message/623694" rel="nofollow noreferrer">https://devforums.apple.com/message/623694</a> for an update from Apple.</p>
<p><strong>UPDATE</strong></p>
<p>I've tried various cases I was having trouble with, and they all seem to be working fine with lldb in Xcode 4.4.1 - hence I highly recommend upgrading if you're having this problem.</p> |
18,458,734 | How do I plot list of tuples in Python? | <p>I have the following data set. I would like to use Python or Gnuplot to plot the data. The tuples are of the form <code>(x, y)</code>. The Y-axis should be a log axis, that is, <code>log(y)</code>. A scatter plot or line plot would be ideal.</p>
<p>How can this be done?</p>
<pre><code> [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
</code></pre> | 18,458,953 | 5 | 0 | null | 2013-08-27 06:46:26.637 UTC | 23 | 2020-03-11 08:47:05.32 UTC | 2020-03-03 03:19:58.127 UTC | null | 3,924,118 | null | 2,200,667 | null | 1 | 71 | python|numpy|matplotlib|scipy|gnuplot | 142,113 | <p>If I get your question correctly, you could do something like this.</p>
<pre><code>>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()
</code></pre>
<p>which would give you something like</p>
<p><img src="https://i.stack.imgur.com/vfaqW.png" alt="enter image description here"></p>
<p>Or as a line plot,</p>
<pre><code>>>> plt.plot(*zip(*testList2))
>>> plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/3IGA6.png" alt="enter image description here"></p>
<p><strong>EDIT</strong> - If you want to add a title and labels for the axis, you could do something like</p>
<pre><code>>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()
</code></pre>
<p>which would give you</p>
<p><img src="https://i.stack.imgur.com/oEhsK.png" alt="enter image description here"></p> |
18,693,463 | jQuery .trigger("change") not working | <p>I can't get <code>.trigger("change")</code> to work. Anyone know why?</p>
<pre><code>jQuery(document).ready(function () {
jQuery("select[id='DROPDOWNID']").change(function () {
var selectedIndex = jQuery("select[id='DROPDOWNID']").prop('selectedIndex');
switch (selectedIndex) {
case 0:
hideVarforProspekt();
break;
case 1:
hideOrdervarde();
break;
case 2:
break;
case 3:
hideSektor();
break;
}
});
** jQuery("select[id='DROPDOWNID']").trigger("change"); **
function hideVarforProspekt() {
jQuery("input[id='IDFROMSHAREPOINT']").closest('tr').hide();
}
function hideSektor() {
jQuery("table[id='IDFROMSHAREPOINT']").closest('tr').hide();
}
function hideUppskOrder() {
jQuery("input[id='IDFROMSHAREPOINT']").closest('tr').hide();
}
});
</code></pre> | 18,693,620 | 8 | 13 | null | 2013-09-09 07:33:59.17 UTC | 2 | 2022-06-01 15:51:20.327 UTC | 2015-06-22 10:39:05.97 UTC | null | 311,992 | null | 2,326,403 | null | 1 | 20 | javascript|jquery | 47,936 | <p>Sometimes the usage of trigger is not necessary:</p>
<pre><code>// use just jQuery("#DROPDOWNID") instead
var select = jQuery("select[id='DROPDOWNID']");
// placing the handler in separate function
var changeHandler = function () {
var selectedIndex = select.prop('selectedIndex');
switch(selectedIndex) {
case 0:
hideVarforProspekt();
break;
case 1:
hideOrdervarde();
break;
case 2:
break;
case 3:
hideSektor();
break;
}
}
// cache your jQuery selectors. It's a good practice
// and improves the readability
select.change(changeHandler);
// triggering
changeHandler();
</code></pre> |
27,566,999 | git with IntelliJ IDEA: Could not read from remote repository | <p>Since a few weeks, I'm not able to pull or push from or to the remote repository. I thought it happend when upgrading to IntelliJ IDEA 14, but I can reproduce the problem with IDEA 13.1.5 as well.</p>
<p>The tooltip says
"Fetch failed
fatal: Could not read from remote repository."</p>
<p>and the exception in the Version Control tab reads</p>
<pre><code>14:02:37.737: cd C:\dev\project
14:02:37.737: git -c core.quotepath=false fetch origin --progress --prune
java.io.IOException: Padding in RSA public key!
at com.trilead.ssh2.signature.RSASHA1Verify.decodeSSHRSAPublicKey(RSASHA1Verify.java:37)
at com.trilead.ssh2.KnownHosts.addHostkey(KnownHosts.java:98)
at com.trilead.ssh2.KnownHosts.initialize(KnownHosts.java:414)
at com.trilead.ssh2.KnownHosts.initialize(KnownHosts.java:440)
at com.trilead.ssh2.KnownHosts.addHostkeys(KnownHosts.java:137)
at org.jetbrains.git4idea.ssh.SSHMain.configureKnownHosts(SSHMain.java:462)
at org.jetbrains.git4idea.ssh.SSHMain.start(SSHMain.java:155)
at org.jetbrains.git4idea.ssh.SSHMain.main(SSHMain.java:137)
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
</code></pre>
<p>Using the built-in terminal of IntelliJ, executing <code>git -c core.quotepath=false fetch origin --progress --prune</code>, it works just as it should.</p>
<p>According to the stacktrace, there seems to be a problem with my <code>KnownHosts</code>, so I deleted our git server from <code>~/.ssh/known_hosts</code>, hoping IntelliJ would insert it again. But the problem still appears when updating via the UI, and there is no new entry written in <code>known_hosts</code>; thinking about some caching of the file, I restarted IntelliJ, without success.</p>
<p>When doing another <code>git fetch</code> from the terminal, now I'm getting asked if I want to permanently add the server. After that, it has been written to <code>known_hosts</code> again, but IntelliJ still won't let me update my project.</p>
<p>I haven't found anything about this behavior online, so I guess it's not a known bug with the new IntelliJ version. Nevertheless, I updated to 14.0.2, but the problem still exists.</p>
<p>IntelliJ is configured to use the built-in SSH executable.</p>
<p>Does anybody have a clue what could be the problem here?</p> | 28,294,279 | 33 | 8 | null | 2014-12-19 13:18:49.983 UTC | 47 | 2022-07-15 14:10:30.293 UTC | 2014-12-19 13:59:09.053 UTC | null | 1,436,981 | null | 1,436,981 | null | 1 | 277 | git|intellij-idea | 206,200 | <p>IntelliJ's built-in SSH client seems to <a href="https://unix.stackexchange.com/questions/31549/is-it-possible-to-find-out-the-hosts-in-the-known-hosts-file">hash its <code>known_hosts</code></a>, but the one I had had its host names in clear text.</p>
<p>When I deleted the file and let IntelliJ create a new one, with only my (hashed) GitLab server and nothing else, it worked.</p>
<p>It's also not possible to mix it - keep some unhashed entries together with hashed entries for IntelliJ. So, you have to configure your other SSH clients <a href="https://security.stackexchange.com/a/56283/44774">to use hashed hosts</a>.</p> |
15,242,507 | Perspective correct texturing of trapezoid in OpenGL ES 2.0 | <p>I have drawn a textured trapezoid, however the result does not appear as I had intended.</p>
<p>Instead of appearing as a single unbroken quadrilateral, a discontinuity occurs at the diagonal line where its two comprising triangles meet. </p>
<p>This illustration demonstrates the issue:<br>
<img src="https://i.stack.imgur.com/lru80.png" alt="Illustration demonstrating the source texture (a checkered pattern), the expected result, and the actual (incorrect) result"><br>
(Note: the last image is not intended to be a 100% faithful representation, but it should get the point across.)</p>
<p>The trapezoid is being drawn using <code>GL_TRIANGLE_STRIP</code> in OpenGL ES 2.0 (on an iPhone). It's being drawn completely facing the screen, and is not being tilted (i.e. that's not a 3D sketch you're seeing!)</p>
<p>I have come to understand that I need to perform "perspective correction," presumably in my vertex and/or fragment shaders, but I am unclear how to do this.</p>
<p>My code includes some simple Model/View/Projection matrix math, but none of it currently influences my texture coordinate values. <strong>Update:</strong> The previous statement is incorrect, according to comment by user infact.</p>
<p>Furthermore, I have found this tidbit in the ES 2.0 spec, but do not understand what it means:</p>
<blockquote>
<p>The PERSPECTIVE CORRECTION HINT is not supported because <strong>OpenGL
ES 2.0 requires that all attributes be perspectively interpolated.</strong></p>
</blockquote>
<p>How can I make the texture draw correctly?</p>
<hr>
<p><strong>Edit:</strong> Added code below:</p>
<pre><code>// Vertex shader
attribute vec4 position;
attribute vec2 textureCoordinate;
varying vec2 texCoord;
uniform mat4 modelViewProjectionMatrix;
void main()
{
gl_Position = modelViewProjectionMatrix * position;
texCoord = textureCoordinate;
}
</code></pre>
<hr>
<pre><code>// Fragment shader
uniform sampler2D texture;
varying mediump vec2 texCoord;
void main()
{
gl_FragColor = texture2D(texture, texCoord);
}
</code></pre>
<hr>
<pre><code>// Update and Drawing code (uses GLKit helpers from iOS)
- (void)update
{
float fov = GLKMathDegreesToRadians(65.0f);
float aspect = fabsf(self.view.bounds.size.width / self.view.bounds.size.height);
projectionMatrix = GLKMatrix4MakePerspective(fov, aspect, 0.1f, 50.0f);
viewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -4.0f); // zoom out
}
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaders[SHADER_DEFAULT]);
GLKMatrix4 modelMatrix = GLKMatrix4MakeScale(0.795, 0.795, 0.795); // arbitrary scale
GLKMatrix4 modelViewMatrix = GLKMatrix4Multiply(viewMatrix, modelMatrix);
GLKMatrix4 modelViewProjectionMatrix = GLKMatrix4Multiply(projectionMatrix, modelViewMatrix);
glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, GL_FALSE, modelViewProjectionMatrix.m);
glBindTexture(GL_TEXTURE_2D, textures[TEXTURE_WALLS]);
glUniform1i(uniforms[UNIFORM_TEXTURE], 0);
glVertexAttribPointer(ATTRIB_VERTEX, 3, GL_FLOAT, GL_FALSE, 0, wall.vertexArray);
glVertexAttribPointer(ATTRIB_TEXTURE_COORDINATE, 2, GL_FLOAT, GL_FALSE, 0, wall.texCoords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, wall.vertexCount);
}
</code></pre> | 15,245,064 | 3 | 5 | null | 2013-03-06 08:39:07.813 UTC | 11 | 2016-01-12 17:55:32.42 UTC | 2013-03-06 13:55:50.533 UTC | null | 1,655,552 | null | 1,655,552 | null | 1 | 27 | opengl-es|opengl-es-2.0 | 15,505 | <p>(I'm taking a bit of a punt here, because your picture does not show exactly what I would expect from texturing a trapezoid, so perhaps something else is happening in your case - but the general problem is well known)</p>
<p>Textures will not (by default) interpolate correctly across a trapezoid. When the shape is triangulated for drawing, one of the diagonals will be chosen as an edge, and while that edge is straight through the middle of the texture, it is not through the middle of the trapezoid (picture the shape divided along a diagonal - the two triangles are very much not equal).</p>
<p>You need to provide more than a 2D texture coordinate to make this work - you need to provide a 3D (or rather, projective) texture coordinate, and perform the perspective divide in the fragment shader, post-interpolation (or else use a texture lookup function which will do the same).</p>
<p>The following shows how to provide texture coordinates for a trapezoid using old-school GL functions (which are a little easier to read for demonstration purposes). The commented-out lines are the 2d texture coordinates, which I have replaced with projective coordinates to get the correct interpolation.</p>
<pre class="lang-c prettyprint-override"><code>glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,640,0,480,1,1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
const float trap_wide = 600;
const float trap_narrow = 300;
const float mid = 320;
glBegin(GL_TRIANGLE_STRIP);
glColor3f(1,1,1);
// glTexCoord4f(0,0,0,1);
glTexCoord4f(0,0,0,trap_wide);
glVertex3f(mid - trap_wide/2,10,-10);
// glTexCoord4f(1,0,0,1);
glTexCoord4f(trap_narrow,0,0,trap_narrow);
glVertex3f(mid - trap_narrow/2,470,-10);
// glTexCoord4f(0,1,0,1);
glTexCoord4f(0,trap_wide,0,trap_wide);
glVertex3f(mid + trap_wide/2,10,-10);
// glTexCoord4f(1,1,0,1);
glTexCoord4f(trap_narrow,trap_narrow,0,trap_narrow);
glVertex3f(mid + trap_narrow/2,470,-10);
glEnd();
</code></pre>
<p>The third coordinate is unused here as we're just using a 2D texture. The fourth coordinate will divide the other two after interpolation, providing the projection. Obviously if you divide it through at the vertices, you'll see you get the original texture coordinates.</p>
<p>Here's what the two renderings look like:</p>
<p><img src="https://i.stack.imgur.com/2qVr1.png" alt="enter image description here"></p>
<p>If your trapezoid is actually the result of transforming a quad, it might be easier/better to just draw that quad using GL, rather than transforming it in software and feeding 2D shapes to GL...</p> |
15,309,692 | Difference between final variables and compile time constant | <p>What is the difference between final variables and compile time constants?</p>
<p>Consider the following code</p>
<pre><code>final int a = 5;
final int b;
b=6;
int x=0;
switch(x)
{
case a: //no error
case b: //compiler error
}
</code></pre>
<p>What does this mean? When and how are final variables assigned a value? What happens at run time and what happens at compile time? Why should we give switch a compile time constant? What other structures of java demands a compile time constant?</p> | 15,309,875 | 5 | 1 | null | 2013-03-09 10:31:10.687 UTC | 12 | 2013-03-09 11:40:06.163 UTC | 2013-03-09 10:39:26.527 UTC | null | 1,516,759 | null | 2,081,665 | null | 1 | 28 | java|compile-time-constant | 8,596 | <p>The problem is, that <strong>all <code>case:</code> statements must be ultimate</strong> at compile time.
Your first statement <em>is ultimate</em>. <code>a</code> will for 100% be no other value than <code>5</code>.</p>
<pre><code>final int a = 5;
</code></pre>
<p>However, this is <em>not guaranteed</em> for <code>b</code>. What if there would be an if-statement around <code>b</code>?</p>
<pre><code>final int b;
if(something())
b=6;
else
b=5;
</code></pre> |
15,061,653 | Run a piece of code only once when an application is installed | <p>I want to run a piece of code only once in my application and is when i run it for the first time (newly installed app). How could i do this, can anyone explain giving a piece of code.</p>
<p>Actually, in my android project i want to create database and insert some values on the first run only. After that, that particular piece of code should not run again. How can i achieve this mechanism through <strong>SharedPreferences</strong> or <strong>Preferences</strong>.</p>
<p>Sample code will be more helpful.</p> | 15,062,051 | 4 | 0 | null | 2013-02-25 07:00:23.933 UTC | 12 | 2020-08-16 08:31:16.26 UTC | null | null | null | null | 1,739,882 | null | 1 | 29 | android|sharedpreferences|android-preferences | 40,682 | <p>Before all you can use <a href="http://developer.android.com/intl/ru/reference/android/database/sqlite/SQLiteOpenHelper.html" rel="noreferrer">SQLiteOpenHelper</a>. It is preferred way to do things with database. This class have a <code>onCreate(SQLiteDatabase)</code> method, that called when first creating database. I think it suits you well.</p>
<p>If you want more flexibility and your first time logic is not tied only with database, you can use sample provided earlier. You just need to put it in startup spot.</p>
<p>There are 2 startup spots. If you have only single activity, you can put your code in <code>onCreate</code> method, so it will be like this:</p>
<pre><code>public void onCreate(Bundle savedInstanceState) {
// don't forget to call super method.
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();
// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
</code></pre>
<p>Don't forget to put <a href="http://developer.android.com/intl/ru/guide/topics/manifest/activity-element.html" rel="noreferrer">activity declaration in manifest</a>, as well as it's <a href="http://developer.android.com/intl/ru/guide/topics/manifest/intent-filter-element.html" rel="noreferrer">intentfilters</a> (action = <code>MAIN</code>, category = <code>LAUNCHER</code>).</p>
<p>If you have more than one activity and you don't want to duplicate your startup logic you can just put your initialization logic in Application instance, that is created before all activities (and other components, such as services, broadcast recievers, content providers). </p>
<p>Just create class like that:</p>
<pre><code>public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
// <---- run your one time code here
databaseSetup();
// mark first time has ran.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
}
</code></pre>
<p>All you need for this to work, is put in <code>application</code> tag in AndroidManifest.xml attribute android:name=".App".</p>
<pre><code><!-- other xml stuff -->
<application ... android:name=".App">
<!-- yet another stuff like nextline -->
<activity ... />
</application>
</code></pre> |
15,301,451 | How to upgrade Typescript to the latest version? | <p>I have a MacBook Pro with OS X 10.8.2
Some time ago I installed Typescript and today I'd like to upgrade that installation to the latest version available (so far, v0.8.3).
I wrote this command from the terminal:</p>
<pre><code>sudo npm install -g typescript
</code></pre>
<p>But this is what I got on the display:</p>
<pre><code>npm http GET https://registry.npmjs.org/typescript
npm http 304 https://registry.npmjs.org/typescript
/usr/local/bin/tsc -> /usr/local/lib/node_modules/typescript/bin/tsc
[email protected] /usr/local/lib/node_modules/typescript
</code></pre>
<p>Does this means that I still have version 0.8.0 installed on my computer?
I tried to see if the tsc command has a <code>-v</code> or a <code>-version</code> parameter but I haven't found it, so I still uncertain if I have upgraded Typescript to the latest release or if I'm still stuck with an older version.</p> | 15,301,680 | 10 | 1 | null | 2013-03-08 19:06:38.34 UTC | 7 | 2021-08-02 21:41:31.983 UTC | 2017-02-06 10:01:47.117 UTC | null | 4,074,148 | null | 932,845 | null | 1 | 52 | typescript|npm | 93,888 | <p>I just realised that I was using an old version of npm. I have upgraded npm to the latest version, then re-installed typescript and now I have the latest version of typescript installed on my computer.</p> |
14,966,821 | Testing for errors thrown in Mocha | <p>I'm hoping to find some help with this problem. I'm trying to write tests for an application I am writing. I have distilled the problem in to the following sample code. I want to test that an error was thrown. I'm using Testacular as a test runner with mocha as the framework and chai as the assertion library. The tests run, but the test fails because an error was thrown! Any help is greatly appreciated!</p>
<pre><code>function iThrowError() {
throw new Error("Error thrown");
}
var assert = chai.assert,
expect = chai.expect;
describe('The app', function() {
describe('this feature', function() {
it("is a function", function(){
assert.throw(iThrowError(), Error, "Error thrown");
});
});
});
</code></pre> | 17,793,483 | 3 | 1 | null | 2013-02-19 20:31:50.743 UTC | 4 | 2021-11-12 14:47:17.103 UTC | 2016-11-07 20:20:51.07 UTC | null | 1,906,307 | null | 1,325,446 | null | 1 | 104 | javascript|testing|mocha.js|chai | 120,360 | <p>You're not passing your function to <code>assert.throws()</code> the right way.</p>
<p>The <code>assert.throws()</code> function expects a function as its first parameter. In your code, you are invoking iThrowError and passing its return value when calling <code>assert.throws()</code>.</p>
<p>Basically, changing this:</p>
<pre><code>assert.throws(iThrowError(), Error, "Error thrown");
</code></pre>
<p>to this:</p>
<pre><code>assert.throws(iThrowError, Error, "Error thrown");
</code></pre>
<p>should solve your problem.</p>
<p>With args:</p>
<pre><code>assert.throws(() => { iThrowError(args) }, Error);
</code></pre>
<p>or</p>
<pre><code>assert.throws(function() { iThrowError(args) }, Error, /Error thrown/);
</code></pre> |
5,356,011 | add onclick function for submit button | <p>Is there a way to add an <code>onclick</code> function to an <code><input type="submit"></code>? I would like to show a hidden <code><div></code> named "div2" when the submit button is clicked inside a form.</p> | 5,356,177 | 5 | 3 | null | 2011-03-18 18:00:21.813 UTC | 1 | 2016-05-26 10:04:15.807 UTC | 2015-02-18 17:33:34.3 UTC | null | 416,791 | null | 634,692 | null | 1 | 6 | javascript | 73,391 | <p>Remember that you need to stop the default behavior of clicking the submit button or else the form will be submitted and a new page will load before the <code>div</code> ever get's displayed. For example:</p>
<pre><code> <script type="text/javascript">
function showDiv() {
document.getElementById('div2').style.display = 'block';
return false;
}
</script>
<div id="div2" style="display: none;">Visible</div>
<form name="test_form" action="#">
<input type="submit" onclick="return showDiv();" value="Submit" />
</form>
</code></pre>
<p>Using this code the form will now not submit and the <code>div</code> will be shown. If you then want to submit the form later you need to either change <code>showDiv()</code> to return <code>true</code>, use another submit button or call the <code>submit()</code> method of the form.</p> |
4,966,203 | Mongo Query question $gt,$lt | <p>I have a query below. I want get items between 4 and 6 so only a:1 should match because it has the value 5 in b. </p>
<pre><code>> db.test.find({ b : { $gt : 4 }, b: {$lt : 6}});
{ "_id" : ObjectId("4d54cff54364000000004331"), "a" : 1, "b" : [ 2, 3, 4, 5 ] }
{ "_id" : ObjectId("4d54d0074364000000004332"), "a" : 2, "b" : [ 2, 4, 6, 8 ] }
>
</code></pre>
<p>Can someone tell be why a:2 is matching this query? I can't really see why it is being returned.</p>
<p>I also tried what was specified in the tutorial but id did not seem to work:</p>
<pre><code>> db.test.find({ b : { $gt : 4, $lt : 6}});
{ "_id" : ObjectId("4d54cff54364000000004331"), "a" : 1, "b" : [ 2, 3, 4, 5 ] }
{ "_id" : ObjectId("4d54d0074364000000004332"), "a" : 2, "b" : [ 2, 4, 6, 8 ] }
>
</code></pre>
<p>And this one to avoid any confusion regarding GT/GTE </p>
<pre><code>> db.test.find({b: {$gt: 4.5, $lt: 5.5}});
{ "_id" : ObjectId("4d54cff54364000000004331"), "a" : 1, "b" : [ 2, 3, 4, 5 ] }
{ "_id" : ObjectId("4d54d0074364000000004332"), "a" : 2, "b" : [ 2, 4, 6, 8 ] }
>
</code></pre>
<p>only a:1 should be returned.</p>
<p>As suggested, I gave $elemMatch a try but it did not appear to work either (objectIds are different because I am on a different machine)</p>
<pre><code>> db.test.find();
{ "_id" : ObjectId("4d5a24a5e82e00000000433f"), "a" : 1, "b" : [ 2, 3, 4, 5 ] }
{ "_id" : ObjectId("4d5a24bbe82e000000004340"), "a" : 2, "b" : [ 2, 4, 6, 8 ] }
> db.test.find({b: {$elemMatch: {$gt : 4, $lt: 6 }}});
>
</code></pre>
<p>No documents were returned.</p> | 4,970,985 | 5 | 3 | null | 2011-02-11 06:24:45.497 UTC | 7 | 2022-03-12 18:23:58.633 UTC | 2011-02-15 07:08:05.15 UTC | null | 284,272 | null | 284,272 | null | 1 | 36 | mongodb | 92,023 | <p>This is a really confusing topic. I work at 10gen and I had to spend a while wrapping my head around it ;) </p>
<p>Let's walk through how the query engine processes this query. </p>
<p>Here's the query again: </p>
<pre><code>> db.test.find({ b : { $gt : 4, $lt : 6}});
</code></pre>
<p>When it gets to the record that seems like it shouldn't match... </p>
<pre><code>{ "_id" : ObjectId("4d54cff54364000000004331"), "a" : 1, "b" : [ 2, 4, 6, 8 ] }
</code></pre>
<p>The match is not performed against each element of the array, but rather against the array as a whole. </p>
<p>The comparison is performed in three steps: </p>
<p><strong>Step 1</strong>: Find all documents where b has a value greater than 4 </p>
<p>b: [2,4,6,8] matches because 6 & 8 are greater than 4</p>
<p><strong>Step 2</strong>: Find all documents where b has a value less than 6 </p>
<p>b: [2,4,6,8] matches because 2 & 4 are less than 6 </p>
<p><strong>Step 3</strong>: Find the set of documents that matched in both step 1 & 2. </p>
<p>The document with b: [2,4,6,8] matched both steps 1 & 2 so it is returned as a match. Note that results are also de-duplicated in this step, so the same document won't be returned twice. </p>
<p>If you want your query to apply to the individual elements of the array, rather than the array as a whole, you can use the $elemMatch operator. For example </p>
<pre><code>> db.temp.find({b: {$elemMatch: {$gt: 4, $lt: 5}}})
> db.temp.find({b: {$elemMatch: {$gte: 4, $lt: 5}}})
{ "_id" : ObjectId("4d558b6f4f0b1e2141b66660"), "b" : [ 2, 3, 4, 5, 6 ] }
</code></pre> |
5,364,233 | PHP Fatal Error Failed opening required File | <p>I am getting the following error from Apache</p>
<p><strong>[Sat Mar 19 23:10:50 2011] [warn] mod_fcgid: stderr: PHP Fatal error: require_once() [function.require]: Failed opening required '/common/configs/config_templates.inc.php' (include_path='.:/usr/share/pear:/usr/share/php') in /home/viapics1/public_html/common/configs/config.inc.php on line 158</strong></p>
<p>I am definately not an expert of Apache but the file config.inc.php & config_templates.inc.php are there. I also tried navigating to a test.html page I placed in common/configs/ so I assume there is no rights issues going on. I also set the rights on config_templates.inc.php to give everyone read, write, and execute rights. Not sure what to do at this point, I checked to see if there was a /usr/share/php directory and I found there was not but when I did yum install php it said it had the latest. Ideas? </p> | 5,364,274 | 6 | 0 | null | 2011-03-19 19:06:14.1 UTC | 15 | 2020-10-09 09:39:22.333 UTC | 2014-02-16 06:06:52.74 UTC | null | 285,587 | null | 61,962 | null | 1 | 63 | php|path | 462,010 | <p>It's not actually an Apache related question. Nor even a PHP related one.
To understand this error you have to distinguish a path on the <em>virtual server</em> from a path in the <em>filesystem</em>.</p>
<p><code>require</code> operator works with files. But a path like this</p>
<pre><code> /common/configs/config_templates.inc.php
</code></pre>
<p>only exists on the virtual HTTP server, while there is no such path in the filesystem. The correct filesystem path would be</p>
<pre><code>/home/viapics1/public_html/common/configs/config_templates.inc.php
</code></pre>
<p>where</p>
<pre><code>/home/viapics1/public_html
</code></pre>
<p>part is called the <em>Document root</em> and it connects the virtual world with the real one. Luckily, web-servers usually have the document root in a configuration variable that they share with PHP. So if you change your code to something like this</p>
<pre><code>require_once $_SERVER['DOCUMENT_ROOT'].'/common/configs/config_templates.inc.php';
</code></pre>
<p><em>it will work from any file placed in any directory!</em></p>
<p>Update: eventually I wrote an article that explains the <a href="https://phpdelusions.net/articles/paths" rel="noreferrer">difference between relative and absolute paths</a>, in the file system and on the web server, which explains the matter in detail, and contains some practical solutions. Like, such a handy variable doesn't exist when you run your script from a command line. In this case a technique called "a single entry point" is to the rescue. You may refer to the article above for the details as well.</p> |
5,006,395 | Does Ruby have containers like stacks, queues, linked-lists, maps, or sets? | <p>I checked several Ruby tutorials online and they seemed to use array for everything. So how could I implement the following data structures in Ruby?</p>
<ul>
<li>Stacks</li>
<li>Queues</li>
<li>Linked lists</li>
<li>Maps</li>
<li>Sets</li>
</ul> | 5,006,860 | 8 | 7 | null | 2011-02-15 16:28:10.573 UTC | 17 | 2022-08-31 01:01:43.647 UTC | 2013-05-23 07:37:02.773 UTC | null | 398,398 | null | 398,398 | null | 1 | 70 | ruby | 43,843 | <p>(Moved from Comment)</p>
<p>Well, an array can be a stack or queue by limiting yourself to stack or queue methods (push, pop, shift, unshift). Using push / pop gives LIFO(last in first out) behavior (stack), while using push / shift or unshift / pop gives FIFO behavior (queue). </p>
<p>Maps are <a href="http://www.ruby-doc.org/core/classes/Hash.html" rel="noreferrer">hashes</a>, and a <a href="http://ruby-doc.org/stdlib/libdoc/set/rdoc/index.html" rel="noreferrer">Set</a> class already exists. </p>
<p>You could implement a linked list using classes, but arrays will give linked-list like behavior using the standard array methods.</p> |
5,444,394 | How to implement a binary search tree in Python? | <p>This is what I've got so far but it is not working:</p>
<pre><code>class Node:
rChild,lChild,data = None,None,None
def __init__(self,key):
self.rChild = None
self.lChild = None
self.data = key
class Tree:
root,size = None,0
def __init__(self):
self.root = None
self.size = 0
def insert(self,node,someNumber):
if node is None:
node = Node(someNumber)
else:
if node.data > someNumber:
self.insert(node.rchild,someNumber)
else:
self.insert(node.rchild, someNumber)
return
def main():
t = Tree()
t.root = Node(4)
t.root.rchild = Node(5)
print t.root.data #this works
print t.root.rchild.data #this works too
t = Tree()
t.insert(t.root,4)
t.insert(t.root,5)
print t.root.data #this fails
print t.root.rchild.data #this fails too
if __name__ == '__main__':
main()
</code></pre> | 5,444,796 | 18 | 7 | null | 2011-03-26 18:37:01.053 UTC | 24 | 2020-06-08 18:11:09.623 UTC | 2017-05-18 19:14:09.517 UTC | null | 895,245 | null | 423,000 | null | 1 | 50 | python|oop|class|data-structures|binary-search-tree | 126,974 | <p>Here is a quick example of a binary insert:</p>
<pre><code>class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def binary_insert(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.l_child is None:
root.l_child = node
else:
binary_insert(root.l_child, node)
else:
if root.r_child is None:
root.r_child = node
else:
binary_insert(root.r_child, node)
def in_order_print(root):
if not root:
return
in_order_print(root.l_child)
print root.data
in_order_print(root.r_child)
def pre_order_print(root):
if not root:
return
print root.data
pre_order_print(root.l_child)
pre_order_print(root.r_child)
</code></pre>
<hr>
<pre><code>r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))
</code></pre>
<hr>
<pre><code> 3
/ \
1 7
/
5
</code></pre>
<hr>
<pre><code>print "in order:"
in_order_print(r)
print "pre order"
pre_order_print(r)
in order:
1
3
5
7
pre order
3
1
7
5
</code></pre> |
5,007,530 | How do I scroll to an element using JavaScript? | <p>I am trying to move the page to a <code><div></code> element.</p>
<p>I have tried the next code to no avail:</p>
<pre><code>document.getElementById("divFirst").style.visibility = 'visible';
document.getElementById("divFirst").style.display = 'block';
</code></pre> | 5,007,606 | 19 | 5 | null | 2011-02-15 18:02:07.78 UTC | 58 | 2022-09-07 15:47:50.237 UTC | 2011-02-15 18:12:19.43 UTC | null | 427,545 | null | 272,756 | null | 1 | 295 | javascript|html | 548,444 | <p>You can use an anchor to "focus" the div. I.e:</p>
<pre><code><div id="myDiv"></div>
</code></pre>
<p>and then use the following javascript:</p>
<pre class="lang-js prettyprint-override"><code>// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
</code></pre> |
16,653,458 | Concatenating a char into a string | <p>I am trying to read a string from the console. But I want to read it char by char. And I'm having trouble with concatenating the char into the string AND with breaking the loop.
Here is the code:</p>
<pre><code>char* createString(){
char c;
char *string;
int x=0;
string = (char*) calloc(1, sizeof(char));
do{
c = getche();
if(c != '\n'){
x++;
realloc(string, sizeof(char)*x);
strcat(string, &c);
};
}while(c != '\n');
return string;
};
</code></pre>
<p>When I run this code, each concatenation adds 3 chars, instead of just 1. It's like is accessing non-allocated memory... (For example, if I press <code>a</code>, the final string is <code>a%T</code>. Then, if I press another key, <code>s</code> for example, string becomes <code>a%Ts%T</code>)</p>
<p>And when I press <code>Enter</code>, it goes into the if and doesn't get out of the loop.</p>
<p>I have no clue of why and what is going on...</p>
<hr>
<h2>EDIT</h2>
<hr>
<p>Based on other tries and responses until now, I changed my code and now it's like this:</p>
<pre><code>char* digitarString(){
char c[2];
char *string;
string = (char*) calloc(1, sizeof(char));
do{
c[0] = getche();
c[1] = '\0';
if(c[0] != '\n'){
strcat(string, c);
};
}while(c[0] != '\n');
return string;
};
</code></pre>
<p>BUT, there are still two issues...</p>
<ul>
<li>The code works, but I think that it's writing in non-allocated memory.</li>
<li>When I press <code>Enter</code> it still doesn't work. It keep entering the loop and if.</li>
</ul>
<p>Forget about the <code>Enter</code>... I changed it...</p>
<pre><code>c[0] = getche();
</code></pre>
<p>to</p>
<pre><code>scanf("%c", &c[0]);
</code></pre>
<p>and worked awesomely well.</p> | 16,654,161 | 3 | 3 | null | 2013-05-20 15:57:15.803 UTC | 1 | 2017-08-13 19:14:53.017 UTC | 2013-05-20 20:32:03.977 UTC | null | 2,402,201 | null | 2,402,201 | null | 1 | 5 | c|string|loops|char|concatenation | 40,894 | <p>Ok here is the solution </p>
<pre><code> strcat(string, &c);
</code></pre>
<p>change this to</p>
<pre><code>strncat(string, &c,1);
</code></pre>
<p><strong>now the answer to the question why ?</strong></p>
<p>well first of call the below statement </p>
<pre><code>c = getche();
</code></pre>
<p>will scan a value for us and will place in variable called c</p>
<p>now lets consider the variable is placed in an arbitrary memory location x</p>
<pre><code> c
+-----------+------------+------------+-----------+------------+------------+
| a | | | | | |
+---------- +---------- +---------- +---------- +--------- - +---------- +
x = &c x+1 x+2 ......
</code></pre>
<p>now to the next important statement </p>
<pre><code>strcat(string, &c);
</code></pre>
<p>the second argument above is supposed to be a string means a NULL termination at the end but we can not guarantee that x+1 location is NULL and if x+1 is not NULL then the string will be more than a single character long and it will end up appending all those characters to your original string hence garbage.</p>
<p>I hope it's clear now...</p>
<p>P.S - if you have access to gdb you can check practically..</p> |
16,993,733 | Sonata Admin Bundle One-to-Many relationship not saving foreign ID | <p>I have a problem with the SonataAdminBunle in combination with symfony 2.2.
I have a Project entity and a ProjectImage entity and specified a One-to-Many relationship between these two like so:</p>
<pre><code>class Project
{
/**
* @ORM\OneToMany(targetEntity="ProjectImage", mappedBy="project", cascade={"all"}, orphanRemoval=true)
*/
private $images;
}
class ProjectImage
{
/**
* @ORM\ManyToOne(targetEntity="Project", inversedBy="images")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $project;
}
</code></pre>
<p>I've configured the ProjectAdmin and ProjectImageAdmin:</p>
<pre><code>class ProjectAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title')
->add('website')
->add('description', 'textarea')
->add('year')
->add('tags')
->add('images', 'sonata_type_collection', array(
'by_reference' => false
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'id',
))
;
}
}
class ProjectImageAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('file', 'file', array(
'required' => false
))
;
}
}
</code></pre>
<p>The problem is that in the project_image table in the database the project_id is not saved, while all other data is and also the image is saved. Couldn't find a working answer anywhere else.</p> | 16,993,909 | 6 | 6 | null | 2013-06-07 22:11:55.973 UTC | 9 | 2018-10-29 09:44:42.043 UTC | 2013-06-07 22:17:08.567 UTC | null | 2,465,090 | null | 2,465,090 | null | 1 | 12 | symfony|sonata-admin | 26,439 | <p>Although unrelated, I'd slighty tweak your One-to-Many annotation:</p>
<pre><code>class Project
{
/**
* @ORM\OneToMany(targetEntity="ProjectImage", mappedBy="project", cascade={"persist"}, orphanRemoval=true)
* @ORM\OrderBy({"id" = "ASC"})
*/
private $images;
}
</code></pre>
<p>Back on track, your annotations and Sonata Admin forms look fine, so I'm pretty sure you're missing one of those methods in your Project entity class:</p>
<pre><code>public function __construct() {
$this->images = new \Doctrine\Common\Collections\ArrayCollection();
}
public function setImages($images)
{
if (count($images) > 0) {
foreach ($images as $i) {
$this->addImage($i);
}
}
return $this;
}
public function addImage(\Acme\YourBundle\Entity\ProjectImage $image)
{
$image->setProject($this);
$this->images->add($image);
}
public function removeImage(\Acme\YourBundle\Entity\ProjectImage $image)
{
$this->images->removeElement($image);
}
public function getImages()
{
return $this->Images;
}
</code></pre>
<p>And in your Admin class:</p>
<pre><code>public function prePersist($project)
{
$this->preUpdate($project);
}
public function preUpdate($project)
{
$project->setImages($project->getImages());
}
</code></pre> |
29,802,034 | Set column name for apply result over groupby | <p>This is a fairly trivial problem, but its triggering my OCD and I haven't been able to find a suitable solution for the past half hour. </p>
<p>For background, I'm looking to calculate a value (let's call it F) for each group in a DataFrame derived from <em>different</em> aggregated measures of columns in the existing DataFrame.</p>
<p>Here's a toy example of what I'm trying to do:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({'A': ['X', 'Y', 'X', 'Y', 'Y', 'Y', 'Y', 'X', 'Y', 'X'],
'B': ['N', 'N', 'N', 'M', 'N', 'M', 'M', 'N', 'M', 'N'],
'C': [69, 83, 28, 25, 11, 31, 14, 37, 14, 0],
'D': [ 0.3, 0.1, 0.1, 0.8, 0.8, 0. , 0.8, 0.8, 0.1, 0.8],
'E': [11, 11, 12, 11, 11, 12, 12, 11, 12, 12]
})
df_grp = df.groupby(['A','B'])
df_grp.apply(lambda x: x['C'].sum() * x['D'].mean() / x['E'].max())
</code></pre>
<p>What I'd like to do is assign a name to the result of <code>apply</code> (or <code>lambda</code>). Is there anyway to do this without moving <code>lambda</code> to a named function or renaming the column after running the last line?</p> | 29,803,131 | 2 | 7 | null | 2015-04-22 15:21:32.54 UTC | 9 | 2020-02-25 17:30:02.657 UTC | 2019-03-09 04:29:01.367 UTC | null | 3,367,799 | null | 1,026,403 | null | 1 | 40 | python|pandas | 30,996 | <p>You could convert your <code>series</code> to a <code>dataframe</code> using <code>reset_index()</code> and provide <code>name='yout_col_name'</code> -- The name of the column corresponding to the Series values</p>
<pre><code>(df_grp.apply(lambda x: x['C'].sum() * x['D'].mean() / x['E'].max())
.reset_index(name='your_col_name'))
A B your_col_name
0 X N 5.583333
1 Y M 2.975000
2 Y N 3.845455
</code></pre> |
12,480,838 | use jQuery to expand/collapse ul list - having problems | <p>I'm trying to create a blog archive list which shows all articles by year and month (which I've done with PHP/MySQL)</p>
<p>Now I'm trying to make it so that on page load, all years are collapsed except the latest year/month and also that each will collapse/expand on click.</p>
<p>At the moment my jQuery click function will open or close all of the li elements rather than just the one I click. I'm still pretty new to jQuery so am not sure how to make it just affect the list section that I click on.</p>
<p>Any help would be grand!</p>
<p>Here's my code so far (the list is generated from PHP/MySQL loops)</p>
<pre><code><ul class="archive_year">
<li id="years">2012</li>
<ul class="archive_month">
<li id="months">September</li>
<ul class="archive_posts">
<li id="posts">Product Review</li>
<li id="posts">UK men forgotten how to act like Gentlemen</li>
<li id="posts">What Do Mormons Believe? Ex-Mormon Speaks Out</li>
<li id="posts">Here is a new post with lots of text and a long title</li>
</ul>
<li id="months">August</li>
<ul class="archive_posts">
<li id="posts">A blog post with an image!</li>
</ul>
</ul>
<li id="years">2011</li>
<ul class="archive_month">
<li id="months">July</li>
<ul class="archive_posts">
<li id="posts">New Blog!</li>
</ul>
</ul>
<li id="years">2009</li>
<ul class="archive_month">
<li id="months">January</li>
<ul class="archive_posts">
<li id="posts">Photography 101</li>
</ul>
</ul>
</ul>
</code></pre>
<p>And here is the jQuery so far:</p>
<pre><code>$(document).ready(function() {
//$(".archive_month ul:gt(0)").hide();
$('.archive_month ul').hide();
$('.archive_year > li').click(function() {
$(this).parent().find('ul').slideToggle();
});
$('.archive_month > li').click(function() {
$(this).parent().find('ul').slideToggle();
});
});
</code></pre>
<p>I was experimenting with the $(".archive_month ul:gt(0)").hide(); but it didn't work as expected, it would switch the open and closed around.</p>
<p>Any help/thoughts?</p>
<p>Also, here is a fiddle for live example: <a href="http://jsfiddle.net/MrLuke/VNkM2/1/">http://jsfiddle.net/MrLuke/VNkM2/1/</a></p> | 12,480,993 | 2 | 4 | null | 2012-09-18 16:07:29.427 UTC | 10 | 2021-07-19 09:39:18.113 UTC | null | null | null | null | 1,235,692 | null | 1 | 12 | jquery | 44,645 | <p>First about the issues:</p>
<ol>
<li><strong>ID-s must be unique!</strong></li>
<li>You have to properly nest your <code><li></code>-s</li>
</ol>
<hr>
<p>And here is how you can solve the problem - <a href="http://jsfiddle.net/VNkM2/2/" rel="noreferrer"><strong>DEMO</strong></a></p>
<p><strong><em>jQuery</em></strong></p>
<pre><code>$('.archive_month ul').hide();
$('.months').click(function() {
$(this).find('ul').slideToggle();
});
</code></pre>
<p><strong><em>HTML</em></strong> <em>(fixed)</em></p>
<pre><code><ul class="archive_year">
<li class="years">2012
<ul class="archive_month">
<li class="months">September
<ul class="archive_posts">
<li class="posts">Article 1</li>
<li class="posts">Article 2</li>
<li class="posts">Article 3</li>
<li class="posts">Article 4</li>
</ul>
</li>
<li class="months">August
<ul class="archive_posts">
<li class="posts">Article 1</li>
</ul>
</li>
</ul>
</li>
<li class="years">2011</li>
<ul class="archive_month">
<li class="months">July
<ul class="archive_posts">
<li class="posts">Article 1</li>
</ul>
</li>
</ul>
</li>
<li class="years">2009</li>
<ul class="archive_month">
<li class="months">January
<ul class="archive_posts">
<li class="posts">Article 1</li>
</ul>
</li>
</ul>
</ul>
</code></pre> |
12,363,047 | How to update column in a table from another table based on condition? | <p>I am having two tables </p>
<ol>
<li>student table it contains (Student_id,school_code,name,year,...)</li>
<li>school table it contains (school_id,School_code,School_name,year
etc.....)</li>
</ol>
<p>I want to update the school_code column in the student table with the school_id column in the school code table based on school code and year. i m having five years data. so school_id varies for every year. </p>
<p>My query was </p>
<pre><code>UPDATE Master.Student
SET school_code=( select school_id from Master.school as sc
JOIN master.student as st
ON st.school_code=sc.school_code
WHERE sc.year=x)
WHERE st.year=x;
</code></pre>
<p>But its not updating. I am getting error of <code>subquery returns more than one value</code>.</p> | 12,363,128 | 4 | 3 | null | 2012-09-11 05:04:51.32 UTC | 4 | 2020-09-04 08:57:39.283 UTC | 2012-10-29 07:54:50.713 UTC | null | 1,369,235 | null | 1,594,415 | null | 1 | 12 | sql-server|subquery|sql-update|multiple-tables | 67,238 | <p>Why to use sub-query when you can do that directly?</p>
<pre><code>UPDATE st
SET st.school_code = sc.school_id
FROM master.student AS st
JOIN Master.school AS sc
ON st.school_code = sc.school_code
WHERE sc.year=x
AND st.year=x;
</code></pre>
<p>For more info See <a href="http://msdn.microsoft.com/en-us/library/ms177523.aspx">UPDATE (Transact-SQL)</a></p> |
12,546,574 | Using Apple icons with iOS 6 | <p>With the release of iOS 6 I'd like to revisit the original question here: <a href="https://stackoverflow.com/questions/6950596/access-to-apples-built-in-icons">Access to Apple's built in Icons?</a></p>
<p>For example, when you hit the 'action' button to share a photo, now instead of an action sheet with buttons titled 'Message', 'Mail', etc., now there is a collection view of the icons for mail, messaging, facebook, twitter, etc.</p>
<p>For a 'share' action in my app I'd like to be able to present the same - because it looks better and would provide a consistent user experience. Is the use of these icons still not allowed, even if they are referring to (and would take the user to) the apps they originally belong to?</p> | 12,546,910 | 3 | 1 | null | 2012-09-22 18:31:55.43 UTC | 10 | 2013-08-08 01:40:37.193 UTC | 2017-05-23 12:28:11.97 UTC | null | -1 | null | 1,428,615 | null | 1 | 13 | ios|icons | 11,756 | <p>For just showing the share UI with icons, you probably want <code>UIActivityViewController</code>.</p>
<pre><code>NSString* someText = self.textView.text;
NSArray* dataToShare = @[someText]; // ...or whatever pieces of data you want to share.
UIActivityViewController* activityViewController =
[[UIActivityViewController alloc] initWithActivityItems:dataToShare
applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:^{}];
</code></pre>
<p>It looks like:</p>
<p><img src="https://i.stack.imgur.com/vvj6Y.png" alt="Screenshot of sharing UI in iOS6"></p>
<p>Documentation <a href="https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIActivityViewController_Class/Reference/Reference.html#//apple_ref/occ/cl/UIActivityViewController" rel="nofollow noreferrer">here</a>.</p> |
12,543,704 | how to hide my source code so to not be copied | <p>I was recently informed by someone that my website was copied. When I looked at the linked that he gave me I so that the site was identic to mine except for the logo and text. Is there a way to hide my code? Or to make it impossible to right click on my page? I saw on some websites that if you go to <a href="http://example.com/images/" rel="noreferrer">http://example.com/images/</a> it will show access denied, not a list with all your images...How do they do it?
Thank you!</p> | 12,543,750 | 8 | 2 | null | 2012-09-22 12:21:17.577 UTC | 8 | 2018-12-01 15:42:40.313 UTC | 2012-09-22 12:24:44.797 UTC | user355252 | null | null | 3,711,219 | null | 1 | 18 | html|copy | 78,224 | <p><strong>Don't do this!</strong> It makes no sense to do this, since the user can disable the script,
and there are many tools like Firebug by which a user can see the code.</p>
<p>The best way to keep safe the store is installing a security camera while leaving the doors open.</p>
<p>You can simply disable the right click by following:</p>
<pre><code><body oncontextmenu="return false">
...
</body>
</code></pre>
<p>or</p>
<pre><code><script language="javascript">
document.onmousedown = disableclick;
status = "Right Click Disabled";
Function disableclick(e)
{
if(event.button == 2)
{
alert(status);
return false;
}
}
</script>
</code></pre>
<p>The code above is from this <a href="http://www.codeproject.com/Articles/11222/Disabling-the-right-click-on-web-page" rel="nofollow">article</a> </p> |
12,068,945 | get layout height and width at run time android | <p>How can I get width and height of a linear layout which is defined in xml as fill_parent both in height and width? I have tried onmeasure method but I dont know why it is not giving exact value. I need these values in an Activity before oncreate method finishes. </p> | 12,212,341 | 5 | 2 | null | 2012-08-22 08:14:59.603 UTC | 8 | 2020-10-15 20:23:50.323 UTC | 2013-03-15 06:55:48.473 UTC | null | 291,827 | null | 1,516,775 | null | 1 | 21 | android-layout | 59,364 | <p>Suppose I have to get a <code>LinearLayout</code> width defined in XML. I have to get reference of it by XML. Define <code>LinearLayout</code> <code>l</code> as instance.</p>
<pre><code> l = (LinearLayout)findviewbyid(R.id.l1);
ViewTreeObserver observer = l.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
init();
l.getViewTreeObserver().removeGlobalOnLayoutListener(
this);
}
});
protected void init() {
int a= l.getHeight();
int b = l.getWidth();
Toast.makeText(getActivity,""+a+" "+b,3000).show();
}
callfragment();
}
</code></pre> |
12,260,906 | How to inject dependencies in jasmine test for an angular item | <p>Here is the test spec file:</p>
<pre><code>describe('Test main controller', function(){
it('Should initialize value to Loading', function(){
$scope = {}
ctrl = new mainNavController($scope)
expect($scope.wksp_name).toBe('Loading')
})
})
</code></pre>
<p>Here is the controller file</p>
<pre><code>function mainNavController($scope) {
$scope.wksp_name = 'Loading...'
$scope.$on('broadCastWkspNameEvent', function (e, args) {
$scope.wksp_name = args
})
}
mainNavController.$inject=['$scope']
</code></pre>
<p>But my test fails saying <code>Object #<Object> has no method '$on'</code></p>
<p>I am using the basic setup of jasmine. </p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner</title>
<link rel="shortcut icon" type="image/png" href="testlib/jasmine-1.2.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="testlib/jasmine-1.2.0/jasmine.css">
<script type="text/javascript" src="testlib/jasmine-1.2.0/jasmine.js"></script>
<script type="text/javascript" src="testlib/jasmine-1.2.0/jasmine-html.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="/static_files/js/test-specs/main-nav-spec.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="/static_files/js/common/jquery/latest.js"></script>
<script type="text/javascript" src="/static_files/js/common/angular/angular-1.0.1.min.js"></script>
<script type="text/javascript" src="/static_files/js/common/angular/angular-resource-1.0.1.min.js"></script>
<script type="text/javascript" src="/static_files/js/section/main-nav-controller.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
</body>
</html>
</code></pre>
<p>What is it that I am doing wrong? I am not able to understand how this thing is supposed to work :)</p> | 12,268,410 | 3 | 0 | null | 2012-09-04 09:51:49.783 UTC | 10 | 2018-02-15 12:02:28.457 UTC | 2018-02-15 12:02:28.457 UTC | null | 2,051,142 | null | 1,278,480 | null | 1 | 29 | jasmine|angularjs | 50,920 | <p>The main problem with your test code is that it tries to create a controller's instance "by hand" using the new operator. When doing so AngularJS has no chance to inject dependencies. What you should be doing is to allow AngularJS inject dependencies:</p>
<pre><code>var $scope, ctrl;
//you need to inject dependencies first
beforeEach(inject(function($rootScope) {
$scope = $rootScope.$new();
}));
it('Should initialize value to Loading', inject(function($controller) {
ctrl = $controller('MainNavController', {
$scope: $scope
});
expect($scope.wksp_name).toBe('Loading...');
}));
</code></pre>
<p>Here is the link to a complete jsFiddle: <a href="http://jsfiddle.net/pkozlowski_opensource/7a7KR/3/" rel="noreferrer">http://jsfiddle.net/pkozlowski_opensource/7a7KR/3/</a></p>
<p>There are 2 things worth noting in the above example:</p>
<ol>
<li>You can use the inject() method from the ngMock module to inject dependencies: <a href="https://docs.angularjs.org/api/ngMock/function/angular.mock.inject" rel="noreferrer">https://docs.angularjs.org/api/ngMock/function/angular.mock.inject</a></li>
<li>To create a controller instance (that supports dependency injection) you would use the $controller service: <a href="http://docs.angularjs.org/api/ng.$controller" rel="noreferrer">http://docs.angularjs.org/api/ng.$controller</a></li>
</ol>
<p>As the last remark: I would advise naming controllers starting with an uppercase letter - this way we won't confuse them with variable names.</p> |
12,505,158 | Generating a UUID in Postgres for Insert statement? | <p>My question is rather simple. I'm aware of the concept of a UUID and I want to generate one to refer to each 'item' from a 'store' in my DB with. Seems reasonable right?</p>
<p>The problem is the following line returns an error:</p>
<pre><code>honeydb=# insert into items values(
uuid_generate_v4(), 54.321, 31, 'desc 1', 31.94);
ERROR: function uuid_generate_v4() does not exist
LINE 2: uuid_generate_v4(), 54.321, 31, 'desc 1', 31.94);
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
</code></pre>
<p>I've read the page at: <a href="http://www.postgresql.org/docs/current/static/uuid-ossp.html" rel="noreferrer">http://www.postgresql.org/docs/current/static/uuid-ossp.html</a></p>
<p><img src="https://i.stack.imgur.com/BDeZ3.png" alt="enter image description here"></p>
<p>I'm running Postgres 8.4 on Ubuntu 10.04 x64.</p> | 12,505,220 | 9 | 2 | null | 2012-09-20 01:53:03.027 UTC | 132 | 2022-07-20 23:50:58.08 UTC | 2015-04-24 00:14:26.363 UTC | null | 398,670 | null | 584,947 | null | 1 | 544 | postgresql|uuid|postgresql-8.4 | 646,330 | <p><code>uuid-ossp</code> is a contrib module, so it isn't loaded into the server by default. You must load it into your database to use it.</p>
<p>For modern PostgreSQL versions (9.1 and newer) that's easy:</p>
<pre><code>CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
</code></pre>
<p>but for 9.0 and below you must instead run the SQL script to load the extension. See <a href="http://www.postgresql.org/docs/8.4/static/contrib.html" rel="noreferrer">the documentation for contrib modules in 8.4</a>.</p>
<p>For Pg 9.1 and newer instead read <a href="http://www.postgresql.org/docs/current/static/contrib.html" rel="noreferrer">the current contrib docs</a> and <a href="http://www.postgresql.org/docs/current/static/sql-createextension.html" rel="noreferrer"><code>CREATE EXTENSION</code></a>. These features do not exist in 9.0 or older versions, like your 8.4.</p>
<p>If you're using a packaged version of PostgreSQL you might need to install a separate package containing the contrib modules and extensions. Search your package manager database for 'postgres' and 'contrib'.</p> |
12,421,989 | NetworkStream.ReadAsync with a cancellation token never cancels | <p>Here the proof.<br>
Any idea what is wrong in this code ?</p>
<pre><code> [TestMethod]
public void TestTest()
{
var tcp = new TcpClient() { ReceiveTimeout = 5000, SendTimeout = 20000 };
tcp.Connect(IPAddress.Parse("176.31.100.115"), 25);
bool ok = Read(tcp.GetStream()).Wait(30000);
Assert.IsTrue(ok);
}
async Task Read(NetworkStream stream)
{
using (var cancellationTokenSource = new CancellationTokenSource(5000))
{
int receivedCount;
try
{
var buffer = new byte[1000];
receivedCount = await stream.ReadAsync(buffer, 0, 1000, cancellationTokenSource.Token);
}
catch (TimeoutException e)
{
receivedCount = -1;
}
}
}
</code></pre> | 12,893,018 | 6 | 3 | null | 2012-09-14 09:45:12.833 UTC | 17 | 2020-09-04 15:04:56.013 UTC | 2014-04-02 09:59:36.963 UTC | null | 885,318 | null | 299,674 | null | 1 | 44 | .net|sockets|.net-4.5|async-await|cancellation-token | 26,572 | <p>I finally found a workaround. Combine the async call with a delay task (Task.Delay) using Task.WaitAny. When the delay elapses before the io task, close the stream. This will force the task to stop. You should handle the async exception on the io task correctly. And you should add a continuation task for both the delayed task and the io task.</p>
<p>It also work with tcp connections. Closing the connection in another thread (you could consider it is the delay task thread) forces all async tasks using/waiting for this connection to stop.</p>
<p>--EDIT--</p>
<p>Another cleaner solution suggested by @vtortola: use the cancellation token to register a call to stream.Close:</p>
<pre><code>async ValueTask Read(NetworkStream stream, TimeSpan timeout = default)
{
if(timeout == default(TimeSpan))
timeout = TimeSpan.FromSeconds(5);
using var cts = new CancellationTokenSource(timeout); //C# 8 syntax
using(cts.Token.Register(() => stream.Close()))
{
int receivedCount;
try
{
var buffer = new byte[30000];
receivedCount = await stream.ReadAsync(buffer, 0, 30000, tcs.Token).ConfigureAwait(false);
}
catch (TimeoutException)
{
receivedCount = -1;
}
}
}
</code></pre> |
18,982,642 | How to disable and then enable onclick event on <div> with javascript | <p>Following is the code which i am trying</p>
<pre><code>document.getElementById("id").disabled = true;
</code></pre> | 18,983,026 | 5 | 4 | null | 2013-09-24 13:12:50.76 UTC | 25 | 2013-09-25 06:55:20.91 UTC | 2013-09-24 13:22:37.83 UTC | null | 1,640,484 | null | 2,798,259 | null | 1 | 41 | javascript|jquery | 199,397 | <p>You can use the CSS property <code>pointer-events</code> to disable the click event on any element:</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events</a></p>
<pre><code>// To disable:
document.getElementById('id').style.pointerEvents = 'none';
// To re-enable:
document.getElementById('id').style.pointerEvents = 'auto';
// Use '' if you want to allow CSS rules to set the value
</code></pre>
<p>Here is a JsBin: <a href="http://jsbin.com/oyAhuRI/1/edit" rel="noreferrer">http://jsbin.com/oyAhuRI/1/edit</a></p> |
18,884,713 | Dynamic drop down list using html and php | <p>I'm learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make a drop down list of employees who belong to a type of department and a specific contract type. In the code would be something like:</p>
<pre><code><html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()"> <!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()"> <!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<?php if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
</code></pre>
<p>The question I have is: how to get the selected values from the first drop-down lists (type_hire and department) for use in the query and fill the drop down list of employees. I know how to fill a dropdown list by querying the DB (what I learned in an online course) but I do not know how to take the values from the dropdown lists and use them in my practice. I read that I can use "document.getElementById (" id "). Value" to give that value to the variable in the query, but nowhere explained in detail how. I am new to web programming and my knowledge of Javascript are poor. Can anyone tell me the best way to do this?. It is possible only using html and php or I have to use javascript?</p> | 18,884,849 | 2 | 6 | null | 2013-09-19 01:01:53.637 UTC | 2 | 2017-10-26 12:36:51.493 UTC | 2013-10-08 09:57:30.963 UTC | null | 2,685,938 | null | 59,468 | null | 1 | 0 | javascript|php|html|html-select | 72,006 | <p>Heres a modified jQuery version of your code. (With some cleanup)</p>
<pre><code><html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()">
<!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()">
<!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<? if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
</body>
</html>
</code></pre>
<p>Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out <a href="http://php.net/manual/en/mysqlinfo.library.choosing.php" rel="nofollow">http://php.net/manual/en/mysqlinfo.library.choosing.php</a> for more info on that. On to the scripting...</p>
<pre><code><script type="text/javascript">
$('#type_hire').change(function() {
var selected = $('#type_hire option:selected'); //This should be the selected object
$.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
//Now data is the results from the DropdownRetrievalScript.php
$('select[name="employees"]').html(data);
}
}
</script>
</code></pre>
<p>Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.</p>
<p>Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.</p> |
3,282,080 | jQuery: how to get "value" of file upload input field | <p>Is it possible to determine if the user has selected a file for a particular input type="file" field using javascript/jQuery?</p>
<p>I have developed a custom fieldtype for ExpressionEngine (PHP-based CMS) that lets users upload and store their files on Amazon S3, but the most popular EE hosting service has set a max_file_uploads limit of 20. I'd like to allow the user to upload 20 files, edit the entry again to add 20 more, etc. Unfortunately upon editing the entry the initial 20 files have a "replace this image" file input field that appears to be knocking out the possibility of uploading new images. I'd like to remove any unused file input fields via javascript when the form is submitted.</p> | 3,282,153 | 3 | 0 | null | 2010-07-19 14:40:43.41 UTC | 1 | 2013-05-21 11:30:03.31 UTC | null | null | null | null | 113,910 | null | 1 | 12 | php|javascript|jquery|forms|file-upload | 61,832 | <p>Yes - you can read the value and even bind to the <code>change</code> event if you want.</p>
<pre><code><html>
<head>
<title>Test Page</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function()
{
$('#tester').change( function()
{
console.log( $(this).val() );
});
});
</script>
</head>
<body>
<input type="file" id="tester" />
</body>
</html>
</code></pre>
<p>But there are other, multiple-upload solutions that might suit your needs better, such as bpeterson76 posted.</p> |
3,337,056 | Convenient way to parse incoming multipart/form-data parameters in a Servlet | <p>Is there any convenient way to read and parse data from incoming request.</p>
<p>E.g client initiate post request</p>
<pre><code>URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
OutputStream output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!
// Send normal param.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"param\"");
writer.println("Content-Type: text/plain; charset=" + charset);
writer.println();
writer.println(param);
</code></pre>
<p>I’m not able to get param using <code>request.getParameter("paramName")</code>. The following code</p>
<pre><code>BufferedReader reader = new BufferedReader(new InputStreamReader(
request.getInputStream()));
StringBuilder sb = new StringBuilder();
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
</code></pre>
<p>however displays the content for me </p>
<pre><code>-----------------------------29772313742745
Content-Disposition: form-data; name="name"
J.Doe
-----------------------------29772313742745
Content-Disposition: form-data; name="email"
[email protected]
-----------------------------29772313742745
</code></pre>
<p>What is the best way to parse incoming request? I don’t want to write my own parser, probably there is a ready solution.</p> | 3,337,115 | 3 | 0 | null | 2010-07-26 16:57:00.807 UTC | 24 | 2016-04-11 20:44:12.393 UTC | 2010-07-26 17:03:19.95 UTC | null | 157,882 | null | 402,527 | null | 1 | 66 | java|servlets|urlconnection | 153,031 | <p><code>multipart/form-data</code> encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using <code>application/x-www-form-urlencoded</code> encoding. When using a different encoding, the <code>request.getParameter()</code> calls will all return <code>null</code>. When you're already on Servlet 3.0 (<a href="http://glassfish.dev.java.net" rel="noreferrer">Glassfish 3</a>, <a href="http://tomcat.apache.org" rel="noreferrer">Tomcat 7</a>, etc), then you can use <a href="http://java.sun.com/javaee/6/docs/api/javax/servlet/http/HttpServletRequest.html#getParts()" rel="noreferrer"><code>HttpServletRequest#getParts()</code></a> instead. Also see <a href="http://balusc.blogspot.com/2009/12/uploading-files-in-servlet-30.html" rel="noreferrer">this blog</a> for extended examples.</p>
<p>Prior to Servlet 3.0, a <a href="http://en.wikipedia.org/wiki/De_facto" rel="noreferrer">de facto</a> standard to parse <code>multipart/form-data</code> requests would be using <a href="http://commons.apache.org/fileupload" rel="noreferrer">Apache Commons FileUpload</a>. Just carefully read its <em>User Guide</em> and <em>Frequently Asked Questions</em> sections to learn how to use it. I've posted an answer with a code example before <a href="https://stackoverflow.com/questions/2422468/upload-big-file-to-servlet/2424824#2424824">here</a> (it also contains an example targeting Servlet 3.0).</p> |
18,932,756 | Disable all CGI (php, perl, …) for a directory using .htaccess | <p>I have a directory where users can upload files.</p>
<p>To avoid security issues (e.g. somebody uploading a malicious php script), I currently change the files' extension by appending <code>.data</code> for example, but then when downloading the file, they have to manually remove the <code>.data</code>.</p>
<p>Another common solution is to upload the files in a directory that is not served by Apache, and <a href="https://stackoverflow.com/a/17949520/324969">have a php script manage all downloads</a> by calling <code>readfile()</code>.</p>
<p>What I'd like to do is to simply disallow execution of any scripts (php, perl, cgi scripts, whatever I may install in the future) in the upload folder. <a href="https://stackoverflow.com/a/7454539/324969">This SO answer</a> suggests adding the following line in a <code>.htaccess</code> file in that folder:</p>
<pre><code>SetHandler default-handler
</code></pre>
<p>However, in my case this has no effect (the example php script I put in that folder is still executed). What am I doing wrong?</p>
<h1>Apache configuration</h1>
<p>The machine is a VPS (Virtual Private Server) running <code>Debian GNU/Linux 6.0.7 (squeeze)</code>, and as far as I can remember (I note down all commands I run on that server, so my "memory" should be pretty accurate), I dindn't change anything in apache2 configuration, appart from running <code>sudo apt-get install php5</code>, and creating the the file <code>/etc/apache2/sites-enabled/mysite.com</code> with the following contents:</p>
<pre><code><VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName mysite.com
ServerAlias www.mysite.com
DocumentRoot /home/me/www/mysite.com/www/
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
<Directory /home/me/www/mysite.com/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from All
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code></pre> | 18,948,152 | 2 | 9 | null | 2013-09-21 12:43:12.84 UTC | 8 | 2016-03-02 16:49:33.957 UTC | 2017-05-23 12:25:51.473 UTC | null | -1 | null | 324,969 | null | 1 | 19 | apache|.htaccess|security | 30,784 | <p>Put this in your <code>.htaccess</code>:</p>
<pre><code><Files *>
# @mivk mentionned in the comments that this may break
# directory indexes generated by Options +Indexes.
SetHandler default-handler
</Files>
</code></pre>
<p>But this has a few security holes: one can upload a .htaccess in a subdirectory, and override these settings, and they might also overwrite the .htaccess file itself!</p>
<p>If you're paranoid that the behaviour of the option should change in the future, put this in your <code>/etc/apache2/sites-enabled/mysite.com</code></p>
<pre><code> <Directory /home/me/www/upload/>
# Important for security, prevents someone from
# uploading a malicious .htaccess
AllowOverride None
SetHandler none
SetHandler default-handler
Options -ExecCGI
php_flag engine off
RemoveHandler .cgi .php .php3 .php4 .php5 .phtml .pl .py .pyc .pyo
<Files *>
AllowOverride None
SetHandler none
SetHandler default-handler
Options -ExecCGI
php_flag engine off
RemoveHandler .cgi .php .php3 .php4 .php5 .phtml .pl .py .pyc .pyo
</Files>
</Directory>
</code></pre>
<p>If you can't modify the apache configuration, then put the files in a <code>.htaccess</code> with the following directory structure:</p>
<pre><code>/home/me/www/
|- myuploadscript.php
|- protected/
|- .htaccess
|- upload/
|- Uploaded files go here
</code></pre>
<p>That way, nobody should be able to overwrite your <code>.../protected/.htaccess</code> file since their uploads go in a subdirectory of <code>.../protected</code>, not in <code>protected</code> itself.</p>
<p>AFAICT, you should be pretty safe with that.</p> |
8,561,393 | Is using increment (operator++) on floats bad style? | <p>Is it considered "bad style" to use the increment operator (++) on floats? It compiles just fine but I find it smelly and counter-intuitive.</p>
<p>The question: In what cases is using <code>++</code> on float variable justified and better than <code>+= 1.0f</code>? If there are no use cases, is there a respectable C++ style guide that explicitly says that ++ on float is evil?</p>
<p>For float ++ does not increment by the smallest possble value, but by 1.0. 1.0f has no special meaning (unlike integer 1). It may confuse the reader causing him to think that the variable is int.</p>
<p>For float it is not guaranteed that operator++ changes the argument. For example the following loop is not infinite:</p>
<pre><code>float i, j;
for (i=0.0, j=1.0; i!=j;i=j++);
</code></pre>
<p>Consequently doing ++ immediately after -- does not guarantee that the value is unchanged.</p> | 8,561,455 | 5 | 6 | null | 2011-12-19 12:29:31.567 UTC | 10 | 2021-03-26 15:33:49.573 UTC | 2011-12-19 12:54:07.197 UTC | null | 847,601 | null | 50,194 | null | 1 | 34 | c++|coding-style|floating-point | 48,848 | <p><strike>In general <code>++/--</code> is not defined for floats, since it's not clear with which value the float should be incremented. So, you may have luck on one system where <code>++</code> leads to <code>f += 1.0f</code> but there may be situations where this is not valid. Therefore, for floats, you'll have to provide a specific value.</strike></p>
<p><code>++/--</code> is defined as "increment/decrement by 1". Therefore this is applicable to floating point values. However, personally i think, that this can be confusing to someone who isn't aware of this definition (or only applies it to integers), so i would recommend using <code>f += 1.0f</code>.</p> |
25,998,437 | Why is respond_with being removed from rails 4.2 into it's own gem? | <p>In <a href="http://weblog.rubyonrails.org/2014/8/20/Rails-4-2-beta1/">rails 4.2</a> respond_with has been moved out of core into the responders gem.</p>
<p>Beta release notes.</p>
<p><code>respond_with has moved out and into its own proper home with the responders gem.</code></p>
<p>Can someone please explain why? What makes the responders gem its proper home? What is wrong with it staying in the Rails gem?</p> | 25,998,873 | 1 | 6 | null | 2014-09-23 15:01:43.857 UTC | 8 | 2015-04-23 16:34:07.55 UTC | 2014-09-23 15:10:51.793 UTC | null | 438,992 | null | 799,618 | null | 1 | 43 | ruby-on-rails|ruby | 16,513 | <p>Rationale from David Heinemeier Hansson (creator of Ruby on Rails):</p>
<blockquote>
<p>I'd like to take this opportunity to split respond_with/class-level
respond_to into an external plugin. I'm generally not a fan of the
code that comes out of using this pattern. It encourages model#to_json
and it hides the difference between HTML and API responses in ways
that convolute the code.</p>
<p>So how about we split this into a gem for 4.2, with the current
behavior, but also with an option to get the new behavior as suggested
here through a configuration point.</p>
</blockquote>
<p>Full discussion at this link:</p>
<p><a href="https://github.com/rails/rails/pull/12136#issuecomment-50216483" rel="noreferrer">https://github.com/rails/rails/pull/12136#issuecomment-50216483</a></p> |
10,999,392 | How to get CPU, RAM and Network-Usage of a Java7 App | <p>I found this older article <a href="https://stackoverflow.com/questions/47177/how-to-monitor-the-computers-cpu-memory-and-disk-usage-in-java">how-to-monitor-the-computers-cpu-memory-and-disk-usage-in-java</a>
and wated to ask, if there is something new in java 7. I want to get the current CPU-, RAM- and netzwork-Usage of my App periodically. It has to work for linux (mac) and windows. The data must not be extremely detailed, 3 values would be enough (cpu: 10%, Ram 4%, Network 40%). Would be cool if the data is just for the app and not the whole os-system, however this would work, too. </p>
<p>Thank's for help</p> | 11,058,821 | 4 | 0 | null | 2012-06-12 15:03:38.107 UTC | 10 | 2020-09-28 18:42:58.017 UTC | 2017-05-23 11:45:51.947 UTC | null | -1 | null | 1,277,462 | null | 1 | 8 | java|networking|cpu|java-7|ram | 16,085 | <p>answering my own question ;P some code i have written...</p>
<p>NetworkData:</p>
<pre><code>public class NetworkData {
static Map<String, Long> rxCurrentMap = new HashMap<String, Long>();
static Map<String, List<Long>> rxChangeMap = new HashMap<String, List<Long>>();
static Map<String, Long> txCurrentMap = new HashMap<String, Long>();
static Map<String, List<Long>> txChangeMap = new HashMap<String, List<Long>>();
private static Sigar sigar;
/**
* @throws InterruptedException
* @throws SigarException
*
*/
public NetworkData(Sigar s) throws SigarException, InterruptedException {
sigar = s;
getMetric();
System.out.println(networkInfo());
Thread.sleep(1000);
}
public static void main(String[] args) throws SigarException,
InterruptedException {
new NetworkData(new Sigar());
NetworkData.startMetricTest();
}
public static String networkInfo() throws SigarException {
String info = sigar.getNetInfo().toString();
info += "\n"+ sigar.getNetInterfaceConfig().toString();
return info;
}
public static String getDefaultGateway() throws SigarException {
return sigar.getNetInfo().getDefaultGateway();
}
public static void startMetricTest() throws SigarException, InterruptedException {
while (true) {
Long[] m = getMetric();
long totalrx = m[0];
long totaltx = m[1];
System.out.print("totalrx(download): ");
System.out.println("\t" + Sigar.formatSize(totalrx));
System.out.print("totaltx(upload): ");
System.out.println("\t" + Sigar.formatSize(totaltx));
System.out.println("-----------------------------------");
Thread.sleep(1000);
}
}
public static Long[] getMetric() throws SigarException {
for (String ni : sigar.getNetInterfaceList()) {
// System.out.println(ni);
NetInterfaceStat netStat = sigar.getNetInterfaceStat(ni);
NetInterfaceConfig ifConfig = sigar.getNetInterfaceConfig(ni);
String hwaddr = null;
if (!NetFlags.NULL_HWADDR.equals(ifConfig.getHwaddr())) {
hwaddr = ifConfig.getHwaddr();
}
if (hwaddr != null) {
long rxCurrenttmp = netStat.getRxBytes();
saveChange(rxCurrentMap, rxChangeMap, hwaddr, rxCurrenttmp, ni);
long txCurrenttmp = netStat.getTxBytes();
saveChange(txCurrentMap, txChangeMap, hwaddr, txCurrenttmp, ni);
}
}
long totalrxDown = getMetricData(rxChangeMap);
long totaltxUp = getMetricData(txChangeMap);
for (List<Long> l : rxChangeMap.values())
l.clear();
for (List<Long> l : txChangeMap.values())
l.clear();
return new Long[] { totalrxDown, totaltxUp };
}
private static long getMetricData(Map<String, List<Long>> rxChangeMap) {
long total = 0;
for (Entry<String, List<Long>> entry : rxChangeMap.entrySet()) {
int average = 0;
for (Long l : entry.getValue()) {
average += l;
}
total += average / entry.getValue().size();
}
return total;
}
private static void saveChange(Map<String, Long> currentMap,
Map<String, List<Long>> changeMap, String hwaddr, long current,
String ni) {
Long oldCurrent = currentMap.get(ni);
if (oldCurrent != null) {
List<Long> list = changeMap.get(hwaddr);
if (list == null) {
list = new LinkedList<Long>();
changeMap.put(hwaddr, list);
}
list.add((current - oldCurrent));
}
currentMap.put(ni, current);
}
}
</code></pre>
<p>CPU-Data:</p>
<pre><code>public class CpuData {
private static Sigar sigar;
public CpuData(Sigar s) throws SigarException {
sigar = s;
System.out.println(cpuInfo());
}
public static void main(String[] args) throws InterruptedException, SigarException {
new CpuData(new Sigar());
CpuData.startMetricTest();
}
private static void startMetricTest() throws InterruptedException, SigarException {
new Thread() {
public void run() {
while(true)
BigInteger.probablePrime(MAX_PRIORITY, new Random());
};
}.start();
while(true) {
String pid = ""+sigar.getPid();
System.out.print(getMetric(pid));
for(Double d:getMetric()){
System.out.print("\t"+d);
}
System.out.println();
Thread.sleep(1000);
}
}
public String cpuInfo() throws SigarException {
CpuInfo[] infos = sigar.getCpuInfoList();
CpuInfo info = infos[0];
String infoString = info.toString();
if ((info.getTotalCores() != info.getTotalSockets())
|| (info.getCoresPerSocket() > info.getTotalCores())) {
infoString+=" Physical CPUs: " + info.getTotalSockets();
infoString+=" Cores per CPU: " + info.getCoresPerSocket();
}
long cacheSize = info.getCacheSize();
if (cacheSize != Sigar.FIELD_NOTIMPL) {
infoString+="Cache size...." + cacheSize;
}
return infoString;
}
public static Double[] getMetric() throws SigarException {
CpuPerc cpu = sigar.getCpuPerc();
double system = cpu.getSys();
double user = cpu.getUser();
double idle = cpu.getIdle();
// System.out.println("idle: " +CpuPerc.format(idle) +", system: "+CpuPerc.format(system)+ ", user: "+CpuPerc.format(user));
return new Double[] {system, user, idle};
}
public static double getMetric(String pid) throws SigarException {
ProcCpu cpu = sigar.getProcCpu(pid);
// System.out.println(sigar.getProcFd(pid));
// System.err.println(cpu.toString());
return cpu.getPercent();
}
}
</code></pre>
<p>RAM-Data:</p>
<pre><code>public class RamData {
private static Sigar sigar;
private static Map<String, Long> pageFoults;
public RamData(Sigar s) throws SigarException {
sigar = s;
System.out.println(getMetric().toString());
}
public static void main(String[] args) throws SigarException,
InterruptedException {
new RamData(new Sigar());
RamData.startMetricTest();
}
public static void startMetricTest() throws SigarException,
InterruptedException {
while (true) {
Map<String, String> map = RamData.getMetric("" + sigar.getPid());
System.out.println("Resident: \t\t"
+ Sigar.formatSize(Long.valueOf(map.get("Resident"))));
System.out.println("PageFaults: \t\t" + map.get("PageFaults"));
System.out.println("PageFaultsTotal:\t" + map.get("PageFaultsTotal"));
System.out.println("Size: \t\t"
+ Sigar.formatSize(Long.valueOf(map.get("Size"))));
Map<String, String> map2 = getMetric();
for (Entry<String, String> e : map2.entrySet()) {
String s;
try {
s = Sigar.formatSize(Long.valueOf(e.getValue()));
} catch (NumberFormatException ex) {
s = ((int) (double) Double.valueOf(e.getValue())) + "%";
}
System.out.print(" " + e.getKey() + ": " + s);
}
System.out.println("\n------------------");
Thread.sleep(1000);
}
}
public static Map<String, String> getMetric() throws SigarException {
Mem mem = sigar.getMem();
return (Map<String, String>) mem.toMap();
}
public static Map<String, String> getMetric(String pid)
throws SigarException {
if (pageFoults == null)
pageFoults = new HashMap<String, Long>();
ProcMem state = sigar.getProcMem(pid);
Map<String, String> map = new TreeMap<String, String>(state.toMap());
if (!pageFoults.containsKey(pid))
pageFoults.put(pid, state.getPageFaults());
map.put("PageFaults", ""
+ (state.getPageFaults() - pageFoults.get(pid)));
map.put("PageFaultsTotal", ""+state.getPageFaults());
return map;
}
}
</code></pre>
<p>PROCES-Data:</p>
<pre><code>public class ProcessData {
private static Sigar sigar;
public ProcessData(Sigar s) throws SigarException {
this.sigar = s;
System.out.println(getMetric().toString());
System.out.println(getMetric(getPidString()).toString());
}
public static void main(String[] args) throws SigarException {
new ProcessData(new Sigar());
System.out.println(ProcessData.getMetric());
System.out.println(ProcessData.getMetric(getPidString()));
}
public static Map<String, String> getMetric() throws SigarException {
ProcStat state = sigar.getProcStat();
return (Map<String, String>) state.toMap();
}
public static Map<String, String> getMetric(String pid) throws SigarException {
ProcState state = sigar.getProcState(pid);
return (Map<String, String>) state.toMap();
}
public static long getPid() {
return sigar.getPid();
}
public static String getPidString() {
return ""+sigar.getPid();
}
}
</code></pre> |
11,294,326 | highcharts pass multiple values to tooltip | <p>I need to display 3 values on the tooltip:
the time, the value and another value(change).</p>
<p>I saw <a href="http://www.highcharts.com/stock/demo/candlestick" rel="noreferrer">this example</a> (but the jsdfiddle is not working). </p>
<p>I tried this</p>
<pre><code>//each loop..
indice.push(["time", "value1", "value2"]);
</code></pre>
<p>, the tooltip settings</p>
<pre><code>tooltip:
{
useHTML: true,
formatter: function()
{
return '' + Highcharts.dateFormat('%H:%M:%S', this.x) +'; '+ this.y + this.z(<-is this right?);
}
},
</code></pre>
<p>and the series</p>
<pre><code>series:
[{
type: 'area',
data: indice
}]
</code></pre>
<p>can somone help pls?
thsnks.</p> | 11,295,015 | 5 | 2 | null | 2012-07-02 13:06:54.183 UTC | 7 | 2019-08-15 17:36:59.727 UTC | 2012-07-02 15:10:02.84 UTC | null | 1,253,219 | null | 1,392,330 | null | 1 | 22 | javascript|tooltip|highcharts | 41,891 | <p>If you want to pass additional data for a point other than the x and y values, then you have to name that value. In the following <a href="http://jsfiddle.net/6tc6T/3/"><strong>example</strong></a> I add the following three additional values to each data point:</p>
<pre><code>{
y: 3,
locked: 1,
unlocked: 1,
potential: 1,
}
</code></pre>
<p>Then to access and display those values in the tooltip I use the following:</p>
<pre><code>tooltip:
{
formatter: function() { return ' ' +
'Locked: ' + this.point.locked + '<br />' +
'Unlocked: ' + this.point.unlocked + '<br />' +
'Potential: ' + this.point.potential;
}
}
</code></pre> |
11,146,255 | Create a mutable java.lang.String | <p>It's common knowledge that Java <code>String</code>s are immutable. Immutable Strings are great addition to java since its inception. Immutability allows fast access and a lot of optimizations, significantly less error-prone compared to C-style strings, and helps enforce the security model.</p>
<p>It's possible to create a mutable one without using hacks, namely</p>
<ul>
<li><code>java.lang.reflect</code></li>
<li><code>sun.misc.Unsafe</code></li>
<li>Classes in bootstrap classloader</li>
<li>JNI (or JNA as it requires JNI)</li>
</ul>
<p>But is it possible in just plain Java, so that the string can be modified at any time? The question is <em>How</em>?</p> | 11,147,102 | 6 | 17 | null | 2012-06-21 20:30:07.65 UTC | 36 | 2019-03-23 07:59:00.123 UTC | 2017-11-30 14:39:18.177 UTC | null | 783,580 | null | 554,431 | null | 1 | 50 | java|string|security | 33,167 | <p>Creating a <code>java.lang.String</code> with the Charset constructor, one can inject your own Charset, which brings your own <code>CharsetDecoder</code>. The <code>CharsetDecoder</code> gets a reference to a <code>CharBuffer</code> object in the decodeLoop method. The CharBuffer wraps the char[] of the original String object. Since the CharsetDecoder has a reference to it, you can change the underlying char[] using the CharBuffer, thus you have a mutable String.</p>
<pre><code>public class MutableStringTest {
// http://stackoverflow.com/questions/11146255/how-to-create-mutable-java-lang-string#11146288
@Test
public void testMutableString() throws Exception {
final String s = createModifiableString();
System.out.println(s);
modify(s);
System.out.println(s);
}
private final AtomicReference<CharBuffer> cbRef = new AtomicReference<CharBuffer>();
private String createModifiableString() {
Charset charset = new Charset("foo", null) {
@Override
public boolean contains(Charset cs) {
return false;
}
@Override
public CharsetDecoder newDecoder() {
CharsetDecoder cd = new CharsetDecoder(this, 1.0f, 1.0f) {
@Override
protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
cbRef.set(out);
while(in.remaining()>0) {
out.append((char)in.get());
}
return CoderResult.UNDERFLOW;
}
};
return cd;
}
@Override
public CharsetEncoder newEncoder() {
return null;
}
};
return new String("abc".getBytes(), charset);
}
private void modify(String s) {
CharBuffer charBuffer = cbRef.get();
charBuffer.position(0);
charBuffer.put("xyz");
}
}
</code></pre>
<p>Running the code prints</p>
<pre><code>abc
zzz
</code></pre>
<p>I don't know how to correctly implement decodeLoop(), but i don't care right now :)</p> |
11,448,068 | MySQL error code: 1175 during UPDATE in MySQL Workbench | <p>I'm trying to update the column <code>visited</code> to give it the value 1. I use MySQL workbench, and I'm writing the statement in the SQL editor from inside the workbench. I'm writing the following command:</p>
<pre><code>UPDATE tablename SET columnname=1;
</code></pre>
<p>It gives me the following error:</p>
<blockquote>
<p>You are using safe update mode and you tried to update a table without
a WHERE that uses a KEY column To disable safe mode, toggle the option
....</p>
</blockquote>
<p>I followed the instructions, and I unchecked the <code>safe update</code> option from the <code>Edit</code> menu then <code>Preferences</code> then <code>SQL Editor</code>. The same error still appear & I'm not able to update this value. Please, tell me what is wrong?</p> | 11,448,213 | 23 | 3 | null | 2012-07-12 08:44:39.407 UTC | 271 | 2022-02-15 08:57:55.327 UTC | 2013-01-10 04:40:34.96 UTC | null | 104,223 | null | 1,476,749 | null | 1 | 1,100 | mysql|sql-update|mysql-workbench | 2,442,714 | <p>I found the answer. The problem was that I have to precede the table name with the schema name. i.e, the command should be:</p>
<pre><code>UPDATE schemaname.tablename SET columnname=1;
</code></pre>
<p>Thanks all.</p> |
11,177,954 | How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X) | <p>My version of node is always v0.6.1-pre even after I install brew node and NVM install v0.6.19.</p>
<p>My node version is:</p>
<pre class="lang-none prettyprint-override"><code>node -v
v0.6.1-pre
</code></pre>
<p>NVM says this (after I install a version of node for the first time in one bash terminal):</p>
<pre class="lang-none prettyprint-override"><code>nvm ls
v0.6.19
current: v0.6.19
</code></pre>
<p>But when I restart bash, this is what I see:</p>
<pre class="lang-none prettyprint-override"><code>nvm ls
v0.6.19
current: v0.6.1-pre
default -> 0.6.19 (-> v0.6.19)
</code></pre>
<p>So where is this phantom node 0.6.1-pre version and how can I get rid of it? I'm trying to install libraries via NPM so that I can work on a project.</p>
<p>I tried using BREW to update before NVM, using <code>brew update</code> and <code>brew install node</code>.
I've tried deleting the "node" directory in my <code>/usr/local/include</code> and the "node" and "node_modules" in my <code>/usr/local/lib</code>.
I've tried uninstalling npm and reinstalling it following <a href="https://superuser.com/questions/268946/uninstall-node-js">these</a> instructions.</p>
<p>All of this because I was trying to update an older version of node to install the "zipstream" library. Now there's folders in my users directory, and the node version STILL isn't up to date, even though NVM says it's using 0.6.19.</p>
<p><strong>Ideally, I'd like to uninstall nodejs, npm, and nvm, and just reinstall the entire thing from scratch on my system.</strong></p> | 11,178,106 | 34 | 5 | null | 2012-06-24 13:40:56.31 UTC | 691 | 2022-09-21 07:32:32.103 UTC | 2020-05-14 10:49:27.837 UTC | null | 860,099 | null | 1,247,659 | null | 1 | 1,639 | javascript|node.js|npm | 2,398,137 | <p>Apparently, there was a <code>/Users/myusername/local</code> folder that contained a <code>include</code> with <code>node</code> and <code>lib</code> with <code>node</code> and <code>node_modules</code>. How and why this was created instead of in my <code>/usr/local</code> folder, I do not know.</p>
<p>Deleting these local references fixed the phantom v0.6.1-pre. If anyone has an explanation, I'll choose that as the correct answer.</p>
<p><strong>EDIT:</strong></p>
<p>You may need to do the additional instructions as well:</p>
<pre><code>sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
</code></pre>
<p>which is the equivalent of (same as above)...</p>
<pre><code>sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node* /usr/local/lib/dtrace/node.d ~/.npm ~/.node-gyp
</code></pre>
<p>or (same as above) broken down...</p>
<p>To completely uninstall node + npm is to do the following:</p>
<ol>
<li>go to <strong>/usr/local/lib</strong> and delete any <strong>node</strong> and <strong>node_modules</strong></li>
<li>go to <strong>/usr/local/include</strong> and delete any <strong>node</strong> and <strong>node_modules</strong> directory </li>
<li>if you installed with <strong>brew install node</strong>, then run <strong>brew uninstall node</strong> in your terminal</li>
<li>check your Home directory for any <strong>local</strong> or <strong>lib</strong> or <strong>include</strong> folders, and delete any <strong>node</strong> or <strong>node_modules</strong> from there</li>
<li>go to <strong>/usr/local/bin</strong> and delete any <strong>node</strong> executable</li>
</ol>
<p>You may also need to do:</p>
<pre><code>sudo rm -rf /opt/local/bin/node /opt/local/include/node /opt/local/lib/node_modules
sudo rm -rf /usr/local/bin/npm /usr/local/share/man/man1/node.1 /usr/local/lib/dtrace/node.d
</code></pre>
<p>Additionally, NVM modifies the PATH variable in <code>$HOME/.bashrc</code>, which must be <a href="https://github.com/creationix/nvm#removal" rel="noreferrer">reverted manually</a>.</p>
<p>Then download <strong>nvm</strong> and follow the instructions to install node. The latest versions of node come with <strong>npm</strong>, I believe, but you can also reinstall that as well.</p> |
13,112,811 | How to insert current date into MySQL database use Java? | <p>I want to insert the current date and time into a columns defined as datetime type.</p>
<p>I typed the following code:</p>
<pre><code>java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
PrepStmt.setDate(1, sqlDate);
</code></pre>
<p>When I check the database, I find that the date inserted correctly, but the time is: 00:00:00. What is the fix ?</p> | 13,112,873 | 6 | 2 | null | 2012-10-28 20:40:19.797 UTC | 7 | 2019-06-06 09:40:00.523 UTC | 2019-06-06 09:40:00.523 UTC | null | 3,728,901 | null | 1,476,749 | null | 1 | 17 | java|mysql | 53,070 | <p>Since you are using <code>datetime</code> as your column type, you need to use <code>java.sql.Timestamp</code> to store your date, and <code>PrepareStatement.setTimestamp</code> to insert it. </p>
<p>Try using this: -</p>
<pre><code>java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
PrepStmt.setTimestamp(1, date);
</code></pre> |
12,807,115 | What would 'std:;' do in c++? | <p>I was recently modifying some code, and found a pre-existing bug on one line within a function:</p>
<pre><code>std:;string x = y;
</code></pre>
<p>This code still compiles and has been working as expected.</p>
<p>The string definition works because this file is <code>using namespace std;</code>, so the <code>std::</code> was unnecessary in the first place.</p>
<p>The question is, why is <code>std:;</code> compiling and what, if anything, is it doing?</p> | 12,807,141 | 5 | 5 | null | 2012-10-09 19:32:27.717 UTC | 6 | 2014-02-15 10:57:14.8 UTC | 2012-10-09 19:37:13.113 UTC | null | 500,104 | null | 1,410,910 | null | 1 | 89 | c++|std|colon | 2,303 | <p><code>std:</code> its a label, usable as a target for <code>goto</code>.</p>
<p>As pointed by <em>@Adam Rosenfield</em> in a comment, it is a legal label name.</p>
<p><em>C++03 §6.1/1:</em></p>
<blockquote>
<p>Labels have their own name space and do not interfere with other identifiers.</p>
</blockquote> |
37,315,085 | An Elegant way to change columns type in dataframe in R | <p>I have a data.frame which contains columns of different types, such as integer, character, numeric, and factor.</p>
<p>I need to convert the integer columns to numeric for use in the next step of analysis. </p>
<p><strong>Example</strong>: <code>test.data</code> includes 4 columns (though there are thousands in my real data set): <code>age</code>, <code>gender</code>, <code>work.years</code>, and <code>name</code>; <code>age</code> and <code>work.years</code> are integer, <code>gender</code> is factor, and <code>name</code> is character. What I need to do is change <code>age</code> and <code>work.years</code> into a numeric type. And I wrote one piece of code to do this.</p>
<pre><code>test.data[sapply(test.data, is.integer)] <-lapply(test.data[sapply(test.data, is.integer)], as.numeric)
</code></pre>
<p>It looks not good enough though it works. So I am wondering if there is some more elegant methods to fulfill this function. Any creative method will be appreciated.</p> | 37,316,042 | 3 | 9 | null | 2016-05-19 06:06:45.257 UTC | 10 | 2019-03-19 14:55:50.307 UTC | 2016-05-19 13:20:39.597 UTC | null | 4,895,725 | null | 6,354,470 | null | 1 | 9 | r | 67,016 | <p>I think elegant code is sometimes subjective. For me, this is elegant but it may be less efficient compared to the OP's code. However, as the question is about elegant code, this can be used.</p>
<pre><code>test.data[] <- lapply(test.data, function(x) if(is.integer(x)) as.numeric(x) else x)
</code></pre>
<p>Also, another elegant option is <code>dplyr</code></p>
<pre><code>library(dplyr)
library(magrittr)
test.data %<>%
mutate_each(funs(if(is.integer(.)) as.numeric(.) else .))
</code></pre> |
17,016,259 | How to configure Python Kivy for PyCharm on Windows? | <p>I'm having trouble getting Kivy to work with PyCharm on Windows 7. I've managed to add most of the external libraries through File > Settings > Python interpreters > Paths Tab.</p>
<p>I'm using the Kivy version of Python.
When I run a Kivy app that works fine with using the [right click > send to > kivy.bat] method in PyCharm, it gives me this error:</p>
<pre><code>Failed modules
Python 2.7.3 (C:/Python27/python.exe)
_imagingtk
dde
gtk._gtk
pangocairo
Generation of skeletons for the modules above will be tried again when the modules are updated or a new version of generator is available
</code></pre>
<p>I think that the problem might be something to do with cython, as my file fails to recognise the kivy.properties file, which is of the Cython *.pxd format.</p> | 26,984,289 | 7 | 1 | null | 2013-06-10 02:47:27.303 UTC | 11 | 2021-09-08 22:34:54.383 UTC | 2020-08-26 11:57:33.54 UTC | null | 1,839,439 | null | 2,469,456 | null | 1 | 19 | python|windows|python-2.7|pycharm|kivy | 56,035 | <p>This Kivy's Wiki page <a href="https://github.com/kivy/kivy/wiki/Setting-Up-Kivy-with-various-popular-IDE's">Setting Up Kivy with various popular IDE's</a> has a better answer and detail commands. It is copied below with added information for Pycharm 3.4. </p>
<p>Go to your unzipped Kivy folder, create a symbol link for "kivy.bat" pointing to "python.bat" in the same directory (mklink python.bat kivy.bat).</p>
<p>Add 2 new Python interpreters in PyCharm.</p>
<ul>
<li>Bootstrapper: Choose the earlier created "python.bat" from the Kivy package folder.</li>
<li>Project Interpreter: Choose the "python.exe" from the Python subdirectory in the Kivy package folder.</li>
</ul>
<p>For the project interpreter, add a path to the "kivy" directory directly contained in the Kivy package folder. In PyCharm 3.4, the path tab is hidden in a sub menu. In Project Interpreter, click the tool icon next to the interpreter dropdown list, click more... (the last one), in the list of all project interpreters, select Run-Configuration Interpreter, on the right side there are five icons (+, -, edit, virtual env, and path), click path to add the Kivy sub-directory in unzipped Kivy folder. </p>
<p>Save all settings and ignore warnings about "Invalid output format". Make sure that the project interpreter is set to our earlier created configuration.</p>
<p>Create a new run configuration and set the Python interpreter to our earlier created bootstrapper. </p>
<p>Simply run the configuration to execute your Kivy application</p> |
16,831,536 | Can you change a file content during git commit? | <p>One of the things I keep in my <a href="http://jj.github.io/hoborg/" rel="noreferrer">open novel in GitHub</a> is a <a href="https://github.com/JJ/hoborg/blob/master/text/words.dic" rel="noreferrer">list of words</a> I would like to set automatically the first line, which is the number of words in the dictionary. My first option is to write a pre-commit hook that reads the file, counts the words, rewrites the first line and writes it back again. Here's the code</p>
<pre><code>PRE_COMMIT {
my ($git) = @_;
my $branch = $git->command(qw/rev-parse --abbrev-ref HEAD/);
say "Pre-commit hook in $branch";
if ( $branch =~ /master/ ) {
my $changed = $git->command(qw/show --name-status/);
my @changed_files = ($changed =~ /\s\w\s+(\S+)/g);
if ( $words ~~ @changed_files ) {
my @words_content = read_file( $words );
say "I have $#words_content words";
$words_content[0] = "$#words_content\n";
write_file( $words, @words_content );
}
}
};
</code></pre>
<p>However, since the file has already been staged, I get this error</p>
<blockquote>
<p>error: Your local changes to the following files would be overwritten
by checkout:
text/words.dic
Please, commit your changes or stash them
before you can switch branches.
Aborting</p>
</blockquote>
<p>Might it be better to do it as a post-commit hook and have it changed for the next commit? Or do something completely different altogether? The general question is: if you want to process and change the contents of a file during commit, what's the proper way of doing it?</p> | 16,832,764 | 2 | 1 | null | 2013-05-30 08:39:43.09 UTC | 8 | 2021-08-06 12:28:24.523 UTC | 2013-05-30 09:43:53.7 UTC | null | 891,440 | null | 891,440 | null | 1 | 39 | git|hook|commit | 27,547 | <p>The actual commit stuck in by <code>git commit</code> is whatever is in the index once the pre-commit hook finishes. This means that you <em>can</em> change files in the pre-commit hook, as long as you <code>git add</code> them too.</p>
<p>Here's my example pre-commit hook, modified from the .sample:</p>
<pre><code>#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# [snipped much of what used to be in it, added this --
# make sure you take out the exec of git diff-index!]
num=$(cat zorg)
num=$(expr 0$num + 1)
echo $num > zorg
git add zorg
echo "updated zorg to $num"
exit 0
</code></pre>
<p>and then:</p>
<pre><code>$ git commit -m dink
updated zorg to 3
[master 76eeefc] dink
1 file changed, 1 insertion(+), 1 deletion(-)
</code></pre>
<p>But note a minor flaw (won't apply to your case):</p>
<pre><code>$ git commit
git commit
updated zorg to 4
# On branch master
# Untracked files:
[snip]
nothing added to commit but untracked files present (use "git add" to track)
$ git commit
updated zorg to 5
# Please enter the commit message for your changes. Lines starting
[snip - I quit editor without changing anything]
Aborting commit due to empty commit message.
$ git commit
updated zorg to 6
# Please enter the commit message for your changes. Lines starting
</code></pre>
<p>Basically, because the pre-commit hook updates and <code>git add</code>s, the file keeps incrementing even though I'm not actually doing the commit, here.</p>
<p>[<strong>Edit</strong> Aug 2021: I need to emphasize that I <em>do not</em> recommend this approach. Note that there are some oddball cases that can come up when using <code>git commit -a</code>, <code>git commit --include</code>, and <code>git commit --only</code>, including the implied <code>--only</code> that is inserted if you name files on the command line. This is due to the fact that this kind of <code>git commit</code> creates a second, and sometimes even a third, internal Git index. Any <code>git add</code> operations you do inside a hook can only affect <em>one</em> of these two or three index files.]</p> |
58,100,739 | how to generate a json object in kotlin? | <p>I'm really new in programming, and recently started a project in Kotlin with Android Studio. </p>
<p>So, I have a problem with a JSON object. I get data from an BroadcastReceiver object, a String to be more specific, with the next format:</p>
<pre><code>{"s1":1}
</code></pre>
<p>This, is a simple string. So I took in a function call toJson and I do this.</p>
<pre><code>private fun toJson(data:String): JSONObject {
var newData: String = data.replace("\"","")
newData = newData.replace("{","")
newData = newData.replace("}","")
val newObject = newData.split(":")
val name = newObject[0]
val value = newObject[1]
val rootObject = JSONObject()
rootObject.put(name,value)
return rootObject
}
</code></pre>
<p>Im doing this the right way?, how can I improve my code?</p>
<p>Thanks for your help, and sorry for my english!</p> | 58,101,247 | 3 | 3 | null | 2019-09-25 14:27:33.943 UTC | 4 | 2020-11-29 22:39:53.737 UTC | 2019-09-25 23:15:33.107 UTC | null | 5,308,259 | null | 8,358,502 | null | 1 | 16 | android|kotlin | 52,729 | <p>Welcome to StackOverflow!</p>
<p>In 2019 no-one is really parsing JSON manually. It's much easier to use <a href="https://github.com/google/gson" rel="noreferrer">Gson</a> library. It takes as an input your object and spits out JSON string and vice-versa.</p>
<p>Example:</p>
<pre><code>data class MyClass(@SerializedName("s1") val s1: Int)
val myClass: MyClass = Gson().fromJson(data, MyClass::class.java)
val outputJson: String = Gson().toJson(myClass)
</code></pre>
<p>This way you're not working with JSON string directly but rather with Kotlin object which is type-safe and more convenient.
Look at the docs. It's pretty big and easy to understand</p>
<p>Here is some tutorials:</p>
<ul>
<li><a href="https://www.youtube.com/watch?v=f-kcvxYZrB4" rel="noreferrer">https://www.youtube.com/watch?v=f-kcvxYZrB4</a></li>
<li><a href="http://www.studytrails.com/java/json/java-google-json-introduction/" rel="noreferrer">http://www.studytrails.com/java/json/java-google-json-introduction/</a></li>
<li><a href="https://www.tutorialspoint.com/gson/index.htm" rel="noreferrer">https://www.tutorialspoint.com/gson/index.htm</a></li>
</ul>
<p><strong>UPDATE</strong>: If you really want to use JSONObject then use its constructor with a string parameter which parses your JSON string automatically.</p>
<pre><code>val jsonObject = JSONObject(data)
</code></pre> |
4,527,204 | log4j - set different loglevel for different packages/classes | <p>I use log4j for logging and i want to print all logger.debug statements in a particular class / selected package.</p>
<p>i set the cfg as below></p>
<pre><code>log4j.category.my.pkg=info
log4j.category.my.pkg.ab.class1=debug
</code></pre>
<p>but still only info messages are shown..</p>
<p>is this not the right way ?</p> | 4,527,351 | 2 | 0 | null | 2010-12-24 16:05:58.71 UTC | 10 | 2020-10-09 19:15:39.723 UTC | 2020-10-09 19:15:39.723 UTC | null | 2,756,574 | null | 348,139 | null | 1 | 54 | java|log4j | 67,999 | <p>Instead of using 'category' use 'logger'. Hence, these level are configured for entire log4j, and does not depend on appender, etc.</p>
<p>Following change works:</p>
<pre><code>log4j.logger.my.pkg=info
log4j.logger.my.pkg.ab.class1=debug
</code></pre> |
26,461,966 | osx 10.10 Curl POST to HTTPS url gives SSLRead() error | <p>I just recently upgraded to OSX 10.10 Yosemite and I since the upgrade I can't do Curl POST to a SSL url anymore.</p>
<p>I first used wordpress's <code>wp_remote_request</code> call and also tried to use curl in php.
Both (as expected) give the same error message:</p>
<blockquote>
<p>Error Number:56</p>
<p>Error String:SSLRead() return error -9806</p>
</blockquote>
<p>Note: when I curl POST to HTTP it works fine.
I reckon it is a setting in PHP.ini or in my apache (I lost my original HTTPD.conf file after upgrade...).</p>
<p>Can anyone help me out?</p> | 26,538,127 | 3 | 7 | null | 2014-10-20 09:05:05.683 UTC | 26 | 2018-09-05 17:25:47.753 UTC | 2018-09-05 17:25:47.753 UTC | null | 166,339 | null | 806,094 | null | 1 | 72 | php|macos|apache|curl|osx-yosemite | 37,549 | <p>I've seen this error happen when php is compiled with a version of cURL that uses <a href="https://developer.apple.com/library/mac/documentation/security/Reference/secureTransportRef/" rel="noreferrer">Apple's Secure Transport</a> under Yosemite and the target of the URL request doesn't support SSLv3 (which was probably disabled due to the <a href="http://googleonlinesecurity.blogspot.com/2014/10/this-poodle-bites-exploiting-ssl-30.html" rel="noreferrer">POODLE vulnerability</a>). What is the output of this command?</p>
<pre><code>$ php -i | grep "SSL Version"
</code></pre>
<p>I suspect you'll see this:</p>
<pre><code>SSL Version => SecureTransport
</code></pre>
<p>You can overcome this by installing a version of php which uses a version of cURL which uses OpenSSL instead of SecureTransport. This is most easily done with <a href="http://brew.sh/" rel="noreferrer">homebrew</a>. So install that first if you don't already have it. If homebrew is installed but you haven't run <code>brew update</code> since upgrading to Yosemite, do that first. Also make sure you've installed XCode >= 6.1 and the latest XCode command line tools. <code>brew doctor</code> will tell you if you've done it all right.</p>
<p>Add the Homebrew taps below that you will need in order to get brewed php installed. Skip this step if these repos are already tapped. If you're unsure if these repos are already tapped, just run the commands below. Worst case scenario, you'll get a harmless <code>Warning: Already tapped!</code></p>
<pre><code>$ brew tap homebrew/dupes
$ brew tap homebrew/versions
$ brew tap homebrew/php
</code></pre>
<p>Then install curl with openssl:</p>
<pre><code>$ brew install --with-openssl curl
</code></pre>
<p>Then install php using the curl you just installed and brewed openssl:</p>
<pre><code>$ brew install --with-homebrew-curl --with-httpd24 php55
</code></pre>
<ul>
<li><p>if using apache, make sure to add <code>LoadModule php5_module /usr/local/opt/php55/libexec/apache2/libphp5.so</code> to your <code>/etc/apache2/httpd.conf</code> and restart apache.</p></li>
<li><p>if not using apache 2.4, you can remove <code>--with-httpd24</code> from the above command.</p></li>
<li><p>if using nginx, follow the caveat instuctions for starting fpm:</p>
<blockquote>
<p>To launch php-fpm on startup:</p>
<pre><code>mkdir -p ~/Library/LaunchAgents
cp /usr/local/opt/php55/homebrew.mxcl.php55.plist ~/Library/LaunchAgents/
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.php55.plist
</code></pre>
</blockquote></li>
</ul>
<p>Install any php extensions you're going to need eg. <code>mcrypt</code>.</p>
<pre><code>$ brew install php55-mcrypt
</code></pre>
<p>After you're done, run this again:</p>
<pre><code>$ php -i | grep "SSL Version"
</code></pre>
<p>And you should see:</p>
<pre><code>SSL Version => OpenSSL/1.0.2h
</code></pre>
<p>And now, re-test your application and the <code>SSLRead() return error -9806</code> should go away.</p> |
68,065,743 | Cannot run gradle test tasks because of java.lang.NoClassDefFoundError: jdk/internal/reflect/GeneratedSerializationConstructorAccessor1 | <p>I have an android project where I cannot run anymore all the test gradle tasks locally (I have 3 different flavors in this project). I have this error message 50 times before the tasks fail. I have no issue running these tasks remotely with Gitlab CI/CD, and I have another project locally where I don't have this issue neither.</p>
<pre><code>java.lang.NoClassDefFoundError: jdk/internal/reflect/GeneratedSerializationConstructorAccessor1
at jdk.internal.reflect.GeneratedSerializationConstructorAccessor1.newInstance(Unknown Source)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at java.base/java.io.ObjectStreamClass.newInstance(ObjectStreamClass.java:1092)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2150)
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1668)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:482)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:440)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.deserializeWorker(SystemApplicationClassLoaderWorker.java:153)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:121)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
</code></pre> | 68,139,455 | 5 | 4 | null | 2021-06-21 09:46:23.66 UTC | 8 | 2022-04-12 17:45:40.157 UTC | null | null | null | null | 9,905,408 | null | 1 | 37 | java|android|unit-testing|gradle | 13,139 | <p>This is an old issue, but for future google searchers and perhaps interested parties that could work around this, it is worth mentioning that if you are using one of the more popular walk-throughs to set up JaCoCo + Robolectric + Espresso - <a href="https://medium.com/@rafael_toledo/setting-up-an-unified-coverage-report-in-android-with-jacoco-robolectric-and-espresso-ffe239aaf3fa" rel="noreferrer">https://medium.com/@rafael_toledo/setting-up-an-unified-coverage-report-in-android-with-jacoco-robolectric-and-espresso-ffe239aaf3fa</a> . Please add below this:</p>
<pre><code>tasks.withType(Test) {
jacoco.includeNoLocationClasses = true
jacoco.excludes = ['jdk.internal.*']
}
</code></pre>
<p>In my case:</p>
<pre><code>junitJacoco {
jacocoVersion = '0.8.4' // type String
includeInstrumentationCoverageInMergedReport = true // type boolean
tasks.withType(Test) {
jacoco.includeNoLocationClasses = true
jacoco.excludes = ['jdk.internal.*']
}
}
</code></pre> |
10,152,539 | Protobuf-net serialization/deserialization | <p>I checked but seem to be unable to see how to directly serialize a class to a byte array and subsequently deserialize from a byte array using Marc Gravell's protobuf-net implementation. </p>
<p>Edit: I changed the question and provided code because the original question of how to serialize into byte[] without having to go through stream was admittedly trivial. My apologies.</p>
<p>Updated Question: Is there any way to not have to deal with generics and instead infer the type of the property "MessageBody" through reflection when it is passed through the constructor? I assume I cannot serialize object type, correct? The current solution looks very cumbersome in that I need to pass in the type of the MessageBody each time I instantiate a new Message. Is there a sleeker solution to this? </p>
<p>I came up with the following:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Message<string> msg = new Message<string>("Producer", "Consumer", "Test Message");
byte[] byteArray = msg.Serialize();
Message<string> message = Message<string>.Deserialize(byteArray);
Console.WriteLine("Output");
Console.WriteLine(message.From);
Console.WriteLine(message.To);
Console.WriteLine(message.MessageBody);
Console.ReadLine();
}
}
[ProtoContract]
public class Message<T>
{
[ProtoMember(1)]
public string From { get; private set; }
[ProtoMember(2)]
public string To { get; private set; }
[ProtoMember(3)]
public T MessageBody { get; private set; }
public Message()
{
}
public Message(string from, string to, T messageBody)
{
this.From = from;
this.To = to;
this.MessageBody = messageBody;
}
public byte[] Serialize()
{
byte[] msgOut;
using (var stream = new MemoryStream())
{
Serializer.Serialize(stream, this);
msgOut = stream.GetBuffer();
}
return msgOut;
}
public static Message<T> Deserialize(byte[] message)
{
Message<T> msgOut;
using (var stream = new MemoryStream(message))
{
msgOut = Serializer.Deserialize<Message<T>>(stream);
}
return msgOut;
}
}
</code></pre>
<p>What I like to get to is something such as: </p>
<p>Message newMsg = new Message("Producer", "Consumer", Foo);
byte[] byteArray = newMsg.Serialize();</p>
<p>and
Message msg = Message.Deserialize(byteArray);</p>
<p>(where Deserialize is a static method and it always deserializes into an object of type Message and only needs to know what type to deserialize the message body into).</p> | 10,153,871 | 2 | 5 | null | 2012-04-14 09:33:01.727 UTC | 4 | 2015-12-26 12:50:01.627 UTC | 2012-04-14 13:03:59.44 UTC | null | 1,023,928 | null | 1,023,928 | null | 1 | 10 | c#|serialization|bytearray|protocol-buffers|protobuf-net | 40,339 | <p>there's a few different questions here, so I'll answer what I can see: if I've missed anything just let me know.</p>
<p>Firstly, as noted, a MemoryStream is the most common way of getting to a byte[]. This is consistent with most serializers - for example, XmlSerializer, BinaryFormatter and DataContractSerializer <em>also</em> don't have an "as a byte[] overload", but will accept MemoryStream.</p>
<p>Generics: you don't need to use generics; v1 has Serializer.NonGeneric, which wraps this away from you. In v2, the "core" is non-generic, and can be accessed via RuntimeTypeModel.Default; of course Serializer and Serializer.NonGeneric continue to work.</p>
<p>For the issue of having to include the type: yes, the protobuf spec assumes the receiver knows what type of data they are being given. A simple option here is to use a simple wrapper object as the "root" object, with multiple typed properties for the data (only one of which is non-null). Another option might spring from the inbuilt inheritance support via ProtoInclude (note: as an implementation detail, these two approaches are identical).</p>
<p>In your specific example, perhaps consider:</p>
<pre><code>[ProtoContract]
[ProtoInclude(1, typeof(Message<Foo>))]
.... More as needed
[ProtoInclude(8, typeof(Message<Bar>))]
public abstract class Message
{ }
[ProtoContract]
public class Message<T> : Message
{
...
}
</code></pre>
<p>Then just serialize with <code><Message></code> - the API will create the right type automatically.</p>
<p>With recent builds, there is also a <strong>DynamicType</strong> option that includes type data for you, for example:</p>
<pre><code>[ProtoContract]
public class MyRoot {
[ProtoMember(1, DynamicType=true)]
public object Value { get; set; }
}
</code></pre>
<p>This will work for any Value that holds a contract-type instance (but not for primitives, and ideally not involving inheritance).</p> |
9,667,243 | mysql match string with start of string in table | <p>I realise that it would be a lot easier if I could modify the table when it was created, but assuming I can't, I have a table that is such as:</p>
<pre><code>abcd
abde
abdf
abff
bbsdf
bcggs
... snip large amount
zza
</code></pre>
<p>The values in the table are not fixed length.
I have a string to match such as abffagpokejfkjs .
If it was the other way round, I could do </p>
<pre><code>SELECT * from table where value like 'abff%'
</code></pre>
<p>but I need to select the value that matches the start of a string that is provided.</p>
<p>Is there a quick way of doing that, or does it need an itteration through the table to find a match?</p> | 9,667,309 | 2 | 2 | null | 2012-03-12 12:44:54.11 UTC | 1 | 2020-05-07 23:53:27.257 UTC | null | null | null | null | 364,082 | null | 1 | 22 | mysql | 51,007 | <p>Try this:</p>
<pre><code>SELECT col1, col2 -- etc...
FROM your_table
WHERE 'abffagpokejfkjs' LIKE CONCAT(value, '%')
</code></pre>
<p>Note that this will not use an index effectively so it will be slow if you have a lot of records.</p>
<p>Also note that some characters in <code>value</code> (e.g. <code>%</code>) may be interpreted by LIKE as having a special meaning, which may undesirable.</p> |
9,939,589 | How to programmatically use iOS voice synthesizers? (text to speech) | <p>iOS devices have embedded voice synthesizers for Accessibility's VoiceOver feature. Is there a way you can use these synthesizers programmatically to generate text-based sounds?</p>
<p>My problem is: I'm working on a simple app for kids to learn colors and rather than recording the names of the colors in each language i want to support and storing them as audio files, i'd rather generate the sounds at runtime with some text-to-speech feature.</p>
<p>Thanks</p>
<p>[EDIT: this question was asked pre-iOS7 so you should really consider the voted answer and ignore older ones, unless you're a software archeologist]</p> | 18,891,418 | 6 | 0 | null | 2012-03-30 08:38:37.94 UTC | 15 | 2017-09-11 16:54:18.057 UTC | 2014-01-21 17:15:37.883 UTC | null | 455,016 | null | 455,016 | null | 1 | 40 | ios|accessibility|voice|audio | 35,986 | <p>Starting from iOS 7, Apple provides <a href="https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVSpeechSynthesizer_Ref/Reference/Reference.html" rel="noreferrer">this</a> API.</p>
<p>See <a href="https://stackoverflow.com/a/17465494/215748">this</a> answer.</p>
<p><strong>Objective-C</strong></p>
<pre><code>#import <AVFoundation/AVFoundation.h>
…
AVSpeechUtterance *utterance = [AVSpeechUtterance
speechUtteranceWithString:@"Hello World!"];
AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
[synth speakUtterance:utterance];
</code></pre>
<p><strong>Swift</strong></p>
<pre><code>import AVFoundation
…
let utterance = AVSpeechUtterance(string: "Hello World!")
let synth = AVSpeechSynthesizer()
synth.speakUtterance(utterance)
</code></pre> |
27,950,891 | How to use a pandas data frame in a unit test | <p>I am developing a set of python scripts to pre-process a dataset then produce a series of machine learning models using scikit-learn. I would like to develop a set of unittests to check the data pre-processing functions, and would like to be able to use a small test pandas dataframe for which I can determine the answers for and use it in assert statements.</p>
<p>I cannot seem to get it to load the dataframe and to pass it to the unit tests using self. My code looks something like this;</p>
<pre><code>def setUp(self):
TEST_INPUT_DIR = 'data/'
test_file_name = 'testdata.csv'
try:
data = pd.read_csv(INPUT_DIR + test_file_name,
sep = ',',
header = 0)
except IOError:
print 'cannot open file'
self.fixture = data
def tearDown(self):
del self.fixture
def test1(self):
self.assertEqual(somefunction(self.fixture), somevalue)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>Thanks for the help.</p> | 42,413,541 | 3 | 5 | null | 2015-01-14 19:28:25.92 UTC | 7 | 2020-09-25 20:16:40.947 UTC | 2015-01-14 19:40:20.53 UTC | null | 4,402,407 | null | 4,402,407 | null | 1 | 28 | python|pandas|python-unittest | 31,139 | <p>Pandas has some utilities for testing.</p>
<pre><code>import unittest
import pandas as pd
from pandas.util.testing import assert_frame_equal # <-- for testing dataframes
class DFTests(unittest.TestCase):
""" class for running unittests """
def setUp(self):
""" Your setUp """
TEST_INPUT_DIR = 'data/'
test_file_name = 'testdata.csv'
try:
data = pd.read_csv(INPUT_DIR + test_file_name,
sep = ',',
header = 0)
except IOError:
print 'cannot open file'
self.fixture = data
def test_dataFrame_constructedAsExpected(self):
""" Test that the dataframe read in equals what you expect"""
foo = pd.DataFrame()
assert_frame_equal(self.fixture, foo)
</code></pre> |
10,209,941 | Object of class DateTime could not be converted to string | <p>I have a table with string values in the format of <strong>Friday 20th April 2012</strong> in a field called <code>Film_Release</code></p>
<p>I am looping through and I want to convert them in <code>datetime</code> and roll them out into another table. My second table has a column called <code>Films_Date</code>, with a format of <code>DATE</code>. I am receiving this error</p>
<blockquote>
<p>Object of class DateTime could not be converted to string</p>
</blockquote>
<pre><code>$dateFromDB = $info['Film_Release'];
$newDate = DateTime::createFromFormat("l dS F Y",$dateFromDB); //( http:php.net/manual/en/datetime.createfromformat.php)
</code></pre>
<p>Then I insert <code>$newdate</code> into the table through an insert command.</p>
<p>Why am I be getting such an error?</p> | 10,210,000 | 8 | 0 | null | 2012-04-18 13:02:36.803 UTC | 7 | 2021-04-19 17:54:52.13 UTC | 2021-04-19 17:54:52.13 UTC | null | 12,771,208 | null | 683,924 | null | 1 | 61 | php|mysql|datetime|insert | 261,100 | <p>Because <code>$newDate</code> is an object of type <code>DateTime</code>, not a string. The <a href="http://php.net/manual/en/datetime.createfromformat.php" rel="noreferrer">documentation</a> is explicit:</p>
<blockquote>
<p>Returns new <code>DateTime</code> object formatted according to the specified
format.</p>
</blockquote>
<p>If you want to convert from a string to <code>DateTime</code> back to string to change the format, call <a href="http://www.php.net/manual/en/datetime.format.php" rel="noreferrer"><code>DateTime::format</code></a> at the end to get a formatted string out of your <code>DateTime</code>.</p>
<pre><code>$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y'); // for example
</code></pre> |
10,082,517 | simplest tool to measure C program cache hit/miss and cpu time in linux? | <p>I'm writing a small program in C, and I want to measure it's performance.</p>
<p>I want to see how much time do it run in the processor and how many cache hit+misses has it made. Information about context switches and memory usage would be nice to have too. </p>
<p>The program takes less than a second to execute.</p>
<p>I like the information of /proc/[pid]/stat, but I don't know how to see it after the program has died/been killed.</p>
<p>Any ideas?</p>
<p><strong>EDIT:</strong> I think Valgrind adds a lot of overhead. That's why I wanted a simple tool, like /proc/[pid]/stat, that is always there.</p> | 10,114,325 | 4 | 1 | null | 2012-04-10 02:47:56.353 UTC | 43 | 2020-11-18 19:38:58.507 UTC | 2018-05-28 05:14:28.32 UTC | null | 644,104 | null | 912,450 | null | 1 | 65 | performance|cpu-cache|measurement|context-switch|memcache-stats | 50,953 | <p>Use <strong>perf</strong>:</p>
<pre><code>perf stat ./yourapp
</code></pre>
<p>See the <a href="https://perf.wiki.kernel.org/index.php/Tutorial" rel="noreferrer">kernel wiki perf tutorial</a> for details. This uses the hardware performance counters of your CPU, so the overhead is very small.</p>
<p>Example from the wiki:</p>
<pre><code>perf stat -B dd if=/dev/zero of=/dev/null count=1000000
Performance counter stats for 'dd if=/dev/zero of=/dev/null count=1000000':
5,099 cache-misses # 0.005 M/sec (scaled from 66.58%)
235,384 cache-references # 0.246 M/sec (scaled from 66.56%)
9,281,660 branch-misses # 3.858 % (scaled from 33.50%)
240,609,766 branches # 251.559 M/sec (scaled from 33.66%)
1,403,561,257 instructions # 0.679 IPC (scaled from 50.23%)
2,066,201,729 cycles # 2160.227 M/sec (scaled from 66.67%)
217 page-faults # 0.000 M/sec
3 CPU-migrations # 0.000 M/sec
83 context-switches # 0.000 M/sec
956.474238 task-clock-msecs # 0.999 CPUs
0.957617512 seconds time elapsed
</code></pre>
<p>No need to load a kernel module manually, on a modern debian system (with the linux-base package) it should just work. With the <code>perf record -a</code> / <code>perf report</code> combo you can also do full-system profiling. Any application or library that has debugging symbols will show up with details in the report.</p>
<p>For visualization <a href="http://www.brendangregg.com/flamegraphs.html" rel="noreferrer">flame graphs</a> seem to work well. (Update 2020: the <a href="https://github.com/KDAB/hotspot" rel="noreferrer">hotspot</a> UI has flame graphs integrated.)</p> |
12,027,987 | How to copy directories with spaces in the name | <p>I am trying to use robocopy but am unable to make it work because of spaces in the directory names.<br>
I am trying to copy 3 directories: My Documents, My Music and My Pictures to 'C:\test-backup' but want the end result to be<br>
'C:\test-backup\My Documents'<br>
'C:\test-backup\My Music'<br>
'C:\test-backup\My Pictures' </p>
<p>My command does not work:<br>
<code>robocopy C:\Users\Angie C:\test-backup "My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"</code></p>
<p>No matter what I do, it’s just not happening. Anybody have any suggestions or tricks?</p> | 12,028,153 | 8 | 0 | null | 2012-08-19 16:13:46.58 UTC | 7 | 2020-09-18 01:43:14.42 UTC | 2015-11-03 06:52:18.723 UTC | null | 395,461 | null | 381,346 | null | 1 | 35 | directory|spaces|robocopy | 135,751 | <p>What's with separating <code>My Documents</code> from <code>C:\test-backup</code>? And why the quotes only around <code>My Documents</code>?</p>
<p>I'm assuming it's a typo, try using <code>robocopy C:\Users\Angie "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"</code></p>
<p><strong>[Edit:]</strong> Since the syntax the documentation specifies (<code>robocopy <Source> <Destination> [<File>[ ...]]</code>) says <em>File</em>, it might not work with <em>Folders</em>. </p>
<p>You'll have to use<code>robocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"</code></p> |
11,935,043 | git error when trying to push to remote branch | <p>I've cloned repository A's master branch from git and created my own branch called Li.
I've made some changes a while ago and pushed the contents of local Li to remote Li.</p>
<p>Now I've pulled some updates from remote master to my local master branch and from the local master branch to the local Li, and I'm trying to push the updates from local Li to remote Li.
However, when I try to run:</p>
<pre><code>git checkout Li
git push origin Li
</code></pre>
<p>I get the following error:</p>
<pre><code>error: failed to push some refs to '[email protected]:anodejs/system.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code></pre>
<p>Note that my local master branch is updated (I invoked git pull origin master) and merged into the local Li branch. I did, however, add local Li a new file, so local Li is not identical to local master (but this shouldn't matter, right?)</p>
<p>Thanks,
Li</p> | 11,935,408 | 4 | 2 | null | 2012-08-13 13:17:49.36 UTC | 13 | 2017-08-23 09:36:34.097 UTC | 2012-10-12 08:54:38.087 UTC | null | 469,220 | null | 429,400 | null | 1 | 41 | git|push | 70,843 | <p>Find the diff with <code>git fetch && git log Li..origin/Li</code>. I would guess you've rebased or otherwise recut <code>Li</code> since last time you pushed, but that command should tell you exactly what's in the remote that isn't in the local. You can find what's in either (but not both) with the triple-dot syntax: <code>git log Li...origin/Li</code>.</p>
<p>If the diff is expected, then just merge with <code>git merge origin/Li</code> and then <code>git push</code>. If the change is unwanted, overwrite the remote with <code>git push -f origin Li</code>. Only do this if you want to abandon the remote's changes.</p> |
11,498,441 | What is this kind of assignment in Python called? a = b = True | <p>I know about <a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">tuple unpacking</a> but what is this assignment called where you have multiple equals signs on a single line? a la <code>a = b = True</code></p>
<p>It always trips me up a bit especially when the RHS is mutable, but I'm having real trouble finding the right keywords to search for in the docs.</p> | 11,498,454 | 4 | 2 | null | 2012-07-16 05:13:25.093 UTC | 16 | 2019-01-18 07:21:55.727 UTC | null | null | null | null | 54,056 | null | 1 | 47 | python|variable-assignment | 19,079 | <p>It's a chain of assignments and the term used to describe it is...</p>
<p><sup>- Could I get a drumroll please?</sup></p>
<h3><em>Chained Assignment</em>.</h3>
<hr />
<p>I just gave it a quite google run and found that there isn't that much to read on the topic, probably since most people find it very straight-forward to use (and only the true geeks would like to know more about the topic).</p>
<hr />
<p>In the previous expression the order of evaluation can be viewed as starting at the right-most <code>=</code> and then working towards the left, which would be equivalent of writing:</p>
<pre><code>b = True
a = b
</code></pre>
<hr />
<p>The above order is what most language describe an <em>assignment-chain</em>, but python does it differently. In python the expression is evaluated as this below equivalent, though it won't result in any other result than what is previously described.</p>
<pre><code>temporary_expr_result = True
a = temporary_expr_result
b = temporary_expr_result
</code></pre>
<hr />
<p>Further reading available here on stackoverflow:</p>
<ul>
<li><strong><a href="https://stackoverflow.com/questions/7601823/how-do-chained-assignments-work">How do chained assignments work?</a></strong> <a href="/questions/tagged/python" class="post-tag" title="show questions tagged 'python'" rel="tag">python</a></li>
</ul> |
11,534,690 | How to do a Jquery Callback after form submit? | <p>I have a simple form with remote=true. </p>
<p>This form is actually on an HTML Dialog, which gets closed as soon as the Submit button is clicked.</p>
<p>Now I need to make some changes on the main HTML page after the form gets submitted successfully. </p>
<p>I tried this using jQuery. But this doesn't ensure that the tasks get performed after some form of response of the form submission.</p>
<pre><code>$("#myform").submit(function(event) {
// do the task here ..
});
</code></pre>
<p>How do I attach a callback, so that my code gets executed only after the form is successfully submitted? Is there any way to add some .success or .complete callback to the form?</p> | 11,543,243 | 7 | 3 | null | 2012-07-18 05:17:25.07 UTC | 45 | 2019-07-26 20:50:06.223 UTC | 2018-07-09 07:26:07.033 UTC | null | 9,959,912 | null | 609,235 | null | 1 | 128 | javascript|jquery|html|asp.net|webforms | 334,808 | <p>I just did this - </p>
<pre><code> $("#myform").bind('ajax:complete', function() {
// tasks to do
});
</code></pre>
<p>And things worked perfectly .</p>
<p>See <a href="http://api.jquery.com/ajaxComplete/" rel="noreferrer">this api documentation</a> for more specific details.</p> |
20,272,762 | First time learning assembly, is this saying a word size is 8-bytes? | <p>When I break main it looks like the bold line is where i is being created and initialized. I think I'm going at this all wrong, I'm trying to examine x86_64 assembly from a book that is explaining x86. This seems weird and I'm pretty sure I just don't understand seeing as in this book he says he'll refer to a word and dword as 4-bytes. If I could get an explanation to aid my incognisance it would be greatly appreciated.
<code> </p>
<pre> (gdb) list
1 #include <stdio.h>
2
3 int main()
4 {
5 int i;
6 for(i=0; i < 10; i++)
7 {
8 printf("Hello, world!\n");
9 }
10 return 0;
(gdb) disassemble main
Dump of assembler code for function main:
0x0000000100000f10 <+0>: push rbp
0x0000000100000f11 <+1>: mov rbp,rsp
0x0000000100000f14 <+4>: sub rsp,0x10
0x0000000100000f18 <+8>: mov DWORD PTR [rbp-0x4],0x0
0x0000000100000f1f <+15>: mov DWORD PTR [rbp-0x8],0x0
0x0000000100000f26 <+22>: cmp DWORD PTR [rbp-0x8],0xa
0x0000000100000f2d <+29>: jge 0x100000f54 <main+68>
0x0000000100000f33 <+35>: lea rdi,[rip+0x48] # 0x100000f82
0x0000000100000f3a <+42>: mov al,0x0
0x0000000100000f3c <+44>: call 0x100000f60
0x0000000100000f41 <+49>: mov DWORD PTR [rbp-0xc],eax
0x0000000100000f44 <+52>: mov eax,DWORD PTR [rbp-0x8]
0x0000000100000f47 <+55>: add eax,0x1
0x0000000100000f4c <+60>: mov DWORD PTR [rbp-0x8],eax
0x0000000100000f4f <+63>: jmp 0x100000f26 <main+22>
0x0000000100000f54 <+68>: mov eax,0x0
0x0000000100000f59 <+73>: add rsp,0x10
0x0000000100000f5d <+77>: pop rbp
0x0000000100000f5e <+78>: ret
End of assembler dump. </code>
</code></pre> | 20,273,175 | 1 | 9 | null | 2013-11-28 18:29:18.62 UTC | 9 | 2013-11-28 18:59:38.073 UTC | null | null | null | null | 1,562,759 | null | 1 | 15 | assembly|x86|size|word|x86-64 | 20,431 | <p>The terms used to describe sizes in the x86 architecture are:</p>
<ul>
<li><code>byte</code>: 8 bits</li>
<li><code>word</code>: 2 bytes</li>
<li><code>dword</code>: 4 bytes (stands for "double word")</li>
<li><code>qword</code>: 8 bytes (stands for "quad word")</li>
</ul>
<p>This is somewhat at odds with the usual meaning of "word": the 16-bit nature of <code>word</code> is a result of the evolution of x86 machines from their 16 bit origins, not a reflection of the natural word size of the machine. For compatibility reasons the size of a <code>word</code> operand must always remain the same, even on a 64-bit machine.</p>
<p>Note that the variable <code>i</code> in your program is 32 bits: you can see <code>dword</code> size annotations in the relevant stack accesses. It may be instructive to recompile your program with the type of <code>i</code> changed to <code>long int</code>.</p> |
20,180,874 | How to get length of a string using strlen function | <p>I have following code that gets and prints a string.</p>
<pre><code>#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << str;
getch();
return 0;
}
</code></pre>
<p>But how to count the number of characters in this string using <code>strlen()</code> function?</p> | 20,180,891 | 7 | 12 | null | 2013-11-24 20:55:11.287 UTC | 12 | 2020-05-08 17:53:33.157 UTC | 2017-02-26 20:30:55.59 UTC | null | 501,557 | null | 1,969,750 | null | 1 | 35 | c++|string | 270,645 | <p>For C++ strings, there's no reason to use <code>strlen</code>. Just use <code>string::length</code>:</p>
<pre><code>std::cout << str.length() << std::endl;
</code></pre>
<p>You should <em>strongly</em> prefer this to <code>strlen(str.c_str())</code> for the following reasons:</p>
<ol>
<li><p><strong><em>Clarity</em></strong>: The <code>length()</code> (or <code>size()</code>) member functions unambiguously give back the length of the string. While it's possible to figure out what <code>strlen(str.c_str())</code> does, it forces the reader to pause for a bit.</p></li>
<li><p><strong><em>Efficiency</em></strong>: <code>length()</code> and <code>size()</code> run in time O(1), while <code>strlen(str.c_str())</code> will take Θ(n) time to find the end of the string.</p></li>
<li><p><strong><em>Style</em></strong>: It's good to prefer the C++ versions of functions to the C versions unless there's a specific reason to do so otherwise. This is why, for example, it's usually considered better to use <code>std::sort</code> over <code>qsort</code> or <code>std::lower_bound</code> over <code>bsearch</code>, unless some other factors come into play that would affect performance.</p></li>
</ol>
<p>The only reason I could think of where <code>strlen</code> would be useful is if you had a C++-style string that had embedded null characters and you wanted to determine how many characters appeared before the first of them. (That's one way in which <code>strlen</code> differs from <code>string::length</code>; the former stops at a null terminator, and the latter counts all the characters in the string). But if that's the case, just use <code>string::find</code>:</p>
<pre><code>size_t index = str.find(0);
if (index == str::npos) index = str.length();
std::cout << index << std::endl;
</code></pre>
<p>Hope this helps!</p> |
4,041,662 | Algorithm to find solution to puzzle | <p>I am trying to make a game where a player has to find his way from Start to End on the Game Board.</p>
<p>As you see this Game Board contains a bunch of red circular obstacles. To win the game the player has to remove a minimum amount of obstacles. So my question is, how do I programmatically find out the minimum amount of obstacles to remove, to free a path? A free path would be considered the space between, circles not overlapping and not touching.</p>
<p>So what I really need is the minimum amount of circles to remove, I don't need the actual path. Is there an easy way to do this?</p>
<p>And to supplement understanding of this game board, the circles each have the same radius, and it is restricted by the black lines.</p>
<p>Also, it is not necessary to move in a straight line.</p> | 4,041,802 | 5 | 7 | null | 2010-10-28 09:50:07.427 UTC | 16 | 2019-08-05 11:13:18.513 UTC | 2019-08-05 11:13:18.513 UTC | null | 7,462,031 | null | 368,379 | null | 1 | 30 | algorithm|path|collision-detection|collision | 2,590 | <p>It is a graph theory <code>maximum flow</code> problem.</p>
<p>Suppose that every circle is a node in the graph. Additionally introduce 2 special nodes: <code>TOP</code> and <code>BOTTOM</code>. Connect circles with these nodes if they intersect with TOP/BOTTOM side. Connect nodes corresponding to circles with each other if the circles intersect.</p>
<p>Now you need to find a minimum cut in this graph, having <em>TOP as source</em> and <em>BOTTOM as sink</em> or vice versa. You can use <a href="http://en.wikipedia.org/wiki/Max-flow_min-cut_theorem" rel="noreferrer">Max-flow_min-cut_theorem</a> to solve it. What it states is that <code>Minimum-cut problem</code> is equivallent to Max-flow problem. You can find details on how to solve <code>Max-Flow problem</code> on <a href="http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=maxFlow" rel="noreferrer">TopCoder</a>.</p>
<p>As we can go through each node only once, we should convert the nodes into a directed edge of capacity one with in-node and out-node for each circle. The max-flow algorithm will solve the problem on the resulting graph and take into account the fact that we are removing circles rather than connections between circles. It is always a better decision for this problem to remove a node in a graph rather than edge, as we can always remove any edge by removing a node. Removing a node additionally can result in removing more than one edge. </p>
<p>By the way, a similar problem can be found on <a href="http://uva.onlinejudge.org/external/118/11853.html" rel="noreferrer">Uva Online Judge</a>. It a good idea to try solve this task on the judge, then you will be sure that your solution is correct.</p> |
3,487,434 | Overriding append method after inheriting from a Python List | <p>I want to create a list that can only accept certain types. As such, I'm trying to inherit from a list in Python, and overriding the append() method like so:</p>
<pre><code>class TypedList(list):
def __init__(self, type):
self.type = type
def append(item)
if not isinstance(item, type):
raise TypeError, 'item is not of type %s' % type
self.append(item) #append the item to itself (the list)
</code></pre>
<p>This will of cause an infinite loop because the body of append() calls itself, but I'm not sure what to do other than using self.append(item).</p>
<p>How I should go about doing this?</p> | 3,487,449 | 6 | 0 | null | 2010-08-15 12:54:38.88 UTC | 11 | 2020-08-29 20:29:50.183 UTC | null | null | null | null | 342,346 | null | 1 | 21 | python|list|inheritance | 35,709 | <p>I have made some changes to your class. This seems to be working. </p>
<p>A couple of suggestions: don't use <code>type</code> as a keyword - <code>type</code> is a built in function. Python instance variables are accessed using the <code>self.</code> prefix. So use <code>self.<variable name></code>.</p>
<pre><code>class TypedList(list):
def __init__(self, type):
self.type = type
def append(self, item):
if not isinstance(item, self.type):
raise TypeError, 'item is not of type %s' % self.type
super(TypedList, self).append(item) #append the item to itself (the list)
from types import *
tl = TypedList(StringType)
tl.append('abc')
tl.append(None)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
tl.append(None)
File "<pyshell#22>", line 7, in append
raise TypeError, 'item is not of type %s' % self.type
TypeError: item is not of type <type 'str'>
</code></pre> |
3,740,371 | How to find the element of an array that is repeated at least N/2 times? | <p>Given an array with N elements. We know that one of those elements repeats itself at least N/2 times.</p>
<p>We don't know anything about the other elements . They may repeat or may be unique . </p>
<p>Is there a way to find out the element that repeats at least N/2 times in a single pass or may be O(N)?</p>
<p>No extra space is to be used .</p> | 3,740,423 | 8 | 8 | null | 2010-09-18 04:21:05.51 UTC | 25 | 2016-09-19 09:30:26.82 UTC | 2016-05-10 18:31:53.683 UTC | null | 895,245 | null | 397,049 | null | 1 | 34 | c|algorithm | 29,523 | <p>st0le answered the question, but here's a 5minute implementation:</p>
<pre><code>#include <stdio.h>
#define SIZE 13
int boyerMoore(int arr[]) {
int current_candidate = arr[0], counter = 0, i;
for (i = 0; i < SIZE; ++i) {
if (current_candidate == arr[i]) {
++counter;
printf("candidate: %i, counter: %i\n",current_candidate,counter);
} else if (counter == 0) {
current_candidate = arr[i];
++counter;
printf("candidate: %i, counter: %i\n",current_candidate,counter);
} else {
--counter;
printf("candidate: %i, counter: %i\n",current_candidate,counter);
}
}
return current_candidate;
}
int main() {
int numbers[SIZE] = {5,5,5,3,3,1,1,3,3,3,1,3,3};
printf("majority: %i\n", boyerMoore(numbers));
return 0;
}
</code></pre>
<p>And here's a fun explanation (more fun than reading the paper, at least): <a href="http://userweb.cs.utexas.edu/~moore/best-ideas/mjrty/index.html" rel="noreferrer">http://userweb.cs.utexas.edu/~moore/best-ideas/mjrty/index.html</a></p> |
3,909,784 | How do I find a particular value in an array and return its index? | <p>Pseudo Code:</p>
<pre><code>int arr[ 5 ] = { 4, 1, 3, 2, 6 }, x;
x = find(3).arr ;
</code></pre>
<p>x would then return 2. </p> | 3,909,788 | 9 | 3 | null | 2010-10-11 20:40:07.09 UTC | 9 | 2022-05-09 12:09:38.023 UTC | 2014-06-26 13:47:48.947 UTC | null | 351,716 | null | 433,417 | null | 1 | 26 | c++|arrays | 158,685 | <p>The syntax you have there for your function doesn't make sense (why would the return value have a member called <code>arr</code>?).</p>
<p>To find the index, use <code>std::distance</code> and <code>std::find</code> from the <code><algorithm></code> header.</p>
<pre><code>int x = std::distance(arr, std::find(arr, arr + 5, 3));
</code></pre>
<p>Or you can make it into a more generic function:</p>
<pre><code>template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
size_t i = 0;
while (first != last && *first != x)
++first, ++i;
return i;
}
</code></pre>
<p>Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.</p>
<p>In your case, you would use it like so:</p>
<pre><code>size_t x = index_of(arr, arr + 5, 3);
</code></pre> |
3,284,185 | Get Pixel color of UIImage | <p>How can I get the RGB value of a particular pixel in a UIImage?</p> | 3,284,234 | 9 | 0 | null | 2010-07-19 19:10:33.143 UTC | 40 | 2022-08-09 04:33:19.547 UTC | 2010-07-19 19:14:09.253 UTC | null | 21,234 | null | 167,586 | null | 1 | 67 | iphone|uiimage|rgb|pixel | 70,069 | <p>You can't access the raw data directly, but by getting the CGImage of this image you can access it. here is a link to another question that answers your question and others you might have regarding detailed image manipulation : <a href="https://stackoverflow.com/questions/448125/how-to-get-pixel-data-from-a-uiimage-cocoa-touch-or-cgimage-core-graphics">CGImage</a></p> |
3,859,958 | CodeIgniter unable to send email using PHP mail() | <p>I'm trying to send an e-mail with Codeigniter like this:</p>
<pre><code>$this->load->library('email');
$this->email->from("[email protected]");
$this->email->reply_to("[email protected]");
$this->email->to("[email protected]");
$this->email->subject("Test mail");
$this->email->message("Email body");
$this->email->set_alt_message("Email body txt");
$this->email->send();
</code></pre>
<p>and I got this on the email debugger: Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.</p>
<p>If I do e simple PHP mail() function with the same addresses, it works but when I use CodeIgniter it gives me the error. So why would it work with simple mail() but not with CodeIgniter ? Any ideas ?</p>
<p>Thanks.</p> | 3,860,218 | 12 | 2 | null | 2010-10-04 23:41:46.847 UTC | 8 | 2020-04-28 04:47:26.78 UTC | null | null | null | null | 56,409 | null | 1 | 19 | email|codeigniter | 80,965 | <p>Do you have an email.php file in your config folder? Maybe there's a problem with your configuration in there.</p> |
3,983,406 | Delete newline in Vim | <p>Is there a way to delete the newline at the end of a line in Vim, so that the next line is appended to the current line?</p>
<p>For example:</p>
<pre><code>Evaluator<T>():
_bestPos(){
}
</code></pre>
<p>I'd like to put this all on one line without copying lines and pasting them into the previous one. It seems like I should be able to put my cursor to the end of each line, press a key, and have the next line jump onto the same one the cursor is on.</p>
<p>End result:</p>
<pre><code>Evaluator<T>(): _bestPos(){ }
</code></pre>
<p>Is this possible in Vim?</p> | 3,983,437 | 13 | 1 | null | 2010-10-21 00:32:15.763 UTC | 86 | 2021-07-02 01:06:44.557 UTC | null | null | null | null | 247,763 | null | 1 | 321 | unix|vim|shell|ssh|vi | 238,512 | <p>If you are on the first line, pressing (upper case) <kbd>J</kbd> will join that line and the next line together, removing the newline. You can also combine this with a count, so pressing <code>3J</code> will combine all 3 lines together.</p> |
3,969,475 | javascript: pause setTimeout(); | <p>If I have an active timeout running that was set through <code>var t = setTimeout("dosomething()", 5000)</code>,</p>
<p>Is there anyway to pause and resume it?
<hr />
Is there any way to get the time remaining on the current timeout?<br>
or do I have to in a variable, when the timeout is set, store the current time, then we we pause, get the difference between now and then?</p> | 3,969,760 | 20 | 1 | null | 2010-10-19 14:36:20.98 UTC | 86 | 2022-08-03 11:56:57.993 UTC | 2010-10-19 14:45:43.657 UTC | null | 383,759 | null | 383,759 | null | 1 | 135 | javascript|timeout | 134,730 | <p>You could wrap <code>window.setTimeout</code> like this, which I think is similar to what you were suggesting in the question:</p>
<pre><code>var Timer = function(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
timerId = null;
remaining -= Date.now() - start;
};
this.resume = function() {
if (timerId) {
return;
}
start = Date.now();
timerId = window.setTimeout(callback, remaining);
};
this.resume();
};
var timer = new Timer(function() {
alert("Done!");
}, 1000);
timer.pause();
// Do some stuff...
timer.resume();
</code></pre> |
8,118,964 | How to convert an integer to an array in PHP? | <p>What would be the most simple way to convert an integer to an array of numbers?</p>
<p>Example:</p>
<p><code>2468</code> should result in <code>array(2,4,6,8)</code>.</p> | 8,118,995 | 4 | 0 | null | 2011-11-14 08:28:45.883 UTC | 2 | 2013-08-30 03:45:33.82 UTC | 2012-10-21 14:17:50.803 UTC | null | 367,456 | null | 864,754 | null | 1 | 16 | php|arrays | 49,584 | <p>You can use <a href="http://php.net/str_split"><code>str_split</code></a> and <a href="http://php.net/intval"><code>intval</code></a>:</p>
<pre><code>$number = 2468;
$array = array_map('intval', str_split($number));
var_dump($array);
</code></pre>
<p>Which will give the following output:</p>
<pre><code>array(4) {
[0] => int(2)
[1] => int(4)
[2] => int(6)
[3] => int(8)
}
</code></pre>
<p><a href="http://codepad.org/HKAF6ZXR">Demo</a></p> |
8,181,114 | Uploading HTTP progress tracking | <p>I've got WPF application I'm writing that posts files to one of social networks.
Upload itself working just fine, but I'd like to provide some indication of how far along I am with the uploading.</p>
<p>I tried a bunch of ways to do this:</p>
<p>1) HttpWebRequest.GetStream method:</p>
<pre><code>using (
var FS = File.Open(
localFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
long len = FS.Length;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
request.ContentType = "multipart/form-data; boundary=--AaB03x";
//predata and postdata is two byte[] arrays, that contains
//strings for MIME file upload (defined above and is not important)
request.ContentLength = predata.Length + FS.Length + postdata.Length;
request.AllowWriteStreamBuffering = false;
using (var reqStream = request.GetRequestStream())
{
reqStream.Write(predata, 0, predata.Length);
int bytesRead = 0;
int totalRead = 0;
do
{
bytesRead = FS.Read(fileData, 0, MaxContentSize);
totalRead += bytesRead;
reqStream.Write(fileData, 0, bytesRead);
reqStream.Flush(); //trying with and without this
//this part will show progress in percents
sop.prct = (int) ((100*totalRead)/len);
} while (bytesRead > 0);
reqStream.Write(postdata, 0, postdata.Length);
}
HttpWebResponse responce = (HttpWebResponse) request.GetResponse();
using (var respStream = responce.GetResponseStream())
{
//do things
}
}
</code></pre>
<p>2) WebClient way (much shorter):</p>
<pre><code>void UploadFile (url, localFilePath)
{
...
WebClient client = new WebClient();
client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadPartDone);
client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadComplete);
client.UploadFileAsync(new Uri(url), localFilePath);
done.WaitOne();
//do things with responce, received from UploadComplete
JavaScriptSerializer jssSer = new JavaScriptSerializer();
return jssSer.Deserialize<UniversalJSONAnswer>(utf8.GetString(UploadFileResponce));
//so on...
...
}
void UploadComplete(object sender, UploadFileCompletedEventArgs e)
{
UploadFileResponce=e.Result;
done.Set();
}
void UploadPartDone(object sender, UploadProgressChangedEventArgs e)
{
//this part expected to show progress
sop.prct=(int)(100*e.BytesSent/e.TotalBytesToSend);
}
</code></pre>
<p>3) Even TcpClient way:</p>
<pre><code>using (
var FS = File.Open(
localFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
long len = FS.Length;
long totalRead = 0;
using (var client = new TcpClient(urli.Host, urli.Port))
{
using (var clearstream = client.GetStream())
{
using (var writer = new StreamWriter(clearstream))
using (var reader = new StreamReader(clearstream))
{
//set progress to 0
sop.prct = 0;
// Send request headers
writer.WriteLine("POST " + urli.AbsoluteUri + " HTTP/1.1");
writer.WriteLine("Content-Type: multipart/form-data; boundary=--AaB03x");
writer.WriteLine("Host: " + urli.Host);
writer.WriteLine("Content-Length: " + (predata.Length + len + postdata.Length).ToString());
writer.WriteLine();
//some data for MIME
writer.Write(utf8.GetString(predata));
writer.Flush();
int bytesRead;
do
{
bytesRead = FS.Read(fileData, 0, MaxContentSize);
totalRead += bytesRead;
writer.BaseStream.Write(fileData, 0, bytesRead);
writer.BaseStream.Flush();
sop.prct = (int) ((100*totalRead)/len);
} while (bytesRead > 0)
writer.Write(utf8.GetString(postdata));
writer.Flush();
//read line of response and do other thigs...
respStr = reader.ReadLine();
...
}
}
}
}
</code></pre>
<p>In all cases the file was successfully sent to the server.
But always progress looks like this: for a few seconds it runs from 0 to 100 and then waits until file actually uploading (about 5 minutes - file is 400MB).</p>
<p>So I think the data from a file is buffered somewhere and I'm tracking not uploading, but buffering data. And then must wait until it's uploaded.</p>
<p>My questions are:</p>
<p>1) Is there any way to track <em>actual</em> uploading data? That the method Stream.Write() or Flush() (which as I read somewhere, does not work for NetworkStream) did not return until it receives confirmation from the server that the TCP packets received.</p>
<p>2) Or can I deny buffering (AllowWriteStreamBUffering for HttpWebRequest doesn't work)?</p>
<p>3) And does it make sense to go further "down" and try with Sockets?</p>
<p><strong>updated:</strong></p>
<p>To avoid any doubts in the way of progress displaying on UI, I rewrote the code to log a file.
so, here is code:</p>
<pre><code>using (var LogStream=File.Open("C:\\123.txt",FileMode.Create,FileAccess.Write,FileShare.Read))
using (var LogWriter=new StreamWriter(LogStream))
using (var FS = File.Open(localFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
long len = FS.Length;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Timeout = 7200000; //2 hour timeout
request.Method = "POST";
request.ProtocolVersion = HttpVersion.Version11;
request.ContentType = "multipart/form-data; boundary=--AaB03x";
//predata and postdata is two byte[] arrays, that contains
//strings for MIME file upload (defined above and is not important)
request.ContentLength = predata.Length + FS.Length + postdata.Length;
request.AllowWriteStreamBuffering = false;
LogWriter.WriteLine(DateTime.Now.ToString("o") + " Start write into request stream. ");
using (var reqStream = request.GetRequestStream())
{
reqStream.Write(predata, 0, predata.Length);
int bytesRead = 0;
int totalRead = 0;
do
{
bytesRead = FS.Read(fileData, 0, MaxContentSize);
totalRead += bytesRead;
reqStream.Write(fileData, 0, bytesRead);
reqStream.Flush(); //trying with and without this
//sop.prct = (int) ((100*totalRead)/len); //this part will show progress in percents
LogWriter.WriteLine(DateTime.Now.ToString("o") + " totalRead= " + totalRead.ToString() + " / " + len.ToString());
} while (bytesRead > 0);
reqStream.Write(postdata, 0, postdata.Length);
}
LogWriter.WriteLine(DateTime.Now.ToString("o") + " All sent!!! Waiting for responce... ");
LogWriter.Flush();
HttpWebResponse responce = (HttpWebResponse) request.GetResponse();
LogWriter.WriteLine(DateTime.Now.ToString("o") + " Responce received! ");
using (var respStream = responce.GetResponseStream())
{
if (respStream == null) return null;
using (var streamReader = new StreamReader(respStream))
{
string resp = streamReader.ReadToEnd();
JavaScriptSerializer jssSer = new JavaScriptSerializer();
return jssSer.Deserialize<UniversalJSONAnswer>(resp);
}
}
}
</code></pre>
<p>and here is result (I cut the middle):</p>
<pre><code>2011-11-19T22:00:54.5964408+04:00 Start write into request stream.
2011-11-19T22:00:54.6404433+04:00 totalRead= 1048576 / 410746880
2011-11-19T22:00:54.6424434+04:00 totalRead= 2097152 / 410746880
2011-11-19T22:00:54.6434435+04:00 totalRead= 3145728 / 410746880
2011-11-19T22:00:54.6454436+04:00 totalRead= 4194304 / 410746880
2011-11-19T22:00:54.6464437+04:00 totalRead= 5242880 / 410746880
2011-11-19T22:00:54.6494438+04:00 totalRead= 6291456 / 410746880
.......
2011-11-19T22:00:55.3434835+04:00 totalRead= 408944640 / 410746880
2011-11-19T22:00:55.3434835+04:00 totalRead= 409993216 / 410746880
2011-11-19T22:00:55.3464837+04:00 totalRead= 410746880 / 410746880
2011-11-19T22:00:55.3464837+04:00 totalRead= 410746880 / 410746880
2011-11-19T22:00:55.3464837+04:00 All sent!!! Waiting for responce...
2011-11-19T22:07:23.0616597+04:00 Responce received!
</code></pre>
<p>as you can see program thinks that it uploaded ~400MB for about 2 seconds. And after 7 minutes file actually uploads and I receive responce.</p>
<p><strong>updated again:</strong></p>
<p>Seems to this is happening under WIndows 7 (not shure about x64 or x86).
When I run my code uder XP everything works perfectly and progress is shown absolute correctly</p> | 13,769,435 | 7 | 0 | null | 2011-11-18 10:40:30.043 UTC | 13 | 2015-01-19 19:19:18.217 UTC | 2011-12-14 23:52:58.32 UTC | user47589 | null | null | 1,053,502 | null | 1 | 16 | c#|file-upload|progress | 14,093 | <p>it's more than year since this question was posted, but I think my post can be usefull for someone. </p>
<p>I had the same problem with showing progress and it behaved exactly like you described. So i decided to use HttpClient which shows upload progress correctly. Then I've encountered interesting bug - when I had Fiddler launched HttpClient started to show its upload progress in unexpected way like in WebClient/HttpWebRequest above so I thinked maybe that was a problem of why WebClient showed upload progres not correctly (I think I had it launched). So I tried with WebClient again (without fiddler-like apps launched) and all works as it should, upload progress has correct values. I have tested in on several PC with win7 and XP and in all cases progress was showing correctly. </p>
<p>So, I think that such program like Fiddler (probably not only a fiddler) has some affect on how WebClient and other .net classes shows upload progress. </p>
<p>this discussion approves it: </p>
<p><a href="https://stackoverflow.com/questions/4801189/httpwebrequest-doesnt-work-except-when-fiddler-is-running">HttpWebRequest doesn't work except when fiddler is running</a> </p> |
7,794,572 | Windows Service to Azure? | <p>I've written a Windows Service in C# that does a whole bunch of background admin tasks on the database. Now my customer wants to migrate the whole shebang to Azure. I know next to nothing about Azure, and my customer says you can't run a Windows Service on Azure. I've googled for this topic and come out with a few very specific case studies of what somebody did to move their Windows Service to Azure, assuming a fairly high level of understanding of how Azure works, but no general articles about whether or not Windows Services can run under Azure, or what to do to adapt them. </p>
<p>I would really like to see a clear answer and explanation to the first question (can you run a Windows Service under Azure?), and if the answer is no, I'd love to find a step-by-step guide for converting a Windows Service to something Azure-compatible.</p>
<p>Thanks!</p> | 7,794,662 | 7 | 0 | null | 2011-10-17 13:36:24.583 UTC | 8 | 2016-07-27 15:48:53.413 UTC | 2011-10-17 13:42:23.157 UTC | null | 7,850 | null | 7,850 | null | 1 | 41 | c#|windows-services|azure | 30,887 | <p>Yes you can do that - for a simple walkthrough see <a href="http://blogs.msdn.com/b/mwasham/archive/2011/03/30/migrating-a-windows-service-to-windows-azure.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/b/mwasham/archive/2011/03/30/migrating-a-windows-service-to-windows-azure.aspx</a></p>
<p>Other links with relevant information:<br/></p>
<ul>
<li><a href="https://stackoverflow.com/questions/7032934/getting-a-service-to-run-inside-of-an-azure-worker-role/7059424#7059424">Getting a Service to Run Inside of an Azure Worker Role</a></li>
<li><a href="http://www.codeproject.com/KB/azure/WCFWorkerRole.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/azure/WCFWorkerRole.aspx</a></li>
</ul> |
4,418,279 | Regex remove special characters | <p>We need a C# function which will remove all special characters from a string.</p>
<p>Also, is it possible to change "George's" to "George" (remove both single quote and character s)?</p> | 4,418,510 | 4 | 2 | null | 2010-12-11 18:34:52.58 UTC | 1 | 2017-02-12 08:27:52.443 UTC | 2017-02-12 08:27:52.443 UTC | null | 4,401,293 | null | 374,760 | null | 1 | 19 | c#|regex | 62,757 | <p>This method will removed everything but letters, numbers and spaces. It will also remove any ' or " followed by the character s. </p>
<pre><code>public static string RemoveSpecialCharacters(string input)
{
Regex r = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
return r.Replace(input, String.Empty);
}
</code></pre> |
4,834,227 | Invoke Command When "ENTER" Key Is Pressed In XAML | <p>I want to invoke a command when ENTER is pressed in a <code>TextBox</code>. Consider the following XAML:</p>
<pre><code><UserControl
...
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
...>
...
<TextBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyUp">
<i:InvokeCommandAction Command="{Binding MyCommand}"
CommandParameter="{Binding Text}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
...
</UserControl>
</code></pre>
<p>and that MyCommand is as follows:</p>
<pre><code>public ICommand MyCommand {
get { return new DelegateCommand<string>(MyCommandExecute); }
}
private void MyCommandExecute(string s) { ... }
</code></pre>
<p>With the above, my command is invoked for every key press. How can I restrict the command to only invoke when the ENTER key is pressed?</p>
<p>I understand that with Expression Blend I can use Conditions but those seem to be restricted to elements and can't consider event arguments.</p>
<p>I have also come across <a href="http://slex.codeplex.com/">SLEX</a> which offers its own <code>InvokeCommandAction</code> implementation that is built on top of the <code>Systems.Windows.Interactivity</code> implementation and can do what I need. Another consideration is to write my own trigger, but I'm hoping there's a way to do it without using external toolkits. </p> | 5,267,495 | 5 | 0 | null | 2011-01-29 00:10:11.837 UTC | 10 | 2018-02-22 08:19:53.943 UTC | 2011-01-29 00:25:21.3 UTC | null | 520,942 | null | 520,942 | null | 1 | 15 | silverlight|xaml|eventtrigger|invoke-command | 23,184 | <p>I like scottrudy's approach (to which I've given a +1) with the custom triggers approach as it stays true to my initial approach. I'm including a modified version of it below to use dependency properties instead of reflection info so that it's possible to bind directly to the ICommand. I'm also including an approach using attached properties to avoid using <code>System.Windows.Interactivity</code> if desired. The caveat to the latter approach is that you lose the feature of multiple invokations from an event, but you can apply it more generally.</p>
<hr>
<p><strong>Custom Triggers Approach</strong></p>
<p>ExecuteCommandAction.cs</p>
<pre><code>public class ExecuteCommandAction : TriggerAction<DependencyObject> {
#region Properties
public ICommand Command {
get { return (ICommand)base.GetValue(CommandProperty); }
set { base.SetValue(CommandProperty, value); }
}
public static ICommand GetCommand(DependencyObject obj) {
return (ICommand)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, ICommand value) {
obj.SetValue(CommandProperty, value);
}
// We use a DependencyProperty so we can bind commands directly rather
// than have to use reflection info to find them
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(ExecuteCommandAction), null);
#endregion Properties
protected override void Invoke(object parameter) {
ICommand command = Command ?? GetCommand(AssociatedObject);
if (command != null && command.CanExecute(parameter)) {
command.Execute(parameter);
}
}
}
</code></pre>
<p>TextBoxEnterKeyTrigger.cs</p>
<pre><code>public class TextBoxEnterKeyTrigger : TriggerBase<UIElement> {
protected override void OnAttached() {
base.OnAttached();
TextBox textBox = this.AssociatedObject as TextBox;
if (textBox != null) {
this.AssociatedObject.KeyUp += new System.Windows.Input.KeyEventHandler(AssociatedObject_KeyUp);
}
else {
throw new InvalidOperationException("This behavior only works with TextBoxes");
}
}
protected override void OnDetaching() {
base.OnDetaching();
AssociatedObject.KeyUp -= new KeyEventHandler(AssociatedObject_KeyUp);
}
private void AssociatedObject_KeyUp(object sender, KeyEventArgs e) {
if (e.Key == Key.Enter) {
TextBox textBox = AssociatedObject as TextBox;
//This checks for an mvvm style binding and updates the source before invoking the actions.
BindingExpression expression = textBox.GetBindingExpression(TextBox.TextProperty);
if (expression != null)
expression.UpdateSource();
InvokeActions(textBox.Text);
}
}
}
</code></pre>
<p>MyUserControl.xaml</p>
<pre><code><UserControl
...
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:b="clr-namespace:MyNameSpace.Interactivity"
...
<TextBox>
<i:Interaction.Triggers>
<b:TextBoxEnterKeyTrigger>
<b:ExecuteCommandAction Command="{Binding MyCommand}" />
</b:TextBoxEnterKeyTrigger>
</i:Interaction.Triggers>
</TextBox>
...
</UserControl>
</code></pre>
<hr>
<p><strong>Attached Properties Approach</strong></p>
<p>EnterKeyDown.cs</p>
<pre><code>public sealed class EnterKeyDown {
#region Properties
#region Command
public static ICommand GetCommand(DependencyObject obj) {
return (ICommand)obj.GetValue(CommandProperty);
}
public static void SetCommand(DependencyObject obj, ICommand value) {
obj.SetValue(CommandProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(EnterKeyDown),
new PropertyMetadata(null, OnCommandChanged));
#endregion Command
#region CommandArgument
public static object GetCommandArgument(DependencyObject obj) {
return (object)obj.GetValue(CommandArgumentProperty);
}
public static void SetCommandArgument(DependencyObject obj, object value) {
obj.SetValue(CommandArgumentProperty, value);
}
public static readonly DependencyProperty CommandArgumentProperty =
DependencyProperty.RegisterAttached("CommandArgument", typeof(object), typeof(EnterKeyDown),
new PropertyMetadata(null, OnCommandArgumentChanged));
#endregion CommandArgument
#region HasCommandArgument
private static bool GetHasCommandArgument(DependencyObject obj) {
return (bool)obj.GetValue(HasCommandArgumentProperty);
}
private static void SetHasCommandArgument(DependencyObject obj, bool value) {
obj.SetValue(HasCommandArgumentProperty, value);
}
private static readonly DependencyProperty HasCommandArgumentProperty =
DependencyProperty.RegisterAttached("HasCommandArgument", typeof(bool), typeof(EnterKeyDown),
new PropertyMetadata(false));
#endregion HasCommandArgument
#endregion Propreties
#region Event Handling
private static void OnCommandArgumentChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) {
SetHasCommandArgument(o, true);
}
private static void OnCommandChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) {
FrameworkElement element = o as FrameworkElement;
if (element != null) {
if (e.NewValue == null) {
element.KeyDown -= new KeyEventHandler(FrameworkElement_KeyDown);
}
else if (e.OldValue == null) {
element.KeyDown += new KeyEventHandler(FrameworkElement_KeyDown);
}
}
}
private static void FrameworkElement_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Enter) {
DependencyObject o = sender as DependencyObject;
ICommand command = GetCommand(sender as DependencyObject);
FrameworkElement element = e.OriginalSource as FrameworkElement;
if (element != null) {
// If the command argument has been explicitly set (even to NULL)
if (GetHasCommandArgument(o)) {
object commandArgument = GetCommandArgument(o);
// Execute the command
if (command.CanExecute(commandArgument)) {
command.Execute(commandArgument);
}
}
else if (command.CanExecute(element.DataContext)) {
command.Execute(element.DataContext);
}
}
}
}
#endregion
}
</code></pre>
<p>MyUserControl.xaml</p>
<pre><code><UserControl
...
xmlns:b="clr-namespace:MyNameSpace.Interactivity"
...
<TextBox b:EnterKeyDown.Command="{Binding AddNewDetailCommand}"
b:EnterKeyDown.CommandArgument="{Binding Path=Text,RelativeSource={RelativeSource Self}}" />
...
</UserControl>
</code></pre> |
4,521,660 | How do I use hasClass to detect if a class is NOT the class I want? | <p>How do I use hasClass so it works as doesNotHaveClass? In other words, rather than looking to see if it is a specified class, looking to see if it is NOT a specified class. Can I use an exclamation point or something like that?</p> | 4,521,680 | 5 | 0 | null | 2010-12-23 19:01:56.623 UTC | 4 | 2015-04-13 11:27:00.15 UTC | 2012-07-06 02:39:46.283 UTC | null | 106,224 | null | 537,082 | null | 1 | 19 | javascript|jquery | 56,645 | <p>Yes, you can.</p>
<pre><code>if (!$('element').hasClass('do-not-want')) {
// This element does not have the .do-not-want class
}
</code></pre> |
4,653,768 | overwriting file in ziparchive | <p>I have <code>archive.zip</code> with two files: <code>hello.txt</code> and <code>world.txt</code></p>
<p>I want to overwrite <code>hello.txt</code> file with new one with that code:</p>
<pre><code>import zipfile
z = zipfile.ZipFile('archive.zip','a')
z.write('hello.txt')
z.close()
</code></pre>
<p>but it won't overwrite file, somehow it creates another instance of <code>hello.txt</code> — take a look at winzip screenshot: </p>
<p><img src="https://i.stack.imgur.com/KCJjE.png" alt="alt text"></p>
<p>Since there is no smth like <code>zipfile.remove()</code>, what's the best way to handle this problem? </p> | 4,653,863 | 5 | 1 | null | 2011-01-11 03:00:23.583 UTC | 14 | 2022-09-05 16:05:03.097 UTC | 2011-01-11 03:06:21.723 UTC | null | 277,262 | null | 277,262 | null | 1 | 32 | python|ziparchive | 23,180 | <p>There's no way to do that with python zipfile module. You have to create a new zip file and recompress everything again from the first file, plus the new modified file.</p>
<p>Below is some code to do just that. But note that it isn't efficient, since it decompresses and then recompresses all data.</p>
<pre><code>import tempfile
import zipfile
import shutil
import os
def remove_from_zip(zipfname, *filenames):
tempdir = tempfile.mkdtemp()
try:
tempname = os.path.join(tempdir, 'new.zip')
with zipfile.ZipFile(zipfname, 'r') as zipread:
with zipfile.ZipFile(tempname, 'w') as zipwrite:
for item in zipread.infolist():
if item.filename not in filenames:
data = zipread.read(item.filename)
zipwrite.writestr(item, data)
shutil.move(tempname, zipfname)
finally:
shutil.rmtree(tempdir)
</code></pre>
<p>Usage:</p>
<pre><code>remove_from_zip('archive.zip', 'hello.txt')
with zipfile.ZipFile('archive.zip', 'a') as z:
z.write('hello.txt')
</code></pre> |
4,235,445 | get started with regular expression | <p>I’m always afraid whenever I see any regular expression. I think it very difficult to understand. But fear is not the solution. I’ve decided to start learning regex, so can someone advise me how I can just start? And if there’s is any easy tutorial?</p> | 4,235,922 | 8 | 5 | null | 2010-11-20 22:55:25.69 UTC | 12 | 2013-08-14 12:25:43.377 UTC | 2013-08-14 12:25:43.377 UTC | user1228 | null | null | 2,067,571 | null | 1 | 10 | regex | 1,695 | <h2>☝ Getting Started with /Regexes/</h2>
<p>Regular expressions are a form of <em>declarative programming</em>. If you are used to imperative, functional, or object-oriented programming, then they are a very different way of thinking. It’s a rules-based approach with subtle backtracking issues. I daresay a background in Prolog might actually do you some good with these, which certainly isn’t something I commonly advise.</p>
<p>Normally I would just have people play around with the <code>grep</code> command from their shell, then advance to using regexes for searching and replacing in their editor.</p>
<p>But I’m guessing you aren’t coming from a Unix background, because if you were, you would have come across regexes all over, from the very most basic <code>grep</code> command to pattern-matching in the <code>vi</code> or <code>emacs</code> editors. You can look at the <code>grep</code> manpage by typing </p>
<pre><code>% man grep
</code></pre>
<p>on your <a href="http://www.openbsd.org/cgi-bin/man.cgi?query=grep&apropos=0&sektion=0&manpath=OpenBSD+Current&arch=i386&format=html" rel="nofollow noreferrer">BSD</a>,
<a href="http://linux.die.net/man/1/grep" rel="nofollow noreferrer">Linux</a>,
<a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/grep.1.html" rel="nofollow noreferrer">Apple</a>, or <a href="http://manpages.unixforum.co.uk/man-pages/unix/solaris-10-11_06/1/grep-man-page.html" rel="nofollow noreferrer">Sun</a> systems — just to name a few.</p>
<p> ☹ <em>¡ʇɟoƨoɹɔᴉƜ ʇnoqɐ əɯ ʞƨɐ ʇ ̦uop əƨɐəld ʇƨnɾ</em> ☹</p>
<hr>
<h2>☟ (?: Book Learnin’? )</h2>
<p>If you ran into regular expresions at school or university, it was probably in the context of automata theory. They come up when discussing <a href="http://en.wikipedia.org/wiki/Regular_language" rel="nofollow noreferrer">regular languages</a>. If you have suffered through such classes, you may remember that regular expressions are the <em>user-friendly face</em> to messy finite automata. What they probably did <em>not</em> teach you, however, is that outside of the ivory tower, the regular expressions people actually use to in the real world are far, far behind "regular" in the rarefied, theoretical, and highly <em>irregular</em> sense of that otherwise commonplace word. This means that the modern regular expressions — call them patterns if you prefer — can do much more than the traditional regular
expressions taught in computer science classes. There just isn’t any REGULAR left in modern regular expressions outside the classroom, but this is a good thing.</p>
<p>I say “modern”, but in fact regular expressions haven’t been regular since Ken Thompson first put back references into his backtracking NFA, back when he was famousluy proving NFA–DFA equivalence. So unless you actually are using a DFA engine, it might be best to just forget any book-learnin’ nonsense about REGULARness of regexes. It just doesn’t apply to the way we really use them every day in the real world.</p>
<p><em>Modern</em> regular expressions allow for much more than just back references though, as you will find once you delve into them. They’re their own wonderful world, even if that world is a bit surreal at times. They can let you substitute for pages and pages of code in just one line. They can also make you lose hair over their crazy behavior. Sometimes they make your computer seem like it’s hung, because it’s actually working very hard in a race between it and the heat-death of the universe in some awful O(2ⁿ) algorithm, or even worse. It can easily be much worse, actually. That’s what having this sort of power in your hands can do. There are no training wheel or slow lane. Regexes are a power tool <em>par excellence</em>.</p>
<hr>
<h2>/☕✷⅋⋙$⚣™‹ª∞¶⌘̤℈⁑‽#♬˘$π❧/</h2>
<p>
</p>
<p>Just one more thing before I give you a big list of helpful references. As I’ve <a href="https://stackoverflow.com/questions/4231382/regular-expression-pattern-not-matching-anywhere-in-string/4234491#4234491">already said today elsewhere</a>, regexes do not have to be ugly, and they do not have to be hard. <strong>REMEMBER: If you create ugly regexes, it is only a reflection on <em>you</em>, not on <em>them</em>.</strong></p>
<p>That’s absolutely <strong>no</strong> excuse for creating regexes that are hard to read. Oh, there’s plenty like that out there all right, but they shouldn’t be and they needn’t be. Even though regexes are (for the most part( a form of declarative programming, all the software engineering techniques that one uses in other forms of programming ̲s̲t̲i̲l̲l̲ ̲a̲p̲p̲l̲y̲ ̲h̲e̲r̲e̲!</p>
<p>A regex should never look like a dense row of punctuation that’s impossible to decipher. <em>Any</em> language would be a disaster if you removed all the alphabetical identifiers, removed all whitespace and indentation, removed all comments, and removed every last trace of top-down programming. So of course they look like cr@p if you do that. Don’t <em>do</em> that!</p>
<p>So use <em>all</em> of those basic tools, including aesthetically pleasing code layout, careful problem decomposition, named subroutines, decoupling the declaration from the execution (including ordering!), unit testing, plus all the rest, whenever you’re creating regexes. These are all critical steps in <a href="https://stackoverflow.com/questions/764247/why-are-regular-expressions-so-controversial/4053506#4053506">making your patterns <em>maintainable</em></a>.</p>
<p>It’s one thing to write <code>/(.)\1/</code>, but quite another to write something like <code>mǁ☕⅋⚣⁑™∞¶⌘℈‽#♬❧ǁ</code>. Those are regexes from the Dark Ages: don’t just reject them: burn them at the stake! It’s <em>programming</em>, after all, not line-noise or golf! </p>
<hr>
<h2>☞ Regex References</h2>
<ol>
<li><p>The <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="nofollow noreferrer">Wikipedia page</a> on regular expressions is a decent enough overview.</p></li>
<li><p>IBM has a <a href="http://www.ibm.com/developerworks/aix/library/au-speakingunix9/index.html" rel="nofollow noreferrer">nice introduction</a> to regexes in their <em>Speaking Unix</em> series. </p></li>
<li><p>Russ Cox has a very nice list of <a href="http://swtch.com/~rsc/regexp/" rel="nofollow noreferrer">classic regular expressions references</a>. You might want to check out the original <a href="http://perldoc.perl.org/perlre.html#Version-8-Regular-Expressions" rel="nofollow noreferrer">Version 8 regular expressions</a>, here found in a Perl manpage, but these were the original, most basic patterns that everybody grew up with back in olden days.</p></li>
<li><p><a href="http://regex.info/" rel="nofollow noreferrer"> <em>Mastering Regular Expressions</em> </a> from O’Reilly, by Jeffrey Friedl.</p></li>
<li><p><a href="http://www.regular-expressions.info/" rel="nofollow noreferrer">Jan Goyvaerts’s <em>regular-expressions.info</em> site</a> and his <a href="http://oreilly.com/catalog/9780596520694" rel="nofollow noreferrer"> <em>Regular Expression Cookbook</em></a>, also from O’Reilly.</p></li>
<li><p>I’m a native speaker of Perl, so let me say four words about it. Chapter 5 of the <a href="http://oreilly.com/catalog/9780596003135" rel="nofollow noreferrer"><em>Perl Cookbook</em></a> and Chapter 6 of <a href="http://oreilly.com/catalog/9780596000271" rel="nofollow noreferrer"><em>Programming Perl</em></a>, both somewhat embarrassingly by <a href="http://en.wikipedia.org/wiki/Tom_Christiansen" rel="nofollow noreferrer">yours truly</a> <em>et alios</em>, also from O’Reilly, are devoted to regular expressions in Perl. Perl was the language that originated most regex features found in modern regular expressions, and it continues to lead the pack. Perl’s Unicode support for regexes is especially rich and remarkably simple to use — in comparison with other languages’. You can download all the code examples from those two books from the O’Reilly site, or see the next item. The <a href="http://perldoc.perl.org/" rel="nofollow noreferrer">perldoc.org site</a> has quite a bit on pattern matching, including the <a href="http://perldoc.perl.org/perlre.html" rel="nofollow noreferrer">perlre</a> and <a href="http://perldoc.perl.org/perluniprops.html" rel="nofollow noreferrer">perluniprops</a> manpages, just to take a couple of starting points.</p></li>
<li><p>Apropos the <em>Perl Cookbook</em>, the <a href="http://pleac.sourceforge.net/" rel="nofollow noreferrer">PLEAC</a> project has reïmplemented the <em>Perl Cookbook</em> code in a dizzying number of diverse languages, including ada, common lisp, groovy, guile, haskell, java, merd, ocaml, php, pike, python, rexx, ruby, and tcl. If you look at what each language does for their equivalent of <em>PCB</em>’s regex chapter, you will learn a <em>tremendously huge amount</em> about how that language deals with regular expressions. It’s a marvellous resource and quite an eye-opener, even if some up the solutions are, um, supoptimal.</p></li>
<li><p><a href="http://www.regular-expressions.info/javabook.html" rel="nofollow noreferrer"><em>Java Regular Expressions</em></a> by Mehran Habibi from Apress. It’s certainly better than trying to figure anything out by reading <a href="http://download.java.net/jdk7/docs/api/java/util/regex/Pattern.html" rel="nofollow noreferrer">Sun’s documentation on the Pattern class</a>. Java is probably the worst possible language for learning regexes in; it is very clumsy and often completely stupid. I speak from painful personal experience, not from ignorance, and <a href="http://www.google.com/codesearch/p?hl=en#4vlodpF_ctc/nexus/nexus-utils/src/main/java/org/sonatype/nexus/util/Inflector.java&q=%66%75%63%6b%69%6e%67%20lang%3ajava&sa=N&cd=225&ct=rc" rel="nofollow noreferrer">I am hardly alone</a> in this appraisal. If you have to use a JVM language, I recommend <a href="http://groovy.codehaus.org/" rel="nofollow noreferrer">Groovy</a> or perhaps <a href="http://www.scala-lang.org/api/current/scala/util/matching/Regex.html" rel="nofollow noreferrer">Scala</a>. Unfortunately, both are based on the standard Java pattern matching classes, so share their inadequacies.</p></li>
<li><p>If you need Unicode and you’re using Java or C⁺⁺ instead of Perl, then I recommend looking into the <a href="http://site.icu-project.org/" rel="nofollow noreferrer">ICU library</a>. They handle Unicode in Java much better than Sun does, but it still feels too much like assembler for my tastes. Perl and Java appear to have the best support for Unicode and multiple encodings. Java is still kinda warty, but other languages often have this even worse. Be warned that languages with regexes bolted on the site are always clumsier to use them in than those that don’t. </p></li>
<li><p>If you’re using C, then I would probably skip over the <a href="http://www.openbsd.org/cgi-bin/man.cgi?query=regex&apropos=0&sektion=0&manpath=OpenBSD+Current&arch=i386&format=html" rel="nofollow noreferrer">system-supplied regex library</a> and jump right into <a href="http://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions" rel="nofollow noreferrer">PCRE by Phil Hazel</a>. A bonus is that PCRE <em>can</em> be built to handle Unicode reasonably well. It is also the basic regex library used by several other languages and tools, including PHP.</p></li>
</ol> |
4,554,031 | When have you used C++ 'mutable' keyword? | <p>When have you used C++ <code>mutable</code> keyword? and why? I don't think I have ever had to use that keyword. I understand it is used for things such as caching (or perhaps memorization) but in what class and condition have you ever needed to use it in?</p> | 4,554,077 | 11 | 7 | null | 2010-12-29 12:21:23.98 UTC | 17 | 2019-08-16 07:23:00.88 UTC | 2013-08-09 03:02:38.787 UTC | null | 1,009,479 | user34537 | null | null | 1 | 39 | c++ | 18,517 | <p>Occasionally I use it to mark a mutex or other thread synchronisation primitive as being mutable so that accessors/query methods, which are typically marked <code>const</code> can still lock the mutex.</p>
<p>It's also sometimes useful when you need to instrument your code for debugging or testing purposes, because instrumentation often needs to modify auxiliary data from inside query methods.</p> |
14,365,449 | jquery rotate image onclick | <p>I am trying to achieve this (90 degree rotation), but it fails without errors.
This image is within a <code><a></a></code> TAG where it has already a toggle jquery function.</p>
<pre><code><?php echo "<img src='down_arrow.png' onclick='$(this).animate({rotate: \"+=90deg\"});' />"; ?>
</code></pre> | 14,365,513 | 8 | 4 | null | 2013-01-16 18:44:40.133 UTC | 2 | 2020-12-26 18:29:46.27 UTC | null | null | null | null | 1,272,401 | null | 1 | 17 | jquery | 102,788 | <p>Consider a jQuery extension such as: <a href="https://code.google.com/p/jquery-rotate/" rel="noreferrer">jQueryRotate</a></p>
<p>It'll make the rotating inside the onclick much easier and more readable.</p> |
14,516,693 | Gradle color output | <p>I've looked this up on Google, but there doesn't seem to be any documentation on the Gradle site, or even people discussing this in forums.</p>
<p>I have Gradle installed on my Mac (10.8.2, ML) and am building a custom build.gradle script. When I call println(), I would like to make the output colored (like errors in red, info in green, etc). How do I do this in my gradle build script?</p>
<p>Here's an example of code I have so far:</p>
<pre><code>def proc = "echo `DATE`".execute()
proc.in.eachLine {line -> println line}
proc.err.eachLine {line -> println 'ERROR: ' + line}
</code></pre>
<p>On <a href="http://gradle.1045684.n5.nabble.com/Colourizing-console-output-td3073839.html" rel="noreferrer">this gradle forum</a>, they talk about various styles like normal, header, userinput, identifier, description, progressstatus, failure, info, and error, as part of the StyledTextOutput class. It looks like this is an internal class. Is there a simple way to tap into the color printing powers of Gradle/Groovy without importing a lot of packages?</p> | 14,518,474 | 6 | 1 | null | 2013-01-25 06:42:07.417 UTC | 7 | 2021-09-27 15:27:54.61 UTC | 2019-12-04 05:56:52.2 UTC | null | 487,033 | null | 695,772 | null | 1 | 32 | logging|groovy|build|gradle | 18,987 | <p>Found the answer! According to <a href="http://forums.gradle.org/gradle/topics/the_correct_way_for_a_custom_plugin_to_output_colored_styled_text_to_the_gradle_logging_system" rel="noreferrer">this gradle forum post</a>, there's no public interface for coloring the output of the logger. You are free to use the internal classes, but those may change in future versions. In the gradle script, put at the top:</p>
<p><strong>Older Gradle</strong>:</p>
<pre><code>import org.gradle.logging.StyledTextOutput;
import org.gradle.logging.StyledTextOutputFactory;
import static org.gradle.logging.StyledTextOutput.Style;
</code></pre>
<p><strong>Gradle 3.3+</strong>:</p>
<pre><code>import org.gradle.internal.logging.text.StyledTextOutput;
import org.gradle.internal.logging.text.StyledTextOutputFactory;
import static org.gradle.internal.logging.text.StyledTextOutput.Style;
</code></pre>
<p>(I still haven't figured out how to move this to the init.gradle file.) Then shortly after, define</p>
<pre><code>def out = services.get(StyledTextOutputFactory).create("blah")
</code></pre>
<p>I'm still not sure what needs to be in the create method's string (it doesn't seem to affect anything yet). Then later in your task,</p>
<pre><code>out.withStyle(Style.Info).println('colored text')
</code></pre>
<p>This should work with all the categories: normal, header, userinput, identifier, description, progressstatus, failure, info, and error. An additional step if you want to customize the color of each category, add the following to an init.gradle file in your ~/.gradle directory (or <a href="http://gradle.org/docs/current/userguide/init_scripts.html" rel="noreferrer">other options</a>):</p>
<pre><code>System.setProperty('org.gradle.color.error', 'RED')
</code></pre>
<p>and then replace the "error" category with any from the above list.</p> |
14,877,415 | Difference between typeof, __typeof and __typeof__ in Objective-C | <p>In Objective-C I often use <code>__typeof__(obj)</code> when dealing with blocks etc. Why not <code>__typeof(obj)</code> or <code>typeof(obj)</code>.</p>
<p>When to use which?</p> | 14,878,370 | 3 | 6 | null | 2013-02-14 14:48:19.723 UTC | 28 | 2019-07-30 04:50:01.59 UTC | 2019-07-30 04:50:01.59 UTC | null | 1,033,581 | null | 202,451 | null | 1 | 71 | objective-c | 31,578 | <p><code>__typeof__()</code> and <code>__typeof()</code> are compiler-specific extensions to the C language, because standard C does not include such an operator. Standard C requires compilers to prefix language extensions with a double-underscore (which is also why you should never do so for your own functions, variables, etc.)</p>
<p><code>typeof()</code> is exactly the same, but throws the underscores out the window with the understanding that every modern compiler supports it. (Actually, now that I think about it, Visual C++ might not. It does support <code>decltype()</code> though, which generally provides the same behaviour as <code>typeof()</code>.)</p>
<p>All three mean the same thing, but none are standard C so a conforming compiler may choose to make any mean something different.</p> |
2,391,401 | C++ error: Invalid use of incomplete type ... | <p>I have a small- to medium-size project that I am doing for my software engineering course this semester. I have chosen to do it in C++ (gtkmm). I am doing okay so far but I have run into a problem with circular references or the following errors:</p>
<pre><code>Login_Dialog.cpp:25: error: invalid use of incomplete type ‘struct MainWindow’
Login_Dialog.h:12: error: forward declaration of ‘struct MainWindow’
make: *** [Login_Dialog.o] Error 1
</code></pre>
<p>In short I have about 10 classes and I know in the future they are all going to need to talk to each other. I have run into one specific case so far, and I have been trying to resolve it on my own, but I am totally stuck.</p>
<p>My program has a main window class that is defined as follows:</p>
<pre><code>/*
* MainWindow.h
*/
#ifndef MAINWINDOW_H_
#define MAINWINDOW_H_
#include "includes.h"
#include "ModelDrawing.h"
#include "ViewDrawing.h"
#include "ControlerDrawing.h"
#include "ModelChat.h"
#include "ViewChat.h"
#include "ControlerChat.h"
#include "ModelQueue.h"
#include "ViewQueue.h"
#include "ControlerQueue.h"
#include "Login_Dialog.h"
#include "TCP_IP_Socket.h"
class MainWindow : public Window
{
public:
MainWindow(int type);
~MainWindow();
void on_menu_file_new_generic();
void on_menu_file_quit();
ModelDrawing* get_mdl_Draw();
ViewDrawing* get_view_Draw();
ControlerDrawing* get_cntrl_Draw();
ModelChat* get_mdl_Chat();
ViewChat* get_view_Chat();
ControlerChat* get_cntrl_Chat();
ModelQueue* get_mdl_Que();
ViewQueue* get_view_Que();
ControlerQueue* get_cntrl_Que();
Label* get_status_label();
void set_status_label(Glib::ustring label);
TCP_IP_Socket* get_socket();
private:
TCP_IP_Socket* socket;
Widget* menu;
RefPtr<Gtk::ActionGroup> m_refActionGroup;
RefPtr<Gtk::UIManager> m_refUIManager;
ModelDrawing* mdl_Draw;
ViewDrawing* view_Draw;
ControlerDrawing* cntrl_Draw;
ModelChat* mdl_Chat;
ViewChat* view_Chat;
ControlerChat* cntrl_Chat;
ModelQueue* mdl_Que;
ViewQueue* view_Que;
ControlerQueue* cntrl_Que;
Frame* label_frame;
Label* status_label;
Login_Dialog* login;
protected:
//Containers
HBox* main_HBox;
VBox* base_VBox;
};
#endif /* MAINWINDOW_H_ */
</code></pre>
<p>The functions are defined as follows:</p>
<pre><code>/*
* MainWindow.cpp
*/
#include "MainWindow.h"
MainWindow::MainWindow(int type)
{
this->socket = new TCP_IP_Socket(this);
//Login Section
this->login = new Login_Dialog(WINDOW_TOPLEVEL, this);
int status;
status = this->login->run();
if(status == 0)
{
exit(1);
}
this->login->hide();
//By Default Create and Open Up Student Queue
this->mdl_Que = new ModelQueue(this);
this->view_Que = new ViewQueue(this);
this->cntrl_Que = new ControlerQueue(this, (this->mdl_Que), (this->view_Que));
this->set_default_size(1200, 750);
this->set_border_width(1);
this->set_title("Tutor App");
this->base_VBox = manage(new VBox());
this->main_HBox = manage(new HBox());
this->label_frame = manage(new Frame());
m_refActionGroup = Gtk::ActionGroup::create();
m_refUIManager = Gtk::UIManager::create();
m_refActionGroup->add(Gtk::Action::create("FileMenu", "File"));
this->add_accel_group(m_refUIManager->get_accel_group());
Glib::ustring ui_info =
"<ui>"
"<menubar name='MenuBar'>"
" <menu action='FileMenu'>"
" </menu>"
"</menubar>"
"</ui>";
m_refUIManager->insert_action_group(m_refActionGroup);
m_refUIManager->add_ui_from_string(ui_info);
this->menu = m_refUIManager->get_widget("/MenuBar");
this->mdl_Draw = new ModelDrawing(this);
this->view_Draw = new ViewDrawing(this);
this->cntrl_Draw = new ControlerDrawing(this, (this->mdl_Draw), (this->view_Draw));
this->mdl_Chat = new ModelChat(this);
this->view_Chat = new ViewChat(this);
this->cntrl_Chat = new ControlerChat(this, (this->mdl_Chat), (this->view_Chat));
this->status_label = manage(new Label("Welcome to The Tutor App", ALIGN_LEFT, ALIGN_LEFT, false));
//Put it all together
this->main_HBox->pack_start(*(this->view_Draw->get_left_VBox()));
this->label_frame->add(*(this->status_label));
this->base_VBox->pack_end(*(this->label_frame));
this->main_HBox->pack_end(*(this->view_Chat->get_right_VBox()));
this->base_VBox->pack_start(*(this->menu), Gtk::PACK_SHRINK);
this->base_VBox->pack_end(*(this->main_HBox), true, true);
this->label_frame->set_size_request(-1, 5);
this->add(*(this->base_VBox));
this->show_all();
this->view_Que->get_window()->show_all();
}
MainWindow::~MainWindow()
{
}
ModelDrawing* MainWindow::get_mdl_Draw()
{
return NULL;
}
ViewDrawing* MainWindow::get_view_Draw()
{
return NULL;
}
ControlerDrawing* MainWindow::get_cntrl_Draw()
{
return NULL;
}
ModelChat* MainWindow::get_mdl_Chat()
{
return NULL;
}
ViewChat* MainWindow::get_view_Chat()
{
return NULL;
}
ControlerChat* MainWindow::get_cntrl_Chat()
{
return NULL;
}
ModelQueue* MainWindow::get_mdl_Que()
{
return NULL;
}
ViewQueue* MainWindow::get_view_Que()
{
return this->view_Que;
}
ControlerQueue* MainWindow::get_cntrl_Que()
{
return NULL;
}
Label* MainWindow::get_status_label()
{
return this->status_label;
}
void MainWindow::set_status_label(Glib::ustring label)
{
this->status_label->set_label(label);
}
TCP_IP_Socket* MainWindow::get_socket()
{
return this->socket;
}
void MainWindow::on_menu_file_quit()
{
hide(); //Closes the main window to stop the Gtk::Main::run().
}
void MainWindow::on_menu_file_new_generic()
{
std::cout << "A File|New menu item was selected." << std::endl;
}
</code></pre>
<p>Now the main window creates a <code>TCP_IP_Socket</code> class and a login dialog. I first create the connection and set a few strings (seen in the code below):</p>
<pre><code>/*
* TCP_IP_Socket.cpp
*/
#include "TCP_IP_Socket.h"
TCP_IP_Socket::TCP_IP_Socket(MainWindow* hwnd)
{
this->hwnd = hwnd;
server_name = "www.geoginfo.com";
this->set_server_ustring(this->server_name);
printf("%s", this->server_name);
struct addrinfo specs;
struct addrinfo* results;
int status;
memset(&specs, 0, sizeof specs);
specs.ai_flags = 0;
specs.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
specs.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(this->server_name, NULL, &specs, &results)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
exit(0);
}
char ipstr[INET6_ADDRSTRLEN];
void* addr;
if (results->ai_family == AF_INET)
{ // IPv4
struct sockaddr_in* ipv4 = (struct sockaddr_in*)results->ai_addr;
addr = &(ipv4->sin_addr);
}
else
{ // IPv6
struct sockaddr_in6* ipv6 = (struct sockaddr_in6 *)results->ai_addr;
addr = &(ipv6->sin6_addr);
}
inet_ntop(results->ai_family, addr, ipstr, sizeof ipstr);
this->set_serverip_ustring(ipstr);
printf(" = %s\n", ipstr);
freeaddrinfo(results); // free the linked list
printf("\n");
}
TCP_IP_Socket::~TCP_IP_Socket()
{
}
void TCP_IP_Socket::set_server_ustring(const char* server_name)
{
this->server_domainname = new ustring(server_name);
}
void TCP_IP_Socket::set_serverip_ustring(const char* ip)
{
this->server_ip = new ustring(ip);
}
Glib::ustring* TCP_IP_Socket::get_server_domainname()
{
return this->server_domainname;
}
Glib::ustring* TCP_IP_Socket::get_server_ip()
{
return this->server_ip;
}
</code></pre>
<p>and then I create the login and try to access the <code>server_ip</code> ustring and <code>server_domainname</code> ustring from my login dialog:</p>
<pre><code>/*
* Login_Dialog.cpp
*/
#include "Login_Dialog.h"
Login_Dialog::Login_Dialog(int type, MainWindow* hwnd)
{
this->hwnd = hwnd;
this->set_default_size(100, 150);
this->user_layout = manage(new HBox());
this->pswd_layout = manage(new HBox());
this->user_name = manage(new Label("Username"));
this->user_entry = manage(new Entry());
this->pswd_user = manage(new Label("Password"));
this->pswd_entry = manage(new Entry());
this->Ok = add_button("Ok", 1);
this->Cancel = add_button("Cancel", 0);
Glib::ustring* one = hwnd->get_socket()->get_server_domainname();
this->status_label = manage (new Label("This is a test", ALIGN_LEFT, ALIGN_LEFT, false));
this->Ok->set_size_request(74, -1);
this->Cancel->set_size_request(74, -1);
this->user_layout->pack_start(*(this->user_name), true, true);
this->user_layout->pack_end(*(this->user_entry), true, true);
this->pswd_layout->pack_start(*(this->pswd_user), true, true);
this->pswd_layout->pack_end(*(this->pswd_entry), true, true);
this->get_vbox()->pack_start(*(this->user_layout));
this->get_vbox()->pack_end(*(this->status_label), true, true);
this->get_vbox()->pack_end(*(this->pswd_layout));
show_all(); //<-- This is key
}
void Login_Dialog::set_status_label(Glib::ustring label)
{
this->status_label->set_label(label);
}
</code></pre>
<p>When I try to compile this I get the error listed at the very top of this post. If I remove <code>class MainWindow;</code> and replace it with <code>#include "MainWindow.h"</code>, I run into circular reference issues with headers. </p>
<p>I know I posted a lot of code, but I didn't want to get flamed for not posting enough.</p> | 2,391,419 | 3 | 1 | null | 2010-03-06 05:01:18.947 UTC | 2 | 2011-08-18 15:41:54.577 UTC | 2011-08-18 15:41:54.577 UTC | null | 496,830 | null | 287,592 | null | 1 | 8 | c++ | 51,321 | <p>You can get away with forward declaring MainWindow in Login_Dialog.h as long as you only forward declar a pointer to the type (which you do), and you add this to the top of <code>Login_Dialog.h</code> so the compiler knows to expect to see a class declaration at some later time.</p>
<pre><code>class MainWindow;
</code></pre>
<p>Then in Login_Dialog.cpp, include "mainwindow.h" like this.</p>
<pre><code>/*
* Login_Dialog.cpp
*
* Created on: Mar 2, 2010
* Author: Matthew
*/
#include "Login_Dialog.h"
#include "MainWindow.h"
</code></pre>
<p>That should do it.</p> |
40,679,441 | Minimize workbook/sheet but keep form opened | <p>Is there a way to minimize a workbook/sheet but able to keep the form opened up?
I have tried the code:</p>
<pre><code>application.visible=false
</code></pre>
<p>and</p>
<pre><code>userform1.show vbmodeless
</code></pre>
<p>But this hides the all active workbooks and the tool bar ribbon thing disappears as well. Is there a way to minimize the workbook but keep the ribbon showing and form opened as well?</p> | 40,680,309 | 1 | 0 | null | 2016-11-18 14:24:59.817 UTC | 1 | 2016-11-18 15:41:31.657 UTC | 2016-11-18 15:10:04.533 UTC | null | 4,687,348 | null | 4,383,965 | null | 1 | 4 | vba|excel | 45,288 | <p><em>Tested on Excel 2010</em></p>
<pre><code>Sub Test()
ActiveWindow.WindowState = xlMinimized
UserForm1.Show
End Sub
</code></pre>
<p>This will minimize the all the workbooks in Excel but will keep the ribbon and any userforms visible, if you dont have <code>Application.ScreenUpdating = False</code> then people will be able to see the workbooks in the bottom left of Excel.</p>
<hr>
<p>If you want to just minimize a single workbook you can use the code below</p>
<p><em><a href="https://stackoverflow.com/a/11357540/5784703">Credit to this answer on SO for the minimizing specific workbooks</a></em></p>
<pre><code>Sub test()
Dim wbName As Window
Set wbName = ActiveWorkbook.Windows(1)'You can use Windows("[Workbook Name]") as well
wbName.Visible = False
wbName.Visible = True
End Sub
</code></pre>
<p>Let me know if you need anything clarified</p> |
38,938,315 | Difference between CMAKE_PROJECT_NAME and PROJECT_NAME? | <p>What is the difference between CMAKE_PROJECT_NAME and PROJECT_NAME?</p>
<p>From the documentation:</p>
<p><a href="https://cmake.org/cmake/help/v3.6/variable/CMAKE_PROJECT_NAME.html" rel="noreferrer">CMAKE_PROJECT_NAME</a></p>
<blockquote>
<p>The name of the current project.</p>
<p>This specifies name of the current project from the closest inherited project() command.</p>
</blockquote>
<p><a href="https://cmake.org/cmake/help/v3.6/variable/PROJECT_NAME.html" rel="noreferrer">PROJECT_NAME</a></p>
<blockquote>
<p>Name of the project given to the project command.</p>
<p>This is the name given to the most recent project() command.</p>
</blockquote>
<p>I don't understand the difference.</p>
<p>When should I use <code>CMAKE_PROJECT_NAME</code>? When should I use <code>PROJECT_NAME</code>?</p> | 38,940,669 | 2 | 0 | null | 2016-08-14 01:04:51.583 UTC | 3 | 2022-03-06 17:49:36.733 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 884,893 | null | 1 | 32 | cmake | 12,956 | <p>From the documentation, I don't get the difference between the two variables.</p>
<p>The difference is that <code>CMAKE_PROJECT_NAME</code> is the name from the last <code>project</code> call from the root CMakeLists.txt, while <code>PROJECT_NAME</code> is from the last <code>project</code> call, regardless from the location of the file containing the command.</p>
<p>The difference is recognizable from the following test.</p>
<p>File structure:</p>
<pre><code>|-CMakeLists.txt
\-test2
|-CMakeLists.txt
\-test3
\-CMakeLists.txt
</code></pre>
<p>CMakeLists.txt:</p>
<pre><code>cmake_minimum_required(VERSION 3.0)
project(A)
message("< ${CMAKE_PROJECT_NAME} / ${PROJECT_NAME}")
project(B)
message("< ${CMAKE_PROJECT_NAME} / ${PROJECT_NAME}")
add_subdirectory(test2)
message("< ${CMAKE_PROJECT_NAME} / ${PROJECT_NAME}")
project(C)
message("< ${CMAKE_PROJECT_NAME} / ${PROJECT_NAME}")
</code></pre>
<p>test2/CMakeLists.txt:</p>
<pre><code>project(D)
message("<< ${CMAKE_PROJECT_NAME} / ${PROJECT_NAME}")
add_subdirectory(test3)
project(E)
message("<< ${CMAKE_PROJECT_NAME} / ${PROJECT_NAME}")
</code></pre>
<p>test2/test3/CMakeLists.txt:</p>
<pre><code>project(F)
message("<<< ${CMAKE_PROJECT_NAME} / ${PROJECT_NAME}")
</code></pre>
<p>The relevant output is:</p>
<blockquote>
<pre><code>< A / A
< B / B
<< B / D
<<< B / F
<< B / E
< B / B
< C / C
</code></pre>
</blockquote>
<p>In the sub-directories, always B is the value for <code>CMAKE_PROJECT_NAME</code>.</p> |
63,410,442 | jenkins installation windows 10 "Service Logon Credentials" | <p>I don't know Jenkins at all. I want to install Jenkins on Windows 10. I downloaded the installer and ran it, but I have a problem. I don't know what to enter in the "Account" and "Password" fields on the "Service Logon Credentials" stage.</p>
<p><a href="https://i.stack.imgur.com/FAHwb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FAHwb.png" alt="Screen of where I got stuck - Service Logon Credentials" /></a></p>
<p>if I use the username and password of my Windows account(with administrator privileges) the following information is displayed:</p>
<p><a href="https://i.stack.imgur.com/TWIwD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TWIwD.png" alt="Test Credentials information" /></a></p> | 63,582,616 | 8 | 1 | null | 2020-08-14 09:46:49.913 UTC | 17 | 2022-08-27 13:02:55.453 UTC | 2020-09-15 16:25:53.757 UTC | null | 4,826,457 | null | 14,104,370 | null | 1 | 63 | jenkins | 61,735 | <p>When installing a service to run under a domain user account, the account must have the right to logon as a service. This logon permission applies strictly to the local computer and must be granted in the Local Security Policy.
Perform the following to edit the Local Security Policy of the computer you want to define the ‘logon as a service’ permission:</p>
<ol>
<li>Logon to the computer with administrative privileges.</li>
<li>Open the ‘Administrative Tools’ and open the ‘Local Security Policy’</li>
<li>Expand ‘Local Policy’ and click on ‘User Rights Assignment’</li>
<li>In the right pane, right-click ‘Log on as a service’ and select properties.</li>
<li>Click on the ‘Add User or Group…’ button to add the new user.</li>
<li>In the ‘Select Users or Groups’ dialogue, find the user you wish to enter and click ‘OK’</li>
<li>Click ‘OK’ in the ‘Log on as a service Properties’ to save changes.</li>
</ol>
<p>Then try again with the added user.</p>
<p>(<a href="https://www.jenkins.io/doc/book/installing/windows" rel="noreferrer">Source</a>)</p> |
35,845,039 | how base option affects gulp.src & gulp.dest | <p>I encountered an issue trying to copy a set of files and when calling .dest('some folder') the entire folder structure was lost.</p>
<p>I searched and found an answer suggesting that I should provide <code>{base:'.'}</code> as an option on my call to <code>gulp.src(...)</code> to resolve this issue.</p>
<p>The <a href="https://github.com/arvindr21/gulp/blob/master/docs/API.md#options" rel="noreferrer">documentation for gulp.src options</a> only says that its options are:</p>
<blockquote>
<p>Options to pass to node-glob through glob-stream.</p>
</blockquote>
<p>Looking into <a href="https://github.com/isaacs/node-glob#options" rel="noreferrer">node-glob documentation for its options</a> base is not listed there at all.<br>
And the <a href="https://github.com/gulpjs/glob-stream#options" rel="noreferrer">glob-stream options documentation</a> only states that </p>
<blockquote>
<p>"the Default is everything before a glob starts (see glob-parent)"</p>
</blockquote>
<p>So no much help here either.</p>
<p>So, what effect does the <code>base</code> option passed to <code>gulp.src</code> have on the viny6l files in the created stream and how does it effect the <code>gulp.dest</code> command ?</p> | 35,848,322 | 1 | 0 | null | 2016-03-07 13:27:55.743 UTC | 16 | 2018-12-11 08:46:45.56 UTC | null | null | null | null | 25,412 | null | 1 | 37 | gulp | 20,826 | <p>(You're not looking at the official gulp documentation. <a href="http://github.com/arvindr21/gulp" rel="noreferrer">http://github.com/arvindr21/gulp</a> is just some guy's fork of the gulpjs github repo. The official repo is <a href="http://github.com/gulpjs/gulp/" rel="noreferrer">http://github.com/gulpjs/gulp/</a> where the <a href="https://github.com/gulpjs/gulp/blob/master/docs/api/concepts.md#glob-base" rel="noreferrer">base option is indeed documented</a>.)</p>
<p>To answer your question:</p>
<p>If you don't specify the <code>base</code> option yourself, then everything before the first glob in your <code>gulp.src()</code> paths is automatically used as the <code>base</code> option and ommitted when writing to the destination folder.</p>
<p>Say you have the following files:</p>
<pre><code>some/path/example/app/js/app.js
some/path/example/vendor/js/vendor.js
some/path/example/vendor/lib/js/lib.js
</code></pre>
<p>And this is your Gulpfile.js:</p>
<pre><code>gulp.src('some/path/**/js/*.js')
.pipe(gulp.dest('output'));
</code></pre>
<p>In this case everything before the <code>**</code> is automatically used as your <code>base</code> option. So the above is essentially equivalent to this:</p>
<pre><code>gulp.src('some/path/**/js/*.js', {base:'some/path/'})
.pipe(gulp.dest('output'));
</code></pre>
<p>What this means is that <code>some/path/</code> is stripped from the path of every file that matches the pattern in <code>gulp.src()</code>. The resulting structure in the <code>output</code> folder looks like this:</p>
<pre><code>output/example/app/js/app.js
output/example/vendor/js/vendor.js
output/example/vendor/lib/js/lib.js
</code></pre>
<p>So a certain part of the directory structure of your source files is indeed lost. How much of your directory structure you lose depends on where the first glob in your <code>gulp.src()</code> pattern is.</p>
<p>If you want to avoid this you have to explicitly specify the <code>base</code> option:</p>
<pre><code>gulp.src('some/path/**/js/*.js', {base:'.'})
.pipe(gulp.dest('output'));
</code></pre>
<p>Now <code>some/path/</code> will not be stripped from your file paths, resulting in the following folder structure in <code>output</code>:</p>
<pre><code>output/some/path/example/app/js/app.js
output/some/path/example/vendor/js/vendor.js
output/some/path/example/vendor/lib/js/lib.js
</code></pre>
<p><strong>EDIT:</strong> If you pass an array of patterns to <code>gulp.src()</code> there's no way to specify a different <code>base</code> option for each of the array elements. This for example <em>won't</em> work:</p>
<pre><code>gulp.src(
['source1/examples/**/*.html',
'source2/examples/**/*.html'],
{ base: ['source1/', // Doesn't work.
'source2/']} // Needs to be a string.
).pipe(gulp.dest('dist'));
</code></pre>
<p>Instead you have to follow the <a href="https://github.com/gulpjs/gulp/blob/master/docs/recipes/using-multiple-sources-in-one-task.md" rel="noreferrer">"Using multiple sources in one task" recipe</a>. This lets you merge two streams each of which can receive its own <code>base</code> option:</p>
<pre><code>var merge = require('merge-stream');
gulp.task('default', function() {
merge(gulp.src('source1/examples/**/*.html', {base: 'source1/'}),
gulp.src('source2/examples/**/*.html', {base: 'source2/'}))
.pipe(gulp.dest('dist'));
});
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.