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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,802,893 | Number of days between two dates in Joda-Time | <p>How do I find the difference in Days between two <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a> <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html" rel="noreferrer"><code>DateTime</code></a> instances?
With ‘difference in days’ I mean if start is on Monday and end is on Tuesday I expect a return value of 1 regardless of the hour/minute/seconds of the start and end dates.</p>
<p><code>Days.daysBetween(start, end).getDays()</code> gives me 0 if start is in the evening and end in the morning.</p>
<p>I'm also having the same issue with other date fields so I was hoping there would be a generic way to 'ignore' the fields of lesser significance. </p>
<p>In other words, the months between Feb and 4 March would also be 1, as would the hours between 14:45 and 15:12 be. However the hour difference between 14:01 and 14:55 would be 0.</p> | 17,959,137 | 9 | 0 | null | 2010-09-27 10:21:30.587 UTC | 46 | 2022-01-25 05:09:22.453 UTC | 2014-12-25 09:27:48.203 UTC | null | 642,706 | null | 15,355 | null | 1 | 357 | java|date|jodatime | 225,595 | <p>Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:</p>
<pre><code>Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
</code></pre>
<p>It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.</p>
<pre><code>// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate()).getDays());
// prints 1
</code></pre>
<p>Going via a <code>LocalDate</code> sidesteps the whole issue.</p> |
8,123,142 | Data-bind href attribute for anchor tag | <p>I'm trying to bind anchor attributes to a KnockoutJS ViewModel field. I tried something like this:</p>
<pre class="lang-html prettyprint-override"><code><a data-bind="href: Link, value: Title"></a>
</code></pre>
<p>but this doesn't work. Where I can get a list of possible data-bind values for html elements?</p> | 8,123,182 | 4 | 0 | null | 2011-11-14 14:37:04.83 UTC | 8 | 2018-05-08 14:01:55.463 UTC | 2015-07-25 20:45:12.58 UTC | null | 419,956 | null | 801,306 | null | 1 | 41 | javascript|html|data-binding|knockout.js | 58,670 | <p>You need to use the <a href="http://knockoutjs.com/documentation/attr-binding.html" rel="noreferrer"><code>attr</code></a> binding, this allows you to set any attribute you like.</p>
<p>For example:</p>
<pre class="lang-html prettyprint-override"><code><a data-bind="attr: { href: Link, title: Title }, text: Title">xxx</a>
</code></pre> |
7,748,039 | Get current changeset id on workspace for TFS | <p>How do I figure out what changeset I currently have in my local workspace?</p>
<p>Sure, I can pick one file and view its history. However, if that file was not recently updated, its changeset is probably older than the more recently updated files in the same solution.</p>
<p>One possible mistake that we may make is that we view the history on the solution file, however the solution file rarely changes unless you're adding a new project / making solution-level changes.</p>
<p>In the end to figure out the changeset I need to remember what were the latest files changed and view their history.</p>
<p>Is there a better way to do this?</p> | 7,760,096 | 5 | 4 | null | 2011-10-13 00:15:11.513 UTC | 29 | 2022-01-04 18:20:29.213 UTC | 2022-01-04 18:20:29.213 UTC | null | 3,241,243 | null | 534,668 | null | 1 | 88 | tfs|tfvc | 25,379 | <p>Your answer is on a MSDN blog by Buck Hodges: <a href="https://devblogs.microsoft.com/buckh/how-to-determine-the-latest-changeset-in-your-workspace/" rel="noreferrer">How to determine the latest changeset in your workspace</a></p>
<p>from the root (top) of your workspace, in cmd perform:</p>
<pre><code>tf history . /r /noprompt /stopafter:1 /version:W
</code></pre> |
4,262,531 | Trouble building gcc 4.6: undefined reference to `yylex' | <p>I'm trying to build gcc 4.6, but I'm getting some linker errors that look like it means bison or flex isn't getting linked to. When the makefile issues this command:</p>
<pre><code>gcc -g -fkeep-inline-functions -DIN_GCC -W -Wall -Wwrite-strings -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wmissing-format-attribute -pedantic -Wno-long-long -Wno-variadic-macros -Wno-overlength-strings -Wold-style-definition -Wc++-compat -fno-common -DHAVE_CONFIG_H -DGENERATOR_FILE -o build/gengtype \
build/gengtype.o build/errors.o build/gengtype-lex.o build/gengtype-parse.o build/version.o ../../build-x86_64-unknown-linux-gnu/libiberty/libiberty.a
</code></pre>
<p>It tells me:</p>
<pre><code>/home/chris/code/gcc/trunk/host-x86_64-unknown-linux-gnu/gcc/../.././gcc/gengtype.c:960: undefined reference to `lexer_line'
... undefined reference to `yylex'
... undefined reference to `yybegin'
... undefined reference to `yyend'
</code></pre>
<p>I've installed Flex and Bison, and even tried several Bison variants with the same result. Does anybody know what else this might mean?</p> | 4,838,822 | 3 | 2 | null | 2010-11-24 00:49:53.693 UTC | 7 | 2015-05-13 07:38:38.35 UTC | 2015-05-13 07:38:38.35 UTC | null | 895,245 | null | 202,146 | null | 1 | 32 | gcc|makefile|bison | 12,044 | <p>Same happened to me, it was due to lack of flex and bison. After installing flex and bison, I ran <code>make distclean</code> and <code>./configure</code>, then it compiled fine.</p> |
4,429,036 | Passing string array between android activities | <p>I am having <strong>2 String arrays</strong> inside First Activity - A , now i need to pass both the arrays to the second_activity - B, how do i do it ? </p>
<p>I know about the <strong><code>Intent</code></strong> kind of concept in Android and already passed just single variable value to another activity, but i haven't implement the concept of passing string arrays between activities, i have already surfed net for the same.</p>
<p>pls let me know about the possible solution.</p> | 4,429,060 | 4 | 0 | null | 2010-12-13 12:59:01.947 UTC | 13 | 2022-09-22 20:26:59.517 UTC | null | null | null | null | 379,693 | null | 1 | 26 | android | 57,576 | <pre><code>Bundle b=new Bundle();
b.putStringArray(key, new String[]{value1, value2});
Intent i=new Intent(context, Class);
i.putExtras(b);
</code></pre>
<p><br>
Hope this will help you.<br>
<br>
In order to read: <br><br></p>
<pre><code>Bundle b=this.getIntent().getExtras();
String[] array=b.getStringArray(key);
</code></pre> |
4,592,352 | Number of parameters for a constructor | <p>I have a class that needs 12 parameters to be passed to its constructor. So I think that there is something wrong with the design of this class.</p>
<p>I would like to ask if there is any design pattern or a general collection of rules regarding the design of a class, especially its constructor.</p> | 4,592,466 | 5 | 2 | null | 2011-01-04 09:56:56.477 UTC | 7 | 2019-04-18 09:06:45.817 UTC | 2011-01-04 10:23:36.123 UTC | null | 265,143 | null | 425,817 | null | 1 | 35 | c++|design-patterns|parameters|refactoring|constructor | 8,068 | <p>12 parameters definitely sound too many to me. Options to reduce their numbers are:</p>
<ol>
<li><p><a href="http://sourcemaking.com/refactoring/introduce-parameter-object" rel="nofollow noreferrer">Introduce Parameter Object</a> by grouping logically related parameters into an object and passing that object instead of the individual parameters.</p></li>
<li><p>Introduce a <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="nofollow noreferrer">Builder</a> (optionally with <a href="http://en.wikipedia.org/wiki/Method_chaining" rel="nofollow noreferrer">method chaining</a>). This does not reduce the actual parameter list but it makes the code more readable, and is especially useful if you have several different creation scenarios with varying parameters. So instead of </p>
<pre><code>MyClass someObject = new MyClass(aFoo, aBar, aBlah, aBaz, aBorp, aFlirp,
andAGoo);
MyClass anotherObject = new MyClass(aFoo, null, null, aBaz, null, null,
andAGoo);
</code></pre>
<p>you can have</p>
<pre><code>MyClass someObject = new MyClassBuilder().withFoo(aFoo).withBar(aBar)
.withBlah(aBlah).withBaz(aBaz).withBorp(aBorp).withFlirp(aFlirp)
.withGoo(aGoo).build();
MyClass anotherObject = new MyClassBuilder().withFoo(aFoo).withBaz(aBaz)
.withGoo(aGoo).build();
</code></pre></li>
<li><p>(Maybe I should have started with this ;-) Analyse the parameters - Are all of them really needed in the constructor (i.e. mandatory)? If a parameter is optional, you may set it via its regular setter instead of the constructor.</p></li>
</ol> |
4,693,120 | Why isn't the 'global' keyword needed to access a global variable? | <p>From my understanding, Python has a separate namespace for functions, so if I want to use a global variable in a function, I should probably use <code>global</code>.</p>
<p>However, I was able to access a global variable even without <code>global</code>:</p>
<pre><code>>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
... return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'
</code></pre>
<p>Why does this work?</p>
<hr />
<p><sub>See also <a href="https://stackoverflow.com/questions/370357">UnboundLocalError on local variable when reassigned after first use</a> for the error that occurs when attempting to <em>assign to</em> the global variable without <code>global</code>. See <a href="https://stackoverflow.com/questions/423379/">Using global variables in a function</a> for the general question of how to use globals.</sub></p> | 4,693,385 | 11 | 2 | null | 2011-01-14 16:11:03.583 UTC | 93 | 2022-09-10 09:37:27.03 UTC | 2022-09-10 09:37:27.03 UTC | null | 523,612 | null | 246,095 | null | 1 | 336 | python|global-variables | 434,335 | <p>The keyword <code>global</code> is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.</p>
<pre><code>def bob():
me = "locally defined" # Defined only in local context
print(me)
bob()
print(me) # Asking for a global variable
</code></pre>
<p>The above will give you:</p>
<pre><code>locally defined
Traceback (most recent call last):
File "file.py", line 9, in <module>
print(me)
NameError: name 'me' is not defined
</code></pre>
<p>While if you use the <code>global</code> statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.</p>
<pre><code>def bob():
global me
me = "locally defined" # Defined locally but declared as global
print(me)
bob()
print(me) # Asking for a global variable
</code></pre>
<p>So the above code will give you:</p>
<pre><code>locally defined
locally defined
</code></pre>
<p>In addition, due to the nature of python, you could also use <code>global</code> to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.</p> |
14,380,442 | Make one section of simple web page have own scroll bar | <p>I have a section of the web page I am building that is dedicated to news events. These are simply entered as follows currently.</p>
<pre><code><tr>
<td class="newsdate">
February 2013
</td>
<td class="news">
News item 1
</td>
</tr>
<tr>
<td class="newsdate">
January 2013
</td>
<td class="news">
News items 2
</td>
</tr>
</code></pre>
<p>I would like to have it so that when there are more than 5 events listed, say, then you can use a scroll bar to see old events. That is the height of the news section will be fixed but you can scroll up and down within it to see newer and older news. How can you do this most simply?</p> | 14,380,510 | 5 | 1 | null | 2013-01-17 13:44:53.47 UTC | 2 | 2016-06-29 11:47:04.053 UTC | 2016-06-29 11:47:04.053 UTC | null | 904,874 | null | 1,473,517 | null | 1 | 13 | html|css | 51,855 | <p>Wrap your <code>table</code> in a <code>div</code> using <code>overflow-y: auto;</code> like this</p>
<p>HTML</p>
<pre><code><div class="scrollable">
<!-- Your table -->
</div>
</code></pre>
<p>CSS </p>
<pre><code>.scrollable {
height: 100px; /* or any value */
overflow-y: auto;
}
</code></pre> |
14,417,571 | Breaking a line of python to multiple lines? | <p>In C++, I like to break up my lines of code if they get too long, or if an if statement if there are a lot of checks in it.</p>
<pre><code>if (x == 10 && y < 20 && name == "hi" && obj1 != null)
// Do things
// vs
if (x == 10
&& y < 20
&& name == "hi"
&& obj1 != null)
{
// Do things
}
AddAndSpawnParticleSystem(inParticleEffectName, inEffectIDHash, overrideParticleSystems, mAppliedEffects[inEffectIDHash], inTagNameHash);
// vs
AddAndSpawnParticleSystem(inParticleEffectName, inEffectIDHash, overrideParticleSystems,
mAppliedEffects[inEffectIDHash], inTagNameHash);
</code></pre>
<p>In Python, code blocks are defined by the tabs, not by the ";" at the end of the line</p>
<pre><code>if number > 5 and number < 15:
print "1"
</code></pre>
<p>Is mutliple lines possible in python? like...</p>
<pre><code>if number > 5
and number < 15:
print "1"
</code></pre>
<p>I don't think this is possible, but it would be cool!</p> | 14,417,604 | 4 | 4 | null | 2013-01-19 18:44:45.993 UTC | 11 | 2021-10-02 11:57:15.833 UTC | 2013-01-19 19:02:33.287 UTC | null | 102,441 | null | 1,072,711 | null | 1 | 17 | python|syntax | 70,685 | <p>Style guide (<a href="https://www.python.org/dev/peps/pep-0008/#:%7E:text=the%20preferred%20way%20of%20wrapping%20long%20lines%20is%20by%20using%20python%27s%20implied%20line%20continuation%20inside%20parentheses%2C%20brackets%20and%20braces.%20long%20lines%20can%20be%20broken%20over%20multiple%20lines%20by%20wrapping%20expressions%20in%20parentheses.%20these%20should%20be%20used%20in%20preference%20to%20using%20a%20backslash%20for%20line%20continuation." rel="nofollow noreferrer">PEP-8</a>) says:</p>
<blockquote>
<p>The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.</p>
</blockquote>
<p>Method 1: Using parenthesis</p>
<pre><code>if (number > 5 and
number < 15):
print "1"
</code></pre>
<p>Method 2: Using backslash</p>
<pre><code>if number > 5 and \
number < 15:
print "1"
</code></pre>
<p>Method 3: Using backslash + indent for better readability</p>
<pre><code>if number > 5 and \
number < 15:
print "1"
</code></pre> |
14,542,193 | How to get Facebook photo, full name, gender using Facebook SDK android | <p>I am working on an Android application in which any Android user who is logging to Facebook using our Application, I need to extract his photo, his gender, his full name from the Facebook. I am using Facebook SDK for this.</p>
<p>With the help of Facebook SDK, I am able to login into Facebook but I am not sure how to extract his photo,gender and full name from the facebook?</p>
<p>Below is the code I am using to login into Facebook. I followed this <a href="https://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/#prerequisities">tutorial</a></p>
<pre><code>public class SessionLoginFragment extends Fragment {
private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
private TextView textInstructionsOrLink;
private Button buttonLoginLogout;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
buttonLoginLogout = (Button) view.findViewById(R.id.buttonLoginLogout);
textInstructionsOrLink = (TextView) view.findViewById(R.id.instructionsOrLink);
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(getActivity(), null, statusCallback,
savedInstanceState);
}
if (session == null) {
session = new Session(getActivity());
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
}
}
updateView();
return view;
}
@Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
@Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Log.d("Hello", URL_PREFIX_FRIENDS + session.getAccessToken());
Intent i = new Intent(getActivity(), ThesisProjectAndroid.class);
startActivity(i);
} else {
Log.d("Hello", "Login Failed");
textInstructionsOrLink.setText(R.string.instructions);
buttonLoginLogout.setText(R.string.login);
buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickLogin();
}
});
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
} else {
Session.openActiveSession(getActivity(), this, true, statusCallback);
}
}
private void onClickLogout() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state, Exception exception) {
updateView();
}
}
}
</code></pre>
<p>Can anyone tell me where I need to make changes in the above class to get all the three information I needed. As far as I know If I am able to get facebook unique id for that person, I can get all the information I guess. Any thoughts?</p> | 17,392,582 | 6 | 3 | null | 2013-01-26 22:23:36.51 UTC | 13 | 2017-11-27 12:28:31.57 UTC | null | null | null | null | 663,148 | null | 1 | 23 | java|android|facebook-graph-api|facebook-android-sdk | 59,874 | <p>In your <code>StatusCallback</code> function, you can get the details from the <code>GraphUser</code> object </p>
<pre><code>private class SessionStatusCallback implements Session.StatusCallback {
private String fbAccessToken;
@Override
public void call(Session session, SessionState state, Exception exception) {
updateView();
if (session.isOpened()) {
fbAccessToken = session.getAccessToken();
// make request to get facebook user info
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
Log.i("fb", "fb user: "+ user.toString());
String fbId = user.getId();
String fbAccessToken = fbAccessToken;
String fbName = user.getName();
String gender = user.asMap().get("gender").toString();
String email = user.asMap().get("email").toString();
Log.i("fb", userProfile.getEmail());
}
});
}
}
}
</code></pre> |
14,563,489 | How to test a spring controller method by using MockMvc? | <p>I'm using spring 3.2.0 and junit 4</p>
<p>This is my controller method which I need to test </p>
<pre><code>@RequestMapping(value="Home")
public ModelAndView returnHome(){
return new ModelAndView("Home");
}
</code></pre>
<p>spring-servlet config is: </p>
<pre><code><context:annotation-config/>
<context:component-scan base-package="com.spring.poc" />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</code></pre>
<p>This is my test class :</p>
<pre><code>public class TestController {
private MockMvc mockMvc;
@Before
public void setup() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
this.mockMvc = standaloneSetup(new CController()).setViewResolvers(
viewResolver).build();
}
@Test
public void CControllerTest() throws Exception {
......
......
}
</code></pre>
<p>}</p>
<p>How can I test this method with MockMvc ?</p> | 14,566,090 | 1 | 0 | null | 2013-01-28 13:49:36.527 UTC | 8 | 2017-06-21 06:12:42.103 UTC | 2015-11-13 16:09:03.657 UTC | null | 1,265,077 | null | 1,686,842 | null | 1 | 25 | spring|junit|integration-testing | 101,845 | <p>You can use your applications dispatcher servlet xml using the following annoations. The following example is hitting a controller with the path /mysessiontest setting some session attributes and expecting a certain view to be returned:</p>
<pre><code>import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ "classpath:springDispatcher-servlet.xml" })
public class MySessionControllerTest {
@Autowired WebApplicationContext wac;
@Autowired MockHttpSession session;
@Autowired MockHttpServletRequest request;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void getAccount() throws Exception {
UserDomain user = new UserDomain();
user.setFirstName("johnny");
session.setAttribute("sessionParm",user);
this.mockMvc.perform(get("/mysessiontest").session(session)
.accept(MediaType.TEXT_HTML))
.andExpect(status().isOk())
.andExpect(view().name("test"));
}
}
</code></pre> |
14,729,385 | Using Moq to Mock a Func<> constructor parameter and Verify it was called twice | <p>Taken the question from this article (<a href="https://stackoverflow.com/questions/6036708/how-to-moq-a-func">How to moq a Func</a>) and adapted it as the answer is not correct. </p>
<pre><code>public class FooBar
{
private Func<IFooBarProxy> __fooBarProxyFactory;
public FooBar(Func<IFooBarProxy> fooBarProxyFactory)
{
_fooBarProxyFactory = fooBarProxyFactory;
}
public void Process()
{
_fooBarProxyFactory();
_fooBarProxyFactory();
}
}
</code></pre>
<p>I have a need to mock a Func<> that is passed as a constructor parameter, the assert that the func was call twice. </p>
<p>When trying to mock the function <code>var funcMock = new Mock<Func<IFooBarProxy>>();</code> Moq raises and exception as the Func type is not mockable. </p>
<p>The issue is that without mocking the func it is not possible to verify that the func was called (n) times. <code>funcMock.Verify( (), Times.AtLeast(2));</code></p> | 14,729,415 | 4 | 1 | null | 2013-02-06 12:43:29.44 UTC | 2 | 2022-07-19 03:51:52.45 UTC | 2017-05-23 12:10:05.507 UTC | null | -1 | null | 2,033,659 | null | 1 | 42 | c#|unit-testing|moq|functional-testing | 25,142 | <p>I don't think it is necessary to use a mock for the Func.</p>
<p>You can simply create an ordinary Func yourself that returns a mock of <code>IFooBarProxy</code>:</p>
<pre><code>int numberOfCalls = 0;
Func<IFooBarProxy> func = () => { ++numberOfCalls;
return new Mock<IFooBarProxy>(); };
var sut = new FooBar(func);
sut.Process();
Assert.Equal(2, numberOfCalls);
</code></pre> |
14,758,088 | How are atomic operations implemented at a hardware level? | <p>I get that at the assembly language level instruction set architectures provide compare and swap and similar operations. However, I don't understand how the chip is able to provide these guarantees.</p>
<p>As I imagine it, the execution of the instruction must</p>
<ol>
<li>Fetch a value from memory</li>
<li>Compare the value</li>
<li>Depending on the comparison, possibly store another value in memory</li>
</ol>
<p>What prevents another core from accessing the memory address after the first has fetched it but before it sets the new value? Does the memory controller manage this?</p>
<p>edit: If the x86 implementation is secret, I'd be happy to hear how any processor family implements it.</p> | 14,761,050 | 4 | 5 | null | 2013-02-07 18:13:29.51 UTC | 33 | 2022-04-10 23:42:36.133 UTC | 2022-04-10 23:42:36.133 UTC | null | 224,132 | null | 1,825,544 | null | 1 | 59 | x86|atomic|cpu-architecture|lock-free|smp | 15,554 | <p>Here is an <a href="http://software.intel.com/en-us/articles/implementing-scalable-atomic-locks-for-multi-core-intel-em64t-and-ia32-architectures" rel="nofollow noreferrer">article</a> over at software.intel.com on that sheds little light on user level locks:</p>
<blockquote>
<p>User level locks involve utilizing the atomic instructions of
processor to atomically update a memory space. The atomic instructions
involve utilizing a lock prefix on the instruction and having the
destination operand assigned to a memory address. The following
instructions can run atomically with a lock prefix on current Intel
processors: ADD, ADC, AND, BTC, BTR, BTS, CMPXCHG, CMPXCH8B, DEC, INC,
NEG, NOT, OR, SBB, SUB, XOR, XADD, and XCHG. [...] On most instructions
a lock prefix must be explicitly used except for the xchg instruction
where the lock prefix is implied if the instruction involves a memory
address.</p>
<p>In the days of Intel 486 processors, the lock prefix used to assert a
lock on the bus along with a large hit in performance. Starting with
the Intel Pentium Pro architecture, the bus lock is transformed into a
cache lock. A lock will still be asserted on the bus in the most
modern architectures if the lock resides in uncacheable memory or if
the lock extends beyond a cache line boundary splitting cache lines.
Both of these scenarios are unlikely, so most lock prefixes will be
transformed into a cache lock which is much less expensive.</p>
</blockquote>
<p>So what prevents another core from accessing the memory address? The <a href="https://en.wikipedia.org/wiki/Cache_coherence#Coherence_protocols" rel="nofollow noreferrer">cache coherency protocol</a> already manages access rights for cache lines. So if a core has (temporal) exclusive access rights to a cache line, no other core can access that cache line. To access that cache line the other core has to obtain access rights first, and the protocol to obtain those rights involves the current owner. In effect, the cache coherency protocol prevents other cores from accessing the cache line silently.</p>
<p>If the locked access is not bound to a single cache line things get more complicated. There are all kinds of nasty corner cases, like locked accesses over page boundaries, etc. Intel does not tell details and they probably use all kinds of tricks to make locks faster.</p> |
14,718,135 | How can I tell which python implementation I'm using? | <p>Python has a few different implementations: CPython, Jython, PyPy, etc. I want to programmatically determine which implementation my code is running on. How can I do that?</p>
<p>To be specific, write a function called <code>get_implementation_name()</code> for me:</p>
<pre><code>impl_name = get_implementation_name()
if impl_name == "CPython":
print "I can abuse CPython implementation details. (I'm a bad, bad man.)"
elif impl_name == "PyPy":
print "Can't count on reference-counting garbage collection here..."
else:
print "I better be careful..."
</code></pre> | 14,718,168 | 2 | 5 | null | 2013-02-05 22:22:56.82 UTC | 14 | 2022-08-15 15:09:16.933 UTC | 2013-02-05 22:43:20.523 UTC | null | 162,094 | null | 162,094 | null | 1 | 73 | python|cpython | 14,972 | <pre><code>In [50]: import platform
In [52]: platform.python_implementation()
Out[52]: 'CPython'
</code></pre> |
3,152,252 | Routing: 'admin' => true vs 'prefix' => 'admin in CakePHP | <p>Hi I'm setting up admin routing in CakePHP.</p>
<p>This is my current route:</p>
<pre><code>Router::connect('/admin/:controller/:action/*', array('admin' => true, 'prefix' => 'admin', 'controller' => 'pages', 'action' => 'display', 'home'));
</code></pre>
<p>It works fine, but I don't understand what the difference between 'admin' => true, and 'prefix' => 'admin' is.</p>
<p>When I omitted <code>'prefix' => 'admin'</code>, the router wouldn't use <code>admin_index</code> and would instead just use <code>index</code>. So what's the point of <code>'admin' => true</code>?</p> | 3,164,666 | 2 | 0 | null | 2010-06-30 18:30:45.813 UTC | 14 | 2010-09-26 11:45:30.067 UTC | null | null | null | null | 375,962 | null | 1 | 14 | cakephp|routing|routes|cakephp-1.3 | 19,546 | <p>By setting <code>'prefix' => 'admin'</code> you are telling CakePHP that you want to use a prefix of <code>admin</code> for that route; basically meaning you want to use controller actions and views that have names prefixed with <code>admin_</code>. This part you are already aware of, and things will probably work fine with just this.</p>
<p>When creating routes though, any array keys passed into the second argument that aren't recognised by CakePHP (ie. not your usual <code>controller</code>, <code>action</code>, <code>plugin</code>, <code>prefix</code> stuff) are set as named parameters during requests matching that route.</p>
<p>Adding <code>'admin' => true</code> is therefore just a named parameter in this case, but it comes with its advantages. Firstly, it can make code more succinct.</p>
<pre><code>/* Determine if a request came through admin routing */
// without:
if ($this->params['prefix'] == 'admin') {}
// with:
if ($this->params['admin']) {}
/* Create a link that is reverse-routed to an admin prefixed route */
// without:
$html->link('...', array('prefix' => 'admin', 'controller' => 'users'));
// with:
$html->link('...', array('admin' => true, 'controller' => 'users'));
</code></pre>
<p>Secondly, it provides backwards compatibility with the way admin routing worked in CakePHP 1.2 (the last line from the above example is how you would have made admin routing links in 1.2). Therefore, developers migrating from 1.2 to 1.3 can prevent having to change links throughout their application by keeping the <code>'admin' => true</code> flag in their routes (and adding the <code>'prefix' => 'admin'</code> one).</p>
<p>Lastly, by setting a custom flag like this with a named parameter and using it in your application instead of referencing your route by an exact string means that you prevent yourself from ever having to change links if you change the prefix to something else (say from <code>admin</code> to <code>administrator</code> or <code>edit</code>)... although this is sort of a moot point, as you would need to rename all your <code>admin_*</code> controller actions and views. :)</p> |
2,364,273 | How to make sure there is no race condition in MySQL database when incrementing a field? | <p>How to prevent a race condition in MySQL database when two connections want to update the same record?</p>
<p>For example, connection 1 wants to increase "tries" counter. And the second connection wants to do the same. Both connections <code>SELECT</code> the "tries" count, increase the value and both <code>UPDATE</code> "tries" with the increased value. Suddenly "tries" is only "tries+1" instead of being "tries+2", because both connections got the same "tries" and incremented it by one.</p>
<p>How to solve this problem?</p> | 2,364,320 | 2 | 1 | null | 2010-03-02 15:29:03.137 UTC | 19 | 2011-08-14 16:50:49.257 UTC | 2011-08-14 16:50:49.257 UTC | null | 560,648 | null | 257,942 | null | 1 | 33 | mysql|race-condition | 20,717 | <p>Here's 3 different approaches:</p>
<h3>Atomic update</h3>
<pre><code>update table set tries=tries+1 where condition=value;
</code></pre>
<p>and it will be done atomically.</p>
<h3>Use transactions</h3>
<p>If you do need to first select the value and update it in your application, you likely need to use transactions. That means you'll have to use InnoDB, not MyISAM tables.
Your query would be something like:</p>
<pre><code>BEGIN; //or any method in the API you use that starts a transaction
select tries from table where condition=value for update;
.. do application logic to add to `tries`
update table set tries=newvalue where condition=value;
END;
</code></pre>
<p>if the transaction fails, you might need to manually retry it.</p>
<h3>Version scheme</h3>
<p>A common approach is to introduce a version column in your table. Your queries would do something like:</p>
<pre><code>select tries,version from table where condition=value;
.. do application logic, and remember the old version value.
update table set tries=newvalue,version=version + 1 where condition=value and version=oldversion;
</code></pre>
<p>If that update fails/returns 0 rows affected, someone else has updated the table in the mean time. You have to start all over - that is, select the new values, do the application logic and try the update again.</p> |
1,379,566 | What is the difference between HttpContext.Current.Request.IsAuthenticated and HttpContext.Current.User.Identity.IsAuthenticated? | <p>What is the difference between HttpContext.Current.Request.IsAuthenticated and HttpContext.Current.User.Identity.IsAuthenticated?</p>
<p>Which one would you use in which situation?</p> | 1,379,601 | 1 | 0 | null | 2009-09-04 14:20:19.25 UTC | 8 | 2011-08-04 10:25:33.98 UTC | null | null | null | null | 15,928 | null | 1 | 34 | asp.net | 7,981 | <p>There's absolutely no difference. Checkout HttpContext.Current.Request.IsAuthenticated implementation:</p>
<pre><code>public bool IsAuthenticated
{
get
{
return (((this._context.User != null) &&
(this._context.User.Identity != null)) &&
this._context.User.Identity.IsAuthenticated);
}
}
</code></pre> |
27,373,812 | Swift - How to hide back button in navigation item? | <p>Right now I have two view controllers. My problem is I don't know how to hide the back button after transitioning to the second view controller. Most references that I found are in Objective-C. How do I code it in Swift?</p>
<p>Hide back button code in Objective-C</p>
<pre><code>[self.navigationItem setHidesBackButton:YES animated:YES];
</code></pre> | 27,373,956 | 13 | 0 | null | 2014-12-09 07:49:20.61 UTC | 24 | 2022-06-29 12:35:41.04 UTC | 2020-08-13 14:38:07.323 UTC | null | 1,032,372 | null | 1,922,589 | null | 1 | 131 | ios|swift | 128,501 | <p>According to the <a href="https://developer.apple.com/documentation/uikit/uinavigationitem/1624934-sethidesbackbutton" rel="noreferrer">documentation</a> for <code>UINavigationItem</code> :</p>
<pre><code>self.navigationItem.setHidesBackButton(true, animated: true)
</code></pre> |
38,940,312 | Why does Spark report "java.net.URISyntaxException: Relative path in absolute URI" when working with DataFrames? | <p>I am running Spark locally on a Windows machine. I was able to launch the spark shell successfully and also read in text files as RDDs. I was also able to follow along the various online tutorials on this subject and was able to perform various operations on the RDDs.</p>
<p>However, when I try to convert an RDD into a DataFrame I am getting an error. This is what I am doing:</p>
<pre><code>val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._
//convert rdd to df
val df = rddFile.toDF()
</code></pre>
<p>This code generates a long series of error messages that seem to relate to the following one:</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
at org.apache.hadoop.fs.Path.initialize(Path.java:205)
at org.apache.hadoop.fs.Path.<init>(Path.java:171)
at org.apache.hadoop.hive.metastore.Warehouse.getWhRoot(Warehouse.java:159)
at org.apache.hadoop.hive.metastore.Warehouse.getDefaultDatabasePath(Warehouse.java:177)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB_core(HiveMetaStore.java:600)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:620)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:461)
at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:66)
at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:72)
at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:5762)
at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:199)
at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:74)
... 85 more
Caused by: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
at java.net.URI.checkPath(URI.java:1823)
at java.net.URI.<init>(URI.java:745)
at org.apache.hadoop.fs.Path.initialize(Path.java:202)
... 96 more
</code></pre>
<p>The entire stack trace follows.</p>
<pre><code>16/08/16 12:36:20 WARN ObjectStore: Failed to get database default, returning NoSuchObjectException
16/08/16 12:36:20 WARN Hive: Failed to access metastore. This class should not accessed in runtime.
org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases(Hive.java:1236)
at org.apache.hadoop.hive.ql.metadata.Hive.reloadFunctions(Hive.java:174)
at org.apache.hadoop.hive.ql.metadata.Hive.<clinit>(Hive.java:166)
at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:503)
at org.apache.spark.sql.hive.client.HiveClientImpl.<init>(HiveClientImpl.scala:171)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.spark.sql.hive.client.IsolatedClientLoader.createClient(IsolatedClientLoader.scala:258)
at org.apache.spark.sql.hive.HiveUtils$.newClientForMetadata(HiveUtils.scala:359)
at org.apache.spark.sql.hive.HiveUtils$.newClientForMetadata(HiveUtils.scala:263)
at org.apache.spark.sql.hive.HiveSharedState.metadataHive$lzycompute(HiveSharedState.scala:39)
at org.apache.spark.sql.hive.HiveSharedState.metadataHive(HiveSharedState.scala:38)
at org.apache.spark.sql.hive.HiveSharedState.externalCatalog$lzycompute(HiveSharedState.scala:46)
at org.apache.spark.sql.hive.HiveSharedState.externalCatalog(HiveSharedState.scala:45)
at org.apache.spark.sql.hive.HiveSessionState.catalog$lzycompute(HiveSessionState.scala:50)
at org.apache.spark.sql.hive.HiveSessionState.catalog(HiveSessionState.scala:48)
at org.apache.spark.sql.hive.HiveSessionState$$anon$1.<init>(HiveSessionState.scala:63)
at org.apache.spark.sql.hive.HiveSessionState.analyzer$lzycompute(HiveSessionState.scala:63)
at org.apache.spark.sql.hive.HiveSessionState.analyzer(HiveSessionState.scala:62)
at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:49)
at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:64)
at org.apache.spark.sql.SparkSession.baseRelationToDataFrame(SparkSession.scala:382)
at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:143)
at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:401)
at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:342)
at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:24)
at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:29)
at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:31)
at $line14.$read$$iw$$iw$$iw$$iw$$iw.<init>(<console>:33)
at $line14.$read$$iw$$iw$$iw$$iw.<init>(<console>:35)
at $line14.$read$$iw$$iw$$iw.<init>(<console>:37)
at $line14.$read$$iw$$iw.<init>(<console>:39)
at $line14.$read$$iw.<init>(<console>:41)
at $line14.$read.<init>(<console>:43)
at $line14.$read$.<init>(<console>:47)
at $line14.$read$.<clinit>(<console>)
at $line14.$eval$.$print$lzycompute(<console>:7)
at $line14.$eval$.$print(<console>:6)
at $line14.$eval.$print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:786)
at scala.tools.nsc.interpreter.IMain$Request.loadAndRun(IMain.scala:1047)
at scala.tools.nsc.interpreter.IMain$WrappedRequest$$anonfun$loadAndRunReq$1.apply(IMain.scala:638)
at scala.tools.nsc.interpreter.IMain$WrappedRequest$$anonfun$loadAndRunReq$1.apply(IMain.scala:637)
at scala.reflect.internal.util.ScalaClassLoader$class.asContext(ScalaClassLoader.scala:31)
at scala.reflect.internal.util.AbstractFileClassLoader.asContext(AbstractFileClassLoader.scala:19)
at scala.tools.nsc.interpreter.IMain$WrappedRequest.loadAndRunReq(IMain.scala:637)
at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:569)
at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:565)
at scala.tools.nsc.interpreter.ILoop.interpretStartingWith(ILoop.scala:807)
at scala.tools.nsc.interpreter.ILoop.command(ILoop.scala:681)
at scala.tools.nsc.interpreter.ILoop.processLine(ILoop.scala:395)
at scala.tools.nsc.interpreter.ILoop.loop(ILoop.scala:415)
at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:923)
at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:909)
at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:909)
at scala.reflect.internal.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:97)
at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:909)
at org.apache.spark.repl.Main$.doMain(Main.scala:68)
at org.apache.spark.repl.Main$.main(Main.scala:51)
at org.apache.spark.repl.Main.main(Main.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:729)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1523)
at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:86)
at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:132)
at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:104)
at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:3005)
at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3024)
at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases(Hive.java:1234)
... 74 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1521)
... 80 more
Caused by: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
at org.apache.hadoop.fs.Path.initialize(Path.java:205)
at org.apache.hadoop.fs.Path.<init>(Path.java:171)
at org.apache.hadoop.hive.metastore.Warehouse.getWhRoot(Warehouse.java:159)
at org.apache.hadoop.hive.metastore.Warehouse.getDefaultDatabasePath(Warehouse.java:177)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB_core(HiveMetaStore.java:600)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:620)
at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:461)
at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:66)
at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:72)
at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:5762)
at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:199)
at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:74)
... 85 more
Caused by: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
at java.net.URI.checkPath(URI.java:1823)
at java.net.URI.<init>(URI.java:745)
at org.apache.hadoop.fs.Path.initialize(Path.java:202)
... 96 more
</code></pre> | 38,945,867 | 5 | 0 | null | 2016-08-14 08:02:14.657 UTC | 8 | 2021-02-11 06:34:53.8 UTC | 2019-01-06 18:51:51.643 UTC | null | -1 | null | 4,957,874 | null | 1 | 26 | apache-spark|dataframe|apache-spark-sql | 60,987 | <p>It's the <a href="https://issues.apache.org/jira/browse/SPARK-15565" rel="noreferrer">SPARK-15565 issue in Spark 2.0 on Windows</a> with a simple solution (that appears to be <a href="https://github.com/apache/spark/commit/c17272902c95290beca274ee6316a8a98fd7a725" rel="noreferrer">part of Spark's codebase</a> that may soon be released as 2.0.2 or 2.1.0).</p>
<p>The solution in Spark 2.0.0 is to set <code>spark.sql.warehouse.dir</code> to some properly-referenced directory, say <code>file:///c:/Spark/spark-2.0.0-bin-hadoop2.7/spark-warehouse</code> that uses <code>///</code> (triple slashes).</p>
<p>Start <code>spark-shell</code> with <code>--conf</code> argument as follows:</p>
<pre><code>spark-shell --conf spark.sql.warehouse.dir=file:///c:/tmp/spark-warehouse
</code></pre>
<p>Or create a <code>SparkSession</code> in your Spark application using the new fluent builder pattern as follows:</p>
<pre><code>import org.apache.spark.sql.SparkSession
SparkSession spark = SparkSession
.builder()
.config("spark.sql.warehouse.dir", "file:///c:/tmp/spark-warehouse")
.getOrCreate()
</code></pre>
<p>Or create <code>conf/spark-defaults.conf</code> with the following content:</p>
<pre><code>spark.sql.warehouse.dir file:///c:/tmp/spark-warehouse
</code></pre> |
40,528,290 | How to implement max-font-size? | <p>I want to specify my font size using <code>vw</code>, as in</p>
<pre><code>font-size: 3vw;
</code></pre>
<p>However, I also want to limit the font size to say 36px. How can I achieve the equivalent of <code>max-font-size</code>, which does not exist--is the only option to use media queries?</p> | 40,530,033 | 5 | 0 | null | 2016-11-10 13:00:35.3 UTC | 30 | 2022-02-23 02:42:02.093 UTC | 2016-11-10 15:30:17.023 UTC | null | 703,717 | user663031 | null | null | 1 | 93 | css|viewport-units | 125,238 | <p><code>font-size: 3vw;</code> means that the font size will be 3% of the viewport width. So when the viewport width is 1200px - the font size will be 3% * 1200px = 36px.</p>
<p>So a max-font-size of 36px can be easily implemented using a single media query to override the default 3vw font-size value.</p>
<h2><a href="http://codepen.io/danield770/pen/eBJpzz" rel="noreferrer">Codepen demo</a> (Resize Browser)</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
font-size: 3vw;
}
@media screen and (min-width: 1200px) {
div {
font-size: 36px;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>hello</div></code></pre>
</div>
</div>
<hr></p>
<h1>Update: With the new CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/min" rel="noreferrer">min() function</a>, we can simplify the above code - without using media queries (<a href="https://caniuse.com/#feat=css-math-functions" rel="noreferrer">caniuse</a>)</h1>
<pre><code>div {
font-size: min(3vw, 36px);
}
</code></pre>
<p>In the above example, the font-size will be at most 36px, but will decrease to 3vw if the the viewport is less than 1200px wide (where 3vw computes to a value less than 36px )</p>
<hr>
<p>That being said, using viewport units for <code>font-size</code> in the above way is problematic because when the viewport width is much smaller - say 320px - then the rendered font size will become 0.03 x 320 = 9.6px which is very (too) small. </p>
<p>In order to overcome this problem, I can recommend using a technique called <a href="https://css-tricks.com/snippets/css/fluid-typography/" rel="noreferrer">Fluid Type</a> AKA <a href="https://blog.typekit.com/2016/08/17/flexible-typography-with-css-locks/" rel="noreferrer">CSS Locks</a>.</p>
<blockquote>
<p>A CSS lock is a specific kind of CSS value calculation where:</p>
<ul>
<li>there is a minimum value and a maximum value, </li>
<li>and two breakpoints (usually based on the viewport width), </li>
<li>and between those breakpoints, the actual value goes linearly from the minimum to the maximum.</li>
</ul>
</blockquote>
<p>So let's say we want to apply the above technique such that the minimum font-size is 16px at a viewport width of 600px or less, and will increase linearly until it reaches a maximum of 32px at a viewport width of 1200px.</p>
<p>This can be represented as follows (see <a href="https://blog.typekit.com/2016/08/17/flexible-typography-with-css-locks/" rel="noreferrer">this CSS-tricks article</a> for more details):</p>
<pre><code>div {
font-size: 16px;
}
@media screen and (min-width: 600px) {
div {
font-size: calc(16px + 16 * ((100vw - 600px) / 600));
}
}
@media screen and (min-width: 1200px) {
div {
font-size: 32px;
}
}
</code></pre>
<p>Alternatively, we could use <a href="https://www.sassmeister.com/gist/7f22e44ace49b5124eec" rel="noreferrer">this SASS mixin</a> which does all of the math for us so that the CSS would look something like this:</p>
<pre><code>/*
1) Set a min-font-size of 16px when viewport width < 600px
2) Set a max-font-size of 32px when viewport width > 1200px and
3) linearly increase the font-size from 16->32px
between a viewport width of 600px-> 1200px
*/
div {
@include fluid-type(font-size, 600px, 1200px, 16px, 32px);
}
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>// ----
// libsass (v3.3.6)
// ----
// =========================================================================
//
// PRECISE CONTROL OVER RESPONSIVE TYPOGRAPHY FOR SASS
// ---------------------------------------------------
// Indrek Paas @indrekpaas
//
// Inspired by Mike Riethmuller's Precise control over responsive typography
//
//
// `strip-unit()` function by Hugo Giraudel
//
// 11.08.2016 Remove redundant `&` self-reference
// 31.03.2016 Remove redundant parenthesis from output
// 02.10.2015 Add support for multiple properties
// 24.04.2015 Initial release
//
// =========================================================================
@function strip-unit($value) {
@return $value / ($value * 0 + 1);
}
@mixin fluid-type($properties, $min-vw, $max-vw, $min-value, $max-value) {
@each $property in $properties {
#{$property}: $min-value;
}
@media screen and (min-width: $min-vw) {
@each $property in $properties {
#{$property}: calc(#{$min-value} + #{strip-unit($max-value - $min-value)} * (100vw - #{$min-vw}) / #{strip-unit($max-vw - $min-vw)});
}
}
@media screen and (min-width: $max-vw) {
@each $property in $properties {
#{$property}: $max-value;
}
}
}
// Usage:
// ======
// /* Single property */
// html {
// @include fluid-type(font-size, 320px, 1366px, 14px, 18px);
// }
// /* Multiple properties with same values */
// h1 {
// @include fluid-type(padding-bottom padding-top, 20em, 70em, 2em, 4em);
// }
////////////////////////////////////////////////////////////////////////////
div {
@include fluid-type(font-size, 600px, 1200px, 16px, 32px);
}
@media screen and (max-width: 600px) {
div {
font-size: 16px;
}
}
@media screen and (min-width: 1200px) {
div {
font-size: 36px;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Responsive Typography technique known as Fluid Type or CSS Locks.
Resize the browser window to see the effect.
</div></code></pre>
</div>
</div>
</p>
<p><a href="https://codepen.io/danield770/pen/zdPrWz" rel="noreferrer">Codepen Demo</a></p>
<p><hr></p>
<h1>Update: We can use the new <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/clamp" rel="noreferrer">clamp() CSS function</a> (<a href="https://caniuse.com/#feat=mdn-css_types_clamp" rel="noreferrer">caniuse</a>) to refactor the above code to simply:</h1>
<pre><code>div {
font-size: clamp(16px, 3vw, 32px);
}
</code></pre>
<p>see <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/clamp#Setting_a_minimum_and_max_size_for_a_font" rel="noreferrer">MDN</a>:</p>
<blockquote>
<p>clamp() allows you to set a font-size that grows with the size of the
viewport, but doesn't go below a minimum font-size or above a maximum
font-size. It has the same effect as the code in Fluid Typography but
in one line, and without the use of media queries.</p>
</blockquote>
<pre><code>p { font-size: clamp(1rem, 2.5vw, 1.5rem); }
<p>
If 2.5vw is less than 1rem, the font-size will be 1rem.
If 2.5vw is greater than 1.5rem, the font-size will be 1.5rem.
Otherwise, it will be 2.5vw.
</p>
</code></pre>
<p>--
<hr></p>
<h2>Further Reading</h2>
<p><a href="https://css-tricks.com/snippets/css/fluid-typography/" rel="noreferrer">Fluid Typography</a></p>
<p><a href="https://css-tricks.com/how-do-you-do-max-font-size-in-css/" rel="noreferrer">How Do You Do max-font-size in CSS?</a></p>
<p><a href="https://www.smashingmagazine.com/2017/05/fluid-responsive-typography-css-poly-fluid-sizing/" rel="noreferrer">Fluid Responsive Typography With CSS Poly Fluid Sizing</a></p>
<p><a href="https://www.madebymike.com.au/writing/non-linear-interpolation-in-css/" rel="noreferrer">Non-linear interpolation in CSS</a></p> |
49,843,670 | When you run jest --coverage, what does the Branches column do/mean? | <p>I ran my tests and this is what I received:</p>
<p><code>---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 0 | 100 | 100 | |
Search | 100 | 100 | 100 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
SearchResults | 100 | 0 | 100 | 100 | |
index.js | 100 | 0 | 100 | 100 | 4 |
---------------|----------|----------|----------|----------|-------------------|
Test Suites: 2 passed, 2 total
Tests: 5 passed, 5 total
Snapshots: 1 passed, 1 total
Time: 4.678s
</code>
I've changed something and now I have 0% on Branch column but I don't know what it means in order to improve it.</p> | 49,844,939 | 2 | 0 | null | 2018-04-15 15:33:41.083 UTC | 1 | 2022-07-14 02:20:45.94 UTC | 2018-04-17 21:44:06.103 UTC | null | 168,143 | null | 6,333,692 | null | 1 | 44 | javascript|reactjs|unit-testing|testing|jestjs | 18,223 | <p>Conditional statements create branches of code which may not be executed (e.g. if/else). This metric tells you how many of your branches have been executed.</p> |
53,553,523 | TypeORM subqueries | <p>Based on typeORM <a href="http://typeorm.io/#/select-query-builder/using-subqueries" rel="noreferrer">docs</a> on using subqueries, there are explained how to create subqueries.
Example:</p>
<pre><code>const qb = await getRepository(Post).createQueryBuilder("post");
const posts = qb
.where("post.title IN " + qb.subQuery().select("user.name").from(User, "user").where("user.registered = :registered").getQuery())
.setParameter("registered", true)
.getMany();
</code></pre>
<p>But there is no equivalent as to what the SQL would be.</p>
<p>Supposed that I have the query which contains subqueries like the following:</p>
<pre><code>SELECT a, TO_CHAR (MAX (jointable.f), 'MON YYYY') as f,
t3.c, t3.d, t1.e
FROM table1 t1
LEFT JOIN table2 t2 ON t2.e = t1.e
JOIN table3 t3 ON t3.d = t2.d
JOIN
(SELECT f, t4.g, t5.e, t6.h
FROM table4 t4
JOIN table5 t5 ON t4.g = t5.g
JOIN table6 t6 ON t6.g = t4.g
AND (t6.i = 2
OR (t6.i = 1 AND j = 1)
)
WHERE t4.k = 4
) jointable ON t1.e = jointable.e
WHERE jointable.h = :h
AND(:d = 3 OR
t3."d" = :d
)
GROUP BY a, t3.c, t3.d, t1.e
ORDER BY a ASC
</code></pre>
<p>How should I use the typeORM query builder function for the SQL query above?</p>
<p>Assuming that I had created entities related to all table being used on the query above.</p> | 53,556,477 | 1 | 0 | null | 2018-11-30 08:03:59.26 UTC | 5 | 2019-10-23 14:45:02.393 UTC | 2019-10-23 14:45:02.393 UTC | null | 263,900 | null | 3,654,837 | null | 1 | 16 | sql|oracle|typeorm|typeorm-datamapper | 44,562 | <p>I hope this answer could help others to use TypeORM subquery.</p>
<pre><code>const subquery = await getManager()
.createQueryBuilder(table4, 't4')
.select('"t4".f')
.addSelect('"t4".g')
.addSelect('"t5".e')
.addSelect('"t6".h')
.innerJoin(table5, 't5', '"t4".g = "t5".g')
.innerJoin(table6, 't6', '"t6".g = "t4".g')
.where('"t4".k = 4 AND ("t6".i = 2 OR ("t6".i = 1 AND "t6".j = 1))');
model = await getManager()
.createQueryBuilder(table1, 't1')
.select('"t1".a')
.addSelect("TO_CHAR (MAX (jointable.f), 'MON YYYY')", 'f')
.addSelect('"t3".c')
.addSelect('"t3".d')
.addSelect('"t1".e')
.leftJoin('table2', 't2', '"t2".e = "t1".e')
.innerJoin(table3, 't3', '"t3".d = "t2".d')
.innerJoin('('+subquery.getQuery()+')', 'jointable', '"t1".e = jointable.e')
.where('jointable.h = :h AND (:d = 3 OR "t3".d = :d)',
{ h: h, d: d })
.groupBy('"t1".a, "t3".c, "t3".d, "t1".e')
.orderBy('"t1".a', 'ASC')
.getRawMany();
</code></pre>
<p>I was using <code>'('+subquery.getQuery()+')'</code> for getting the subquery select query as an equivalent to</p>
<blockquote>
<p>(SELECT f, t4.g, t5.e, t6.h ....</p>
<p>......</p>
<p>.... ) jointable ON t1.e = jointable.e</p>
</blockquote>
<p>Based on what I understand:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/565620/difference-between-join-and-inner-join"><code>Join</code> actually</a> <a href="https://softwareengineering.stackexchange.com/questions/206035/join-vs-inner-join-and-full-outer-join">is equal to <code>inner join</code></a></p>
</li>
<li><p><code>.select</code> is and equivalent of <code>select</code> in SQL. You could also add
<a href="https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#what-are-aliases-for" rel="noreferrer"><code>aliases</code></a> (<a href="https://www.dofactory.com/sql/alias" rel="noreferrer">as in SQL</a>).</p>
</li>
<li><p><code>.addSelect</code> is similar to <code>, in select</code></p>
</li>
<li><p><a href="https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#getting-values-using-querybuilder" rel="noreferrer">There are two types of results you can get using select query
builder: entities or raw results</a>. To describe whether you want
the data as entities (<code>getOne</code> and <code>getMany</code>) or what it
is(<code>getRawOne</code> and <code>getRawMany</code>).</p>
</li>
</ul> |
2,591,715 | Deploying Django (fastcgi, apache mod_wsgi, uwsgi, gunicorn) | <p>Can someone explain the difference between apache mod_wsgi in daemon mode and django fastcgi in threaded mode. They both use threads for concurrency I think.
<strong>Supposing that I'm using nginx as front end to apache mod_wsgi.</strong></p>
<p><strong>UPDATE:</strong></p>
<p>I'm comparing django built in fastcgi(./manage.py method=threaded maxchildren=15) and mod_wsgi in 'daemon' mode(WSGIDaemonProcess example threads=15). They both use threads and acquire GIL, am I right?</p>
<p><strong>UPDATAE 2:</strong></p>
<p>So if they both are similar, is there any benefits of apache mod_wsgi against fastcgi. I see such pros of fastcgi:</p>
<ul>
<li>we don't need apache</li>
<li>we consume less RAM</li>
<li>I noticed that fastcgi has lesser overhead</li>
</ul>
<p><strong>UPDATAE 3:</strong></p>
<p>I'm now happy with nginx + uwsgi.</p>
<p><strong>UPDATAE 4:</strong></p>
<p>I'm now happy with nginx + gunicorn :)</p> | 2,591,927 | 1 | 0 | null | 2010-04-07 10:46:42.033 UTC | 11 | 2011-11-25 07:51:38.517 UTC | 2011-11-25 07:51:38.517 UTC | null | 198,418 | null | 198,418 | null | 1 | 17 | python|django|deployment|fastcgi|mod-wsgi | 9,084 | <p>Neither have to use threads to be able to handle concurrent requests. It depends on how you configure them. You can use multiple processes where each is single threaded if you want.</p>
<p>For more background on mod_wsgi process/threading models see:</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading" rel="noreferrer">http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading</a></p>
<p>The models are similar albeit that mod_wsgi handles process management itself. What happens in FASTCGI as far as process management depends on what FASTCGI hosting mechanism you are using and you don't say what that is.</p>
<p>Another difference is that FASTCGI still needs a separate FASTCGI to WSGI bridge such as flup where as mod_wsgi doesn't need any sort of bridge as implements WSGI interface natively.</p>
<p>Finally, FASTCGI process are an exec/fork of some supervisor process or the web server, dependent on hosting mechanism. In mod_wsgi the processes are a fork only of Apache parent process. In general this doesn't matter too much but does have some implications.</p>
<p>There are other differences but they arise more because mod_wsgi offers a lot more functionality and configurability than a FASTCGI hosting mechanism does.</p>
<p>Anyway, the question is a bit vague, can you be more specific about what it is you are wanting to know or contrast between the two and why? Answer can then perhaps be targeted better.</p> |
47,710,805 | laravel APi resource Call to undefined method Illuminate\Database\Query\Builder::mapInto() | <p>i have Post and User model with one to one relation and it works good:</p>
<pre><code>//User.php
public function post(){
return $this->hasOne(Post::class);
}
// Post.php
public function user() {
return $this->belongsTo(User::class);
}
</code></pre>
<p>now i create API resources:</p>
<pre><code>php artisan make:resource Post
php artisan make:resource User
</code></pre>
<p>I need to return all post with an api call then i set my route:</p>
<pre><code>//web.php: /resource/posts
Route::get('/resource/posts', function () {
return PostResource::collection(Post::all());
});
</code></pre>
<p>this is my Posts resource class:</p>
<pre><code><?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
use App\Http\Resources\User as UserResource;
class Posts extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'bodys' => $this->body,
'users' => UserResource::collection($this->user),
'published' => $this->published,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
</code></pre>
<p>this is the error: </p>
<pre><code>Call to undefined method Illuminate\Database\Query\Builder::mapInto()
</code></pre>
<p>if i remove:</p>
<pre><code>'users' => UserResource::collection($this->user),
</code></pre>
<p>it's work but i need to include relations in my api json, i have read and followed the doc at <a href="https://laravel.com/docs/5.5/collections" rel="noreferrer">https://laravel.com/docs/5.5/collections</a>.</p>
<p>this is my User resource class:</p>
<p>```
<pre><code>namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class User extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'user_id' => $this->user_id,
'name' => $this->name,
'lastname' => $this->lastname,
'email' => $this->email
];
}
}
</code></pre>
<p>any ideas where am i wrong?</p> | 47,710,930 | 4 | 0 | null | 2017-12-08 08:59:46.067 UTC | 3 | 2022-09-22 17:07:14.677 UTC | null | null | null | null | 3,469,806 | null | 1 | 50 | laravel|api|laravel-5.5 | 46,870 | <p>The problem is that you use <code>UserResource::collection($this->user)</code> and you have just one element not a collection so you can replace it with <code>new UserResource($this->user)</code> like this :</p>
<pre><code>return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'bodys' => $this->body,
'users' => new UserResource($this->user),
'published' => $this->published,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
</code></pre> |
38,837,341 | Javascript array push only if value not null | <p>I'm wondering if, and if how the following thing is working:</p>
<p>I have an array defined like the following:</p>
<pre><code>var array = [
{number: '1', value: 'one', context: 'someContext'},
{number: '2', value: 'two', context: 'anotherContext'},
...
]
</code></pre>
<p>What I'm currently doing is pushing the elements into the array, so <code>array.push({number: '1', value: 'one', context: 'someContext'});</code> and so on, with every array element. </p>
<p>Now this thing is extended: Say there's another key called 'content'. This key has a appropriate value, that is either undefined or a string. Now the question is: If I put the pushing in a function like this:</p>
<pre><code>push(number, value, context, content) {
array.push({
number: number,
value: value,
context: context,
content: content
})
}
</code></pre>
<p>Is there anyway, I can make sure, that the key content is only added to the element, if the content (the function gets as parameter) is not null. </p>
<p>Of course I can modify function like that:</p>
<pre><code>push(number, value, context, content) {
if(!content) {
array.push({
number: number,
value: value,
context: context,
content: content
})
} else {
array.push({
number: number,
value: value,
context: context
})
}
}
</code></pre>
<p>But the question is, if there is anyway to do this in the push function. I also thought about something like</p>
<pre><code>array.push({
number: number,
value: value,
context: context,
content? content: content
})
</code></pre>
<p>So it would only be inserted if content is defined, but does this work, it didn't seem like, but maybe theres a mistake in my code.</p> | 38,837,457 | 4 | 2 | null | 2016-08-08 19:46:18.927 UTC | 3 | 2019-01-14 14:07:25.637 UTC | 2018-08-24 00:41:40.307 UTC | null | 3,211,932 | null | 5,638,730 | null | 1 | 13 | javascript|arrays|if-statement | 77,544 | <p>If the objective isn't just to make code shorter, the most readable would be something like this, where you create the object, add the property if there is a value, and then push the object to the array.</p>
<pre><code>push(number, value, context, content) {
var o = {
number : number,
value : value,
context : context
}
if (content !== null) o.content = content;
array.push(o);
);
</code></pre>
<p>Here's an ES6 way to construct the object directly inside <code>Array.push</code>, and filter any that has <code>null</code> as a value.</p>
<pre><code>function push(...arg) {
array.push(['number','value','context','content'].reduce((a,b,i)=> {
if (arg[i] !== null) a[b]=arg[i]; return a;
}, {}))
}
</code></pre> |
31,546,081 | Laravel 5 Querying with relations causes "Call to a member function addEagerConstraints() on null" error | <p>I have been trying to create a simple user management system but keep on hitting road blocks when it comes to querying relations. For example I have <strong>users</strong> and <strong>roles</strong> and whenever I try to make a query for all users and their roles I get an error. The one in the title is only the latest one I've encountered.</p>
<p>My User and Role Models look like this:</p>
<pre><code>class Role extends Model
{
public function users()
{
$this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');
}
}
</code></pre>
<hr>
<pre><code>class User extends Model
{
public function roles()
{
$this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}
}
</code></pre>
<p>My migration table for many-to-many relationship between the two looks like this:</p>
<pre><code>public function up()
{
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable(); //fk => users
$table->integer('role_id')->unsigned()->nullable(); //fk => roles
$table->foreign('fk_user_role')->references('id')->on('users')->onDelete('cascade');
$table->foreign('fk_role_user')->references('id')->on('roles')->onDelete('cascade');
});
}
</code></pre>
<p>And then I try to get all records with their relation in a controller:</p>
<pre><code>public function index()
{
$users = User::with('roles')->get();
return $users;
}
</code></pre>
<p>So I need another pair of eyes to tell me what is it I am missing here?</p> | 31,546,352 | 4 | 0 | null | 2015-07-21 17:44:50.227 UTC | 6 | 2021-06-07 14:07:30.713 UTC | 2017-02-14 12:42:38.953 UTC | null | 1,594,915 | null | 1,347,153 | null | 1 | 80 | php|mysql|laravel|laravel-5|eloquent | 64,172 | <p>You are missing <strong>return</strong> statements in the methods that define relations. They need to return relation definition.</p>
<p>Replace</p>
<pre><code>public function roles()
{
$this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}
</code></pre>
<p>With</p>
<pre><code>public function roles()
{
return $this->belongsToMany('\App\Role', 'role_user', 'user_id', 'role_id');
}
</code></pre> |
6,304,773 | How to get X509Certificate from certificate store and generate xml signature data? | <p>How can I get X509Certificate from certificate store and then generate XML SignatureData in .net C#?</p> | 6,742,137 | 1 | 0 | null | 2011-06-10 09:57:31.107 UTC | 6 | 2019-07-02 03:51:41.407 UTC | 2011-08-05 15:05:54.36 UTC | null | 680,925 | null | 600,221 | null | 1 | 26 | c#|.net|xml|x509certificate|xml-signature | 69,269 | <p>As far as I know, certificates are not saved by XML Format , you should combine it by yourself.</p>
<p>Is this what you want ?</p>
<pre><code> static void Main(string[] args)
{
X509Certificate2 cer = new X509Certificate2();
cer.Import(@"D:\l.cer");
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Certificates.Add(cer);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName, "My Cert's Subject Name", false);
if (cers.Count>0)
{
cer = cers[0];
};
store.Close();
}
</code></pre> |
54,357,468 | How to set build and version number of Flutter app | <p>How do you set the version name and version code of a Flutter app without having to go into the Android and iOS settings?</p>
<p>In my pubspec.yaml I have</p>
<pre><code>version: 2.0.0
</code></pre>
<p>but I don't see a place for the build number.</p> | 54,357,469 | 7 | 0 | null | 2019-01-25 00:39:13.733 UTC | 20 | 2022-09-08 06:11:52.783 UTC | 2020-10-31 05:44:39.537 UTC | user10563627 | null | null | 3,681,880 | null | 1 | 73 | android|ios|flutter|version | 85,035 | <h2>Setting the version and build number</h2>
<p>You can update both the version name and the version code number in the same place in <em>pubspec.yaml</em>. Just separate them with a <code>+</code> sign. For example:</p>
<pre><code>version: 2.0.0+8
</code></pre>
<p>This means</p>
<ul>
<li>The version name is <code>2.0.0</code></li>
<li>The version code is <code>8</code></li>
</ul>
<p>This is described in the documentation of a new project (but you might have deleted that if you are working on an old project):</p>
<blockquote>
<p>The following defines the version and build number for your application.
A version number is three numbers separated by dots, like 1.2.43
followed by an optional build number separated by a +.
Both the version and the builder number may be overridden in flutter
build by specifying --build-name and --build-number, respectively.
Read more about versioning at semver.org.</p>
</blockquote>
<blockquote>
<p><code>version: 1.0.0+1</code></p>
</blockquote>
<h2>Re-enabling auto versioning</h2>
<p>If your Flutter versioning is not automatically updating anymore, see <a href="https://stackoverflow.com/a/63914373/3681880">this answer</a> for how to fix it.</p>
<h2>See also:</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/53672171/how-to-get-build-and-version-number-of-flutter-app">How to get build and version number of Flutter app</a></li>
</ul> |
28,524,231 | Laravel array to json format | <p>So I'm trying to convert a Laravel array into <code>json</code> so I can then manipulate it through javascript. Im not sure how this is achieved correctly. Here is the code, so far</p>
<pre><code>@foreach ($posts as $post)
<div class="row">
<div class="col-md-8">
<div class="row">
<div class="col-md-8 tag">
<h4><strong><a href="{{{ $post>postName }}}">#{{String::title($posts->postName) }}</a></strong></h4>
</div>
</div>
<!-- ./ post title -->
</div>
</div>
<hr />
@endforeach
<script type="text/javascript">
var data = "{{ ($posts) }}"; // ??
console.log(data);
</script>
</code></pre> | 28,524,412 | 5 | 0 | null | 2015-02-15 08:19:35.907 UTC | 2 | 2019-09-06 11:44:22.17 UTC | null | null | null | null | 1,477,957 | null | 1 | 7 | javascript|php|html|laravel | 52,259 | <p>You could return an json_encoded array from the controller like so:</p>
<pre><code>public function index()
{
$posts = Post::all();
$json = json_encode($posts);
return View::make('posts.index', compact('posts', 'json'));
}
</code></pre>
<p>Which you then can work on in your view like you'd like:</p>
<pre><code><script type="text/javascript">
var data = {{ $json }};
console.log(data);
</script>
</code></pre>
<p>Also, if you have sensitive fields on your post model, you should exclude these in the model class to prevent them to show in your javascript inspector:</p>
<pre><code>class Post extends \Eloquent {
...
protected $hidden = array(
'id',
'created_at',
'updated_at'
);
...
}
</code></pre> |
25,209,073 | Sending multiple responses with the same response object in Express.js | <p>I have a long running process which needs to send data back at multiple stages. Is there some way to send back multiple responses with <a href="http://expressjs.com/" rel="noreferrer">express.js</a></p>
<pre><code>res.send(200, 'hello')
res.send(200, 'world')
res.end()
</code></pre>
<p>but when I run <code>curl -X POST localhost:3001/helloworld</code> all I get is <code>hello</code></p>
<p>How can I send multiple responses or is this not possible to do with express?</p> | 25,209,191 | 4 | 0 | null | 2014-08-08 17:32:16.12 UTC | 10 | 2020-02-26 10:17:11.867 UTC | null | null | null | null | 1,470,897 | null | 1 | 18 | javascript|node.js|express | 41,766 | <p>Use <code>res.write()</code>.</p>
<p><code>res.send()</code> already makes a call to <code>res.end()</code>, meaning you can't write to res anymore after a call to res.send (meaning also your <code>res.end()</code> call was useless).</p>
<p>EDIT: It is a Node.js internal function. <a href="https://nodejs.org/dist/latest-v13.x/docs/api/http.html#http_response_write_chunk_encoding_callback" rel="noreferrer">See the documentation here</a></p> |
25,407,931 | Prevent indent when formatting CSS | <p>In Visual Studio 2013 when I format my CSS code (<kbd>Ctrl</kbd>+<kbd>K</kbd>+<kbd>F</kbd>) it will sometimes indent my CSS properties into a hierarchy.</p>
<p>For example:</p>
<pre class="lang-css prettyprint-override"><code>.a { color:red; }
.a .b {color:blue; }
</code></pre>
<p>Becomes:</p>
<pre class="lang-css prettyprint-override"><code>.a {
color:red;
}
.a .b {
color:blue;
}
</code></pre>
<p>When I would prefer:</p>
<pre class="lang-css prettyprint-override"><code>.a {
color:red;
}
.a .b {
color:blue;
}
</code></pre>
<p>Is there a way of modifying Visual Studio to prevent this indentation?</p> | 25,412,948 | 1 | 0 | null | 2014-08-20 14:11:34.397 UTC | 3 | 2019-04-03 18:53:24.11 UTC | 2019-04-03 18:53:24.11 UTC | null | 1,548,895 | Curt | 370,103 | null | 1 | 30 | css|visual-studio|visual-studio-2013 | 2,412 | <p>Yes, you can set a preference for this from the Tools, Options menu. </p>
<p>Drill down in <code>Text Editor</code> to <code>CSS</code>, and under <code>Advanced</code>, turn <code>Hierarchical Indentation</code> off:</p>
<p><img src="https://i.stack.imgur.com/zKYXV.png" alt="enter image description here"></p> |
44,841,215 | Auto fix TSLint Warnings | <pre><code> [64, 1]: space indentation expected
[15, 27]: Missing semicolon
[109, 36]: missing whitespace
[111, 24]: missing whitespace
[70, 1]: Consecutive blank lines are forbidden
</code></pre>
<p>I keep getting warnings like these from TSLint. There are huge amount of warnings, and it will be very difficult to fix it manually.</p>
<p>I was looking for a way which can <strong>auto-fix</strong> most of the warnings.</p> | 44,850,320 | 6 | 1 | null | 2017-06-30 07:42:30.543 UTC | 7 | 2020-08-04 08:53:31.393 UTC | 2018-03-20 19:47:34.633 UTC | null | 165,713 | null | 6,429,598 | null | 1 | 82 | angular|typescript|warnings|tslint | 61,450 | <p>You can use the <a href="https://palantir.github.io/tslint/usage/cli/#cli-usage" rel="noreferrer"><code>--fix</code> option</a> of TSLint to automatically fix most warnings. This might look something like this in a common use case:</p>
<pre><code>tslint --fix -c ./config/tslint.json 'src/**/*{.ts,.tsx}'
</code></pre>
<p>Keep in mind that this will overwrite your source code. While this is safe 99.9% of the time, I recommend the following workflow:</p>
<ol>
<li>Commit the changes you have made to your code</li>
<li>Run TSLint with the <code>--fix</code> flag like above</li>
<li>Quickly review the changes TSLint has made</li>
<li>Make a new commit with these changes, or simply amend them to your previous commit</li>
</ol>
<p>This way, you'll never be taken surprise by a rogue autocorrection gone wrong.</p> |
7,124,483 | Difference between subprojects and submodules in Git? | <p>In Git, is there a difference between a "submodule" (as created and managed by the git submodule command) and a "subproject" (literally just one Git repository that you put inside another Git repository), and if so, what is it?</p>
<p>All the documentation I've been able to find about this is rather ambiguous (and in some cases, contradictory). My suspicion is that there is no difference, but I figure I ought to confirm that and leave a question for Git newbies to find.</p> | 7,124,607 | 1 | 0 | null | 2011-08-19 16:17:04.71 UTC | 18 | 2021-07-07 07:24:03.007 UTC | null | null | null | user597474 | null | null | 1 | 78 | git | 27,687 | <p>A <em>subproject</em> is a generic term for one of three types of nesting:</p>
<ul>
<li><strong>Submodules</strong> provide semi-fixed references from the superproject into subprojects and are integrated into git. It is best used when the subproject:
<ul>
<li>is developed by someone else, is not under the administrative control of the superproject and follows a different release cycle.</li>
<li>contains code shared between superprojects (especially when the intention is to propagate bugfixes and new features back to other superprojects).</li>
<li>separates huge and/or many files that would hurt performance of everyday git commands. </li>
</ul></li>
<li><strong>Subtrees</strong> causes the subproject repository to be imported into the superproject's repository to be a native part of the repository with full history, typically in a specific subdirectory of the superproject. </li>
<li><strong>Wrappers</strong>, which provide multi-repository management functionality to a superproject with associated subprojects.</li>
</ul>
<p><em><a href="https://git.wiki.kernel.org/index.php/SubprojectSupport" rel="noreferrer">Reference documentation</a></em></p> |
24,892,810 | Python 3.4 and 2.7: Cannot install numpy package for python 3.4 | <p>I am using Ubuntu 12.04 and want to use python 3.4 side by side with python 2.7.</p>
<p>The installation of python 3.4 worked properly. However, I cannot install the numpy package for python 3 (and as a consequence I can't install scipy, pandas etc.).</p>
<p>Using </p>
<pre><code> sudo pip3 install numpy
</code></pre>
<p>spits out the following error:</p>
<pre><code>File "numpy/core/setup.py", line 289, in check_types
"Cannot compile 'Python.h'. Perhaps you need to "\
SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.
</code></pre>
<p>Btw, I already have python-dev installed.</p>
<p>Moreover, installing numpy via </p>
<pre><code> sudo apt-get install python-numpy
</code></pre>
<p>does not work either since I already installed numpy for python 2.7 and the installer responds that numpy is already up to date.</p>
<p>What can I do? Thanks!</p> | 24,892,867 | 2 | 0 | null | 2014-07-22 16:26:58.177 UTC | 6 | 2020-07-07 22:31:14.71 UTC | 2018-02-12 09:42:10.21 UTC | null | 100,297 | null | 2,396,598 | null | 1 | 41 | python|numpy|ubuntu|pip|python-3.4 | 46,566 | <p>You have not installed the Python 3 <em>development package</em>. Install <code>python3.4-dev</code>:</p>
<pre><code>apt-get install python3.4-dev
</code></pre>
<p>The main package never includes the development headers; Debian (and by extension Ubuntu) package policy is to put those into a separate <code>-dev</code> package. To install <code>numpy</code> however, you need these files to be able to compile the extension.</p> |
2,719,173 | Change background color of android menu | <p>I'm trying to change the standard light grey to a light green. Seems that there is not a simple way to do this (through Android Themes, for example) but I have found a workaround as explained at this page: <a href="http://tinyurl.com/342dgn3" rel="noreferrer">http://tinyurl.com/342dgn3</a>. </p>
<p>The author seems disappeared, can someone help me integrating this code? I don't understand where I need to implement the <code>LayoutInflater</code> factory class. </p> | 6,211,536 | 3 | 4 | null | 2010-04-27 06:32:12.323 UTC | 7 | 2013-04-27 17:08:15.363 UTC | 2013-04-27 17:08:15.363 UTC | null | 321,354 | null | 321,354 | null | 1 | 19 | android|menu|background|layout-inflater | 92,341 | <p>When ur are inflating the menu call this setMenuBackground() method</p>
<pre><code>@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu,menu);
setMenuBackground();
return true;
}
</code></pre>
<p>and write this in the setMenuBackground() method</p>
<pre><code> protected void setMenuBackground(){
// Log.d(TAG, "Enterting setMenuBackGround");
getLayoutInflater().setFactory( new Factory() {
public View onCreateView(String name, Context context, AttributeSet attrs) {
if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
try { // Ask our inflater to create the view
LayoutInflater f = getLayoutInflater();
final View view = f.createView( name, null, attrs );
/* The background gets refreshed each time a new item is added the options menu.
* So each time Android applies the default background we need to set our own
* background. This is done using a thread giving the background change as runnable
* object */
new Handler().post( new Runnable() {
public void run () {
// sets the background color
view.setBackgroundResource( R.color.androidcolor);
// sets the text color
((TextView) view).setTextColor(Color.BLACK);
// sets the text size
((TextView) view).setTextSize(18);
}
} );
return view;
}
catch ( InflateException e ) {}
catch ( ClassNotFoundException e ) {}
}
return null;
}});
}
</code></pre> |
2,890,156 | How to bind collection to WPF:DataGridComboBoxColumn | <p>I have a simple object like:</p>
<pre><code>class Item
{
....
public String Measure { get; set; }
public String[] Measures {get; }
}
</code></pre>
<p>Which I am trying to bind to a DataGrid with two text columns and a combo box column.
For the combo box column, property Measure is the current selection and Measures the possible values.</p>
<p>My XAML is:</p>
<pre><code><DataGrid Name="recipeGrid" AutoGenerateColumns="False"
CellEditEnding="recipeGrid_CellEditEnding" CanUserAddRows="False"
CanUserDeleteRows="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Food" Width="Auto"
Binding="{Binding Food.Name}" />
<DataGridTextColumn Header="Quantity" IsReadOnly="False"
Binding="{Binding Quantity}" />
<DataGridComboBoxColumn Header="Measure" Width="Auto"
SelectedItemBinding="{Binding Path=Measure}"
ItemsSource="{Binding Path=Measures}" />
</DataGrid.Columns>
</DataGrid>
</code></pre>
<p>The text column are displayed just fine but the combobox is not - the values are not displayed at all. The binding error is:</p>
<blockquote>
<p>System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Measures; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=11497055); target property is 'ItemsSource' (type 'IEnumerable')</p>
</blockquote>
<p>How do I fix this?</p> | 2,896,276 | 3 | 0 | null | 2010-05-22 23:32:08.717 UTC | 3 | 2019-11-18 16:42:19.737 UTC | 2019-11-18 16:42:19.737 UTC | null | 285,795 | null | 165,656 | null | 1 | 21 | c#|wpf|datagrid | 39,121 | <p>The problem lies in that Columns does no inherit DataContext. </p>
<p>See more here <a href="https://stackoverflow.com/questions/502389/binding-in-a-wpf-data-grid-text-column">Binding in a WPF data grid text column</a></p>
<p>here <a href="http://blogs.msdn.com/vinsibal/archive/2008/12/17/wpf-datagrid-dynamically-updating-datagridcomboboxcolumn.aspx" rel="nofollow noreferrer">blogs.msdn.com/vinsibal/archive/2008/12/17/wpf-datagrid-dynamically-updating-datagridcomboboxcolumn.aspx</a></p>
<p>and here <a href="http://blogs.msdn.com/jaimer/archive/2008/11/22/forwarding-the-datagrid-s-datacontext-to-its-columns.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/jaimer/archive/2008/11/22/forwarding-the-datagrid-s-datacontext-to-its-columns.aspx</a></p> |
3,146,274 | Is it OK to use DYLD_LIBRARY_PATH on Mac OS X? And, what's the dynamic library search algorithm with it? | <p>I read some articles discouraging of the use of DYLD_LIBRARY_PATH, as the the path of dynamic library should be fixed using -install_name, @rpath, and @loader_path. </p>
<p>In terms of making a program that runs both on Linux and Mac OS X, DYLD_LIBRARY_PATH of Mac OS X does exactly what LD_LIBRARY_PATH of Linux. And, we can share (almost) the same make file that doesn't have the -install_name and @rpath. </p>
<ul>
<li>Is this OK to use DYLD_LIBRARY_PATH on Mac OS X?</li>
<li>What's the dynamic library search algorithm with Mac OS X when the binary can't find the dynamic library? current directory -> DYLD_LIBRARY_PATH directories ... ? </li>
</ul> | 3,172,515 | 3 | 1 | null | 2010-06-30 03:26:55.837 UTC | 30 | 2016-12-10 04:09:45.3 UTC | 2010-06-30 13:40:23.22 UTC | null | 260,127 | null | 260,127 | null | 1 | 76 | language-agnostic|macos|dynamic-linking|dll | 107,501 | <p>As you've noted, <code>DYLD_LIBRARY_PATH</code> behaves like <code>LD_LIBRARY_PATH</code> on other *nix. However, there is another environment variable you should look at called <code>DYLD_FALLBACK_LIBRARY_PATH</code>.</p>
<p>In general, these are (both on osx and linux) suggested only for development use as they can cause symbol lookup errors when you override with a library that does not have the same symbol table. A good example of this is when you attempt to override the default install of VecLib (e.g. blas lapack) with a custom install. This will cause symbol not found errors in applications linked to the system VecLib if <code>DYLD_LIBRARY_PATH</code> is set and the reverse (symbol lookup errors in custom applications) if it is not. This is due to the system blas/lapack not being a full implementation of the ATLAS libs.</p>
<p><code>DYLD_FALLBACK_LIBRARY_PATH</code> will not produce these problems.</p>
<p>When installing libraries to a non-standard location, <code>DYLD_FALLBACK_LIBRARY_PATH</code> is much more sane. This will look for symbols in libraries provided in the default paths and if the symbol is not found there, fall back to the specified path. </p>
<p>The benefit is that this process will not cause symbol lookup errors in applications compiled against the default libraries.</p>
<p>In general, when libraries are installed to non-standard locations absolute paths should be specified which negates the ambiguity of the dynamic lookup. </p> |
3,073,812 | Why PHP variables start with a $ sign symbol? | <p>Has anybody ever thought about this question. Why we must write <code>$var_name = value;</code> and not <code>var_name = value;</code>? Yes I know that it is the syntax rule that PHP uses, but why is it a <code>$</code> sign symbol?</p> | 3,073,818 | 4 | 4 | null | 2010-06-19 00:16:03.077 UTC | 6 | 2016-12-16 23:07:08.06 UTC | 2010-06-19 00:34:31.987 UTC | null | 218,196 | null | 282,887 | null | 1 | 38 | php|syntax|variables | 23,290 | <p>Because PHP was based on Perl which used <code>$</code>, though the symbols Perl used were meaningful and plenty used to indicate the data type, ( such as @ used to indicate an array ) PHP just has <code>$</code>.</p>
<p>PHP in its early stages was a simplistic version of Perl but over time incorporated more of Perl's features, though one may argue PHP was for a long time a simplistic primitive version of Perl since before PHP 5.3 it did not include features that have been around in other languages such as closures/namespacing.</p>
<p><a href="http://en.wikipedia.org/wiki/PHP" rel="noreferrer">http://en.wikipedia.org/wiki/PHP</a></p>
<p>Larry Wall, the creator of Perl, was inspired to use <code>$</code> from shell scripting: <a href="http://en.wikipedia.org/wiki/Sigil_%28computer_programming%29" rel="noreferrer">http://en.wikipedia.org/wiki/Sigil_%28computer_programming%29</a></p> |
31,883,657 | Customized ObjectMapper not used in test | <p>I am using the Spring Framework, version 4.1.6, with Spring web services and without Spring Boot. To learn the framework, I am writing a REST API and am testing to make sure that the JSON response received from hitting an endpoint is correct. Specifically, I am trying to adjust the <code>ObjectMapper</code>'s <code>PropertyNamingStrategy</code> to use the "lower case with underscores" naming strategy. </p>
<p>I am using <a href="https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring#without-spring-boot" rel="noreferrer">the method detailed on Spring's blog</a> to create a new <code>ObjectMapper</code> and add it to the list of converters. This is as follows:</p>
<pre><code>package com.myproject.config;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = jacksonBuilder();
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
return builder;
}
}
</code></pre>
<p>Then I run the following test (using JUnit, MockMvc, and Mockito) to verify my changes:</p>
<pre><code>package com.myproject.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// Along with other application imports...
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebConfig.class}, loader = AnnotationConfigWebContextLoader.class)
public class MyControllerTest {
@Mock
private MyManager myManager;
@InjectMocks
private MyController myController;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(this.myController).build();
}
@Test
public void testMyControllerWithNameParam() throws Exception {
MyEntity expected = new MyEntity();
String name = "expected";
String title = "expected title";
// Set up MyEntity with data.
expected.setId(1); // Random ID.
expected.setEntityName(name);
expected.setEntityTitle(title)
// When the MyManager instance is asked for the MyEntity with name parameter,
// return expected.
when(this.myManager.read(name)).thenReturn(expected);
// Assert the proper results.
MvcResult result = mockMvc.perform(
get("/v1/endpoint")
.param("name", name))
.andExpect(status().isOk())
.andExpect((content().contentType("application/json;charset=UTF-8")))
.andExpect(jsonPath("$.entity_name", is(name))))
.andExpect(jsonPath("$.entity_title", is(title)))
.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
}
</code></pre>
<p>However, this returns a response of:</p>
<pre><code>{"id": 1, "entityName": "expected", "entityTitle": "expected title"}
</code></pre>
<p>When I should get:</p>
<pre><code>{"id": 1, "entity_name": "expected", "entity_title": "expected title"}
</code></pre>
<p>I have an implemented WebApplicationInitializer that scans for the package:</p>
<pre><code>package com.myproject.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.scan("com.myproject.config");
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
servletContext.addListener(new ContextLoaderListener(ctx));
}
}
</code></pre>
<p>Using my debugger within IntelliJ, I can see that the builder is created and added, but somewhere down the line the resulting <code>ObjectMapper</code> is not actually used. I must be missing something, but all the examples I've managed to find don't seem to mention what that is! I've tried eliminating <code>@EnableWebMvc</code> and implementing <code>WebMvcConfigurationSupport</code>, using <code>MappingJackson2HttpMessageConverter</code> as a Bean, and setting <code>ObjectMapper</code> as a Bean to no avail.</p>
<p>Any help would be greatly appreciated! Please let me know if any other files are required.</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong> Was doing some more digging and found <a href="https://stackoverflow.com/questions/12514285/registrer-mappingjackson2httpmessageconverter-in-spring-3-1-2-with-jaxb-annotati">this</a>. In the link, the author appends <code>setMessageConverters()</code> before he/she builds MockMvc and it works for the author. Doing the same worked for me as well; however, I'm not sure if everything will work in production as the repositories aren't flushed out yet. When I find out I will submit an answer.</p>
<p><strong>EDIT 2:</strong> See answer.</p> | 32,098,439 | 4 | 0 | null | 2015-08-07 17:40:00.72 UTC | 8 | 2020-03-03 17:15:18.377 UTC | 2017-05-23 11:54:59.99 UTC | null | -1 | null | 5,202,851 | null | 1 | 43 | spring|spring-mvc|jackson | 39,621 | <p>I looked into understanding why this works the way that it did. To reiterate, the process of getting my customized ObjectMapper to work in my test (assuming MockMvc is being created as a standalone) is as follows:</p>
<ol>
<li>Create a <code>WebConfig</code> class that extends <code>WebMvcConfigurerAdapter</code>.</li>
<li>In the <code>WebConfig</code> class, create a new <code>@Bean</code> that returns a <code>MappingJackson2HttpMessageConverter</code>. This <code>MappingJackson2HttpMessageConverter</code> has the desired changes applied to it (in my case, it was passing it a <code>Jackson2ObjectMapperBuilder</code> with the <code>PropertyNamingStrategy</code> set to <code>CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES</code>.)</li>
<li>Also in the <code>WebConfig</code> class, <code>@Override</code> <code>configureMessageConverters()</code> and add the <code>MappingJackson2HttpMessageConverter</code> from (2) to the list of message converters.</li>
<li>In the test file, add a <code>@ContextConfiguration(classes = { WebConfig.class })</code> annotation to inform the test of your <code>@Bean</code>.</li>
<li>Use <code>@Autowired</code> to inject and access the <code>@Bean</code> defined in (2).</li>
<li>In the setup of <code>MockMvc</code>, use the <code>.setMessageConverters()</code> method and pass it the injected <code>MappingJackson2HttpMessageConverter</code>. The test will now use the configuration set in (2).</li>
</ol>
<p>The test file:</p>
<pre><code>package com.myproject.controller;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// Along with other application imports...
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebConfig.class})
public class MyControllerTest {
/**
* Note that the converter needs to be autowired into the test in order for
* MockMvc to recognize it in the setup() method.
*/
@Autowired
private MappingJackson2HttpMessageConverter jackson2HttpMessageConverter;
@Mock
private MyManager myManager;
@InjectMocks
private MyController myController;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders
.standaloneSetup(this.myController)
.setMessageConverters(this.jackson2HttpMessageConverter) // Important!
.build();
}
@Test
public void testMyControllerWithNameParam() throws Exception {
MyEntity expected = new MyEntity();
String name = "expected";
String title = "expected title";
// Set up MyEntity with data.
expected.setId(1); // Random ID.
expected.setEntityName(name);
expected.setEntityTitle(title)
// When the MyManager instance is asked for the MyEntity with name parameter,
// return expected.
when(this.myManager.read(name)).thenReturn(expected);
// Assert the proper results.
MvcResult result = mockMvc.perform(
get("/v1/endpoint")
.param("name", name))
.andExpect(status().isOk())
.andExpect((content().contentType("application/json;charset=UTF-8")))
.andExpect(jsonPath("$.entity_name", is(name))))
.andExpect(jsonPath("$.entity_title", is(title)))
.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
}
</code></pre>
<p>And the configuration file:</p>
<pre><code>package com.myproject.config;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(jackson2HttpMessageConverter());
}
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
Jackson2ObjectMapperBuilder builder = this.jacksonBuilder();
converter.setObjectMapper(builder.build());
return converter;
}
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
return builder;
}
}
</code></pre>
<p>Deploying my generated WAR file to Tomcat 7 in XAMPP shows that the naming strategy is being used correctly. The reason I believe that this works the way that it does is because with a standalone setup, a default set of message converters is always used unless otherwise specified. This can be seen in the comment for the <code>setMessageConverters()</code> function within StandAloneMockMvcBuilder.java (version 4.1.6, <code>\org\springframework\test\web\servlet\setup\StandaloneMockMvcBuilder.java</code>):</p>
<pre><code> /**
* Set the message converters to use in argument resolvers and in return value
* handlers, which support reading and/or writing to the body of the request
* and response. If no message converters are added to the list, a default
* list of converters is added instead.
*/
public StandaloneMockMvcBuilder setMessageConverters(HttpMessageConverter<?>...messageConverters) {
this.messageConverters = Arrays.asList(messageConverters);
return this;
}
</code></pre>
<p>Therefore, if MockMvc is not explicitly told about one's changes to the message converters during the building of the MockMvc, it will not use the changes.</p> |
32,064,375 | Magnet pattern and overloaded methods | <p>There is a significant difference in how Scala resolves implicit conversions from "Magnet Pattern" for non-overloaded and overloaded methods.</p>
<p>Suppose there is a trait <code>Apply</code> (a variation of a "Magnet Pattern") implemented as follows.</p>
<pre><code>trait Apply[A] {
def apply(): A
}
object Apply {
implicit def fromLazyVal[A](v: => A): Apply[A] = new Apply[A] {
def apply(): A = v
}
}
</code></pre>
<p>Now we create a trait <code>Foo</code> that has a single <code>apply</code> taking an instance of <code>Apply</code> so we can pass it any value of arbitrary type <code>A</code> since there an implicit conversion from <code>A => Apply[A]</code>.</p>
<pre><code>trait Foo[A] {
def apply(a: Apply[A]): A = a()
}
</code></pre>
<p>We can make sure it works as expected using REPL and <a href="https://gist.github.com/mpilquist/4ed3196e9ee4543c1847">this workaround to de-sugar Scala code</a>.</p>
<pre><code>scala> val foo = new Foo[String]{}
foo: Foo[String] = $anon$1@3a248e6a
scala> showCode(reify { foo { "foo" } }.tree)
res9: String =
$line21$read.foo.apply(
$read.INSTANCE.Apply.fromLazyVal("foo")
)
</code></pre>
<p>This works great, but suppose we pass a <em>complex expression</em> (with <code>;</code>) to the <code>apply</code> method.</p>
<pre><code>scala> val foo = new Foo[Int]{}
foo: Foo[Int] = $anon$1@5645b124
scala> var i = 0
i: Int = 0
scala> showCode(reify { foo { i = i + 1; i } }.tree)
res10: String =
$line23$read.foo.apply({
$line24$read.`i_=`($line24$read.i.+(1));
$read.INSTANCE.Apply.fromLazyVal($line24$read.i)
})
</code></pre>
<p>As we can see, an implicit conversion has been applied only on the last part of the complex expression (i.e., <code>i</code>), not to the whole expression. So, <code>i = i + 1</code> was strictly evaluated at the moment we pass it to an <code>apply</code> method, which is not what we've been expecting.</p>
<p>Good (or bad) news. We can make <code>scalac</code> to use the whole expression in the implicit conversion. So <code>i = i + 1</code> will be evaluated lazily as expected. To do so we (surprize, surprize!) we add an overload method <code>Foo.apply</code> that takes any type, but not <code>Apply</code>.</p>
<pre><code>trait Foo[A] {
def apply(a: Apply[A]): A = a()
def apply(s: Symbol): Foo[A] = this
}
</code></pre>
<p>And then.</p>
<pre><code>scala> var i = 0
i: Int = 0
scala> val foo = new Foo[Int]{}
foo: Foo[Int] = $anon$1@3ff00018
scala> showCode(reify { foo { i = i + 1; i } }.tree)
res11: String =
$line28$read.foo.apply($read.INSTANCE.Apply.fromLazyVal({
$line27$read.`i_=`($line27$read.i.+(1));
$line27$read.i
}))
</code></pre>
<p>As we can see, the entire expression <code>i = i + 1; i</code> made it under the implicit conversion as expected.</p>
<p>So my question is why is that? Why the scope of which an implicit conversion is applied depends on the fact whether or not there is an overloaded method in the class.</p> | 32,068,645 | 1 | 0 | null | 2015-08-18 05:42:56.653 UTC | 8 | 2015-08-18 09:31:58.83 UTC | 2015-08-18 06:16:52.367 UTC | null | 554,460 | null | 554,460 | null | 1 | 19 | scala|implicit | 1,771 | <p>Now, that is a tricky one. And it's actually pretty awesome, I didn't know that "workaround" to the "lazy implicit does not cover full block" problem. Thanks for that!</p>
<p>What happens is related to <em>expected types</em>, and how they affect type inference works, implicit conversions, and overloads.</p>
<h2>Type inference and expected types</h2>
<p>First, we have to know that type inference in Scala is bi-directional. Most of the inference works bottom-up (given <code>a: Int</code> and <code>b: Int</code>, infer <code>a + b: Int</code>), but some things are top-down. For example, inferring the parameter types of a lambda is top-down:</p>
<pre><code>def foo(f: Int => Int): Int = f(42)
foo(x => x + 1)
</code></pre>
<p>In the second line, after resolving <code>foo</code> to be <code>def foo(f: Int => Int): Int</code>, the type inferencer can tell that <code>x</code> must be of type <code>Int</code>. It does so <em>before</em> typechecking the lambda itself. It propagates type information from the function application down to the lambda, which is a parameter.</p>
<p>Top-down inference basically relies on the notion of <em>expected type</em>. When typechecking a node of the AST of the program, the typechecker does not start empty-handed. It receives an expected type from "above" (in this case, the function application node). When typechecking the lambda <code>x => x + 1</code> in the above example, the expected type is <code>Int => Int</code>, because we know what parameter type is expected by <code>foo</code>. This drives the type inference into inferring <code>Int</code> for the parameter <code>x</code>, which in turn allows to typecheck <code>x + 1</code>.</p>
<p>Expected types are propagated down certain constructs, e.g., blocks (<code>{}</code>) and the branches of <code>if</code>s and <code>match</code>es. Hence, you could also call <code>foo</code> with</p>
<pre><code>foo({
val y = 1
x => x + y
})
</code></pre>
<p>and the typechecker is still able to infer <code>x: Int</code>. That is because, when typechecking the block <code>{ ... }</code>, the expected type <code>Int => Int</code> is passed down to the typechecking of the last expression, i.e., <code>x => x + y</code>.</p>
<h2>Implicit conversions and expected types</h2>
<p>Now, we have to introduce implicit conversions into the mix. When typechecking a node produces a value of type <code>T</code>, but the expected type for that node is <code>U</code> where <code>T <: U</code> is false, the typechecker looks for an implicit <code>T => U</code> (I'm probably simplifying things a bit here, but the gist is still true). This is why your first example does not work. Let us look at it closely:</p>
<pre><code>trait Foo[A] {
def apply(a: Apply[A]): A = a()
}
val foo = new Foo[Int] {}
foo({
i = i + 1
i
})
</code></pre>
<p>When calling <code>foo.apply</code>, the expected type for the parameter (i.e., the block) is <code>Apply[Int]</code> (<code>A</code> has already been instantiated to <code>Int</code>). We can "write" this typechecker "state" like this:</p>
<pre><code>{
i = i + 1
i
}: Apply[Int]
</code></pre>
<p>This expected type is <em>passed down</em> to the last expression of the block, which gives:</p>
<pre><code>{
i = i + 1
(i: Apply[Int])
}
</code></pre>
<p>at this point, since <code>i: Int</code> and the expected type is <code>Apply[Int]</code>, the typechecker finds the implicit conversion:</p>
<pre><code>{
i = i + 1
fromLazyVal[Int](i)
}
</code></pre>
<p>which causes only <code>i</code> to be lazified.</p>
<h2>Overloads and expected types</h2>
<p>OK, time to throw overloads in there! When the typechecker sees an application of an overload method, it has much more trouble deciding on an expected type. We can see that with the following example:</p>
<pre><code>object Foo {
def apply(f: Int => Int): Int = f(42)
def apply(f: String => String): String = f("hello")
}
Foo(x => x + 1)
</code></pre>
<p>gives:</p>
<pre><code>error: missing parameter type
Foo(x => x + 1)
^
</code></pre>
<p>In this case, the failure of the typechecker to figure out an expected type causes the parameter type not to be inferred.</p>
<p>If we take your "solution" to your issue, we have a different consequence:</p>
<pre><code>trait Foo[A] {
def apply(a: Apply[A]): A = a()
def apply(s: Symbol): Foo[A] = this
}
val foo = new Foo[Int] {}
foo({
i = i + 1
i
})
</code></pre>
<p>Now when typechecking the block, the typechecker has <em>no expected type</em> to work with. It will therefore typecheck the last expression without expression, and eventually typecheck the whole block as an <code>Int</code>:</p>
<pre><code>{
i = i + 1
i
}: Int
</code></pre>
<p>Only now, with an already typechecked argument, does it try to resolve the overloads. Since none of the overloads conforms directly, it tries to apply an implicit conversion from <code>Int</code> to either <code>Apply[Int]</code> or <code>Symbol</code>. It finds <code>fromLazyVal[Int]</code>, which it applies <em>to the entire argument</em>. It does not push it inside the block anymore, giving:</p>
<pre><code>fromLazyVal({
i = i + 1
i
}): Apply[Int]
</code></pre>
<p>In this case, the whole block is lazified.</p>
<p>This concludes the explanation. To summarize, the major difference is the presence vs absence of an expected type when typechecking the block. With an expected type, the implicit conversion is pushed down as much as possible, down to just <code>i</code>. Without the expected type, the implicit conversion is applied a posteriori on the entire argument, i.e., the whole block.</p> |
56,730,412 | Change the default border color of TextFormField in FLUTTER | <p>Unable to change the default border color when TextFormField is not active. When TextFormField is not active this shows DarkGrey-Border color. So, how to change that.</p>
<p><a href="https://i.stack.imgur.com/VI1rW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VI1rW.png" alt="enter image description here"></a></p>
<pre><code>Theme(
data: new ThemeData(
primaryColor: Colors.red,
primaryColorDark: Colors.black,
),
child: TextFormField(
decoration: new InputDecoration(
labelText: "Enter Email",
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
//fillColor: Colors.green
),
validator: (val) {
if (val.length == 0) {
return "Email cannot be empty";
} else {
return null;
}
},
keyboardType: TextInputType.emailAddress,
style: new TextStyle(
fontFamily: "Poppins",
),
),
),
</code></pre> | 56,730,464 | 1 | 0 | null | 2019-06-24 05:40:10.883 UTC | 6 | 2019-06-24 05:46:51.413 UTC | 2019-06-24 05:46:51.413 UTC | null | 666,221 | null | 4,603,998 | null | 1 | 47 | flutter|dart|textfield|default|flutter-layout | 61,884 | <p>Use <code>enabledBorder</code> of the <code>InputDecoration</code>, don't forget you can also use the <code>focusedBorder</code>, like this :</p>
<pre><code>InputDecoration(
labelText: "Enter Email",
fillColor: Colors.white,
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.blue,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(
color: Colors.red,
width: 2.0,
),
),
)
</code></pre>
<p>Here you have more info: <a href="https://api.flutter.dev/flutter/material/InputDecoration/enabledBorder.html" rel="noreferrer">https://api.flutter.dev/flutter/material/InputDecoration/enabledBorder.html</a></p> |
36,461,174 | How do I disable all Roslyn Code Analyzers? | <p>I'm trying to work with a large opensource project that has a handful of Roslyn Code Analyzers. When I open the solution Visual Studio uses ~35% CPU for about 15 minutes. Using PerfView I've figured out that the code analyzers being run on the solution are bogging down Visual Studio.</p>
<p>I know it's possible to disable analyzers on a per-project basis but this solution contains over 100 projects so I'd rather not do this one-by-one.</p>
<p>My question(s):</p>
<ul>
<li>Can I disable all Roslyn Analyzers for a given solution to avoid this?</li>
<li>Can I disable all Roslyn Analyzers for all solutions in Visual Studio?</li>
</ul> | 36,866,362 | 8 | 0 | null | 2016-04-06 19:58:40.657 UTC | 7 | 2022-07-13 14:15:18.1 UTC | 2016-04-06 20:36:02.223 UTC | null | 300,908 | null | 300,908 | null | 1 | 42 | c#|visual-studio|visual-studio-2015|roslyn|analyzer | 49,889 | <p>Try <code>Tools/Options/Text Editor/C#/Advanced</code> and disable full solution analysis. It's only available since VS2015 Update 2.</p> |
510,315 | How should I implement user membership in my ASP.NET MVC site? | <p>I'm creating an ASP.NET MVC site and I need to implement login and membership functionality. </p>
<p>Is this something where I roll my own? I already have a members table in my database, should I create a username and password hash field and just check against it? What about keeping the user logged in with a cookie that expires? </p>
<p>Is this an instance when you would use ASP.NET's built in Membership service? </p>
<p>ASP.NET MVC neophyte seeks help.</p> | 511,592 | 2 | 1 | null | 2009-02-04 06:48:54.09 UTC | 10 | 2010-02-06 00:59:31.833 UTC | 2009-02-04 07:32:15.393 UTC | Simucal | 2,635 | Simucal | 2,635 | null | 1 | 10 | asp.net-mvc|authentication|asp.net-membership|membership | 3,946 | <p>When you create a new ASP.NET MVC site, it already has membership built in. The CodePlex project mentioned in the other reply is only needed in special cases, namely:</p>
<ul>
<li>You are using an early beta of the MVC framework, which doesn't have the membership feature.</li>
<li>You want to use an authentication system like OpenID, which isn't supported "out-of-the-box" with MVC.</li>
<li>You want membership administration features not included "out-of-the-box"</li>
</ul>
<p>However, like I said, basic membership functionality is already present in an MVC site. Just add the <code>[Authorize]</code> attribute to any action requiring login. This is regular forms authentication, so you configured in Web.config like a non-MVC site (specifying the database, etc.; there's lots of information on the web about this).</p>
<p>A default MVC site will contain an "Account" controller and views which you can customize to fit your needs.</p>
<p>To answer the obvious question, no, you should not "roll your own." Even if you need custom authentication, it would be better to create a regular ASP.NET membership provider than to create an entirely new membership framework.</p>
<p><strong>Update</strong>: The <a href="http://mvcmembership.codeplex.com/" rel="nofollow noreferrer">CodePlex project</a> was updated to work with MVC 1.0</p> |
1,062,937 | Java equivalent to .Net's NotSupportedException | <p>Is there (not NotImplementedException, not supported).</p> | 1,062,942 | 2 | 2 | null | 2009-06-30 10:28:06.66 UTC | 4 | 2009-06-30 12:47:51.12 UTC | null | null | null | null | 11,236 | null | 1 | 68 | java|.net|exception | 19,439 | <p><code>java.lang.UnsupportedOperationException</code></p>
<p>Or, if you use Apache Commons Lang and the operation should be supported, but has not been implemented (yet?):</p>
<p><code>org.apache.commons.lang.NotImplementedException</code></p> |
1,074,729 | Get the value of an instance variable given its name | <p>In general, how can I get a reference to an object whose name I have in a string?</p>
<p>More specifically, I have a list of the parameter names (the member variables - built dynamically so I can't refer to them directly).</p>
<p>Each parameter is an object that also has an <code>from_s</code> method.</p>
<p>I want to do something like the following (which of course doesn't work...):</p>
<pre><code>define_method(:from_s) do | arg |
@ordered_parameter_names.each do | param |
instance_eval "field_ref = @#{param}"
field_ref.from_s(param)
end
end
</code></pre> | 1,077,682 | 2 | 0 | null | 2009-07-02 14:30:36.353 UTC | 15 | 2015-11-06 20:42:16.307 UTC | 2015-11-06 20:41:21.823 UTC | null | 128,421 | null | 115,822 | null | 1 | 108 | ruby|metaprogramming | 94,482 | <p>The most idiomatic way to achieve this is:</p>
<pre><code>some_object.instance_variable_get("@#{name}")
</code></pre>
<p>There is no need to use <code>+</code> or <code>intern</code>; Ruby will handle this just fine. However, if you find yourself reaching into another object and pulling out its ivar, there's a reasonably good chance that you have broken encapsulation.</p>
<p>If you explicitly want to access an ivar, the right thing to do is to make it an accessor. Consider the following:</p>
<pre><code>class Computer
def new(cpus)
@cpus = cpus
end
end
</code></pre>
<p>In this case, if you did <code>Computer.new</code>, you would be forced to use <code>instance_variable_get</code> to get at <code>@cpus</code>. But if you're doing this, you probably mean for <code>@cpus</code> to be public. What you should do is:</p>
<pre><code>class Computer
attr_reader :cpus
end
</code></pre>
<p>Now you can do <code>Computer.new(4).cpus</code>.</p>
<p>Note that you can reopen <strong>any</strong> existing class and make a private ivar into a reader. Since an accessor is just a method, you can do <code>Computer.new(4).send(var_that_evaluates_to_cpus)</code></p> |
2,985,032 | Powershell Remoting Profiles | <p>How do I use a function in my profile on the remote machine when using <code>Enter-PSSession</code> on my local machine to open a remote PowerShell session.</p> | 2,985,127 | 5 | 1 | null | 2010-06-06 17:02:41.397 UTC | 9 | 2019-01-31 11:01:01.727 UTC | 2017-12-10 01:26:14.643 UTC | null | 64,046 | null | 317,603 | null | 1 | 11 | powershell|powershell-remoting | 12,264 | <p>You can't. When starting a remote interactive session with enter-pssession, a remote profile is loaded. Additionally, only the machine-level profile in $pshome is loaded. If you want remote functions available you'll have to initialize them in the startup script of the remote session configuration. Have a look at get/set-pssessionconfiguration on the remote server.</p> |
2,686,593 | Emacs: adding 1 to every number made of 2 digits inside a marked region | <p>Imagine I've got the following in a text file opened under Emacs:</p>
<pre><code>some 34
word 30
another 38
thing 59
to 39
say 10
here 47
</code></pre>
<p>and I want to turn into this, adding 1 to every number made of 2 digits:</p>
<pre><code>some 35
word 31
another 39
thing 60
to 40
say 11
here 48
</code></pre>
<p>(this is a short example, my actual need is on a much bigger list, not my call)</p>
<p>How can I do this from Emacs?</p>
<p>I don't mind calling some external Perl/sed/whatever magic as long as the call is made directly from Emacs and operates only on the marked region I want.</p>
<p>How would you automate this from Emacs? </p>
<p>I think the answer I'm thinking of consist in calling <em>shell-command-on-region</em> and replace the region by the output... But I'm not sure as to how to concretely do this.</p> | 2,686,722 | 5 | 4 | null | 2010-04-21 21:12:34.09 UTC | 11 | 2015-08-18 08:29:14.807 UTC | 2010-04-21 21:18:18.54 UTC | null | 257,356 | null | 257,356 | null | 1 | 26 | emacs|elisp | 3,300 | <p>This can be solved by using the command <em>query-replace-regexp</em> (bound to <kbd>C-M-%</kbd>):</p>
<p><kbd>C-M-%</kbd>
<code>\b[0-9][0-9]\b</code>
<kbd>return</kbd>
<code>\,(1+ \#&)</code></p>
<p>The expression that follows <code>\,</code> would be evaluated as a Lisp expression, the result of which used as the replacement string. In the Lisp expression, <code>\#&</code> would be replaced by the matched string, interpreted as a number.</p>
<p>By default, this works on the whole document, starting from the cursor. To have this work on the region, there are several posibilities:</p>
<ol>
<li>If <em>transient-mark-mode</em> is turned on, you just need to select the region normally (using point and mark);</li>
<li>If for some reason you don't like <em>transient-mark-mode</em>, you may use <em>narrow-to-region</em> to restrict the changes to a specific region: select a region using point and mark, <kbd>C-x n n</kbd> to narrow, perform <em>query-replace-regexp</em> as described above, and finally <kbd>C-x n w</kbd> to widen. (Thanks to Justin Smith for this hint.)</li>
<li>Use the mouse to select the region.</li>
</ol>
<p>See section <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Replace.html" rel="noreferrer">Regexp Replacement</a> of the Emacs Manual for more details.</p> |
2,735,890 | find svn revision by removed text | <p>Is there a way to find an SVN revision by searching for a text string that got removed in the file? I know the exact text to search for and which file to look in, but there are hundreds of revisions.</p> | 2,742,851 | 5 | 4 | null | 2010-04-29 08:46:57.4 UTC | 9 | 2018-09-17 15:10:37.563 UTC | 2010-04-29 09:16:14.28 UTC | null | 237,524 | null | 237,524 | null | 1 | 34 | svn|search|revision | 6,976 | <p>Building on khmarbaise's script, I came up with this:</p>
<pre><code>#!/bin/bash
file="$1"
REVISIONS=`svn log $file -q --stop-on-copy |grep "^r" | cut -d"r" -f2 | cut -d" " -f1`
for rev in $REVISIONS; do
prevRev=$(($rev-1))
difftext=`svn diff --old=$file@$prevRev --new=$file@$rev | tr -s " " | grep -v " -\ \- " | grep -e "$2"`
if [ -n "$difftext" ]; then
echo "$rev: $difftext"
fi
done
</code></pre>
<p>pass the file name and search string on the command line:</p>
<pre><code>xyz.sh "filename" "text to search"
</code></pre>
<p>svn diff gives me both the rev where it's added and where it's deleted; I'll leave it here in case it's useful to anyone. There's an error message at the last revision that I don't know how to get rid of (I still got a lot of bash to learn :) ) but the rev numbers are correct.</p> |
3,120,761 | How do I get console input in spidermonkey JavaScript? | <p>I'm currently using spidermonkey to run my JavaScript code. I'm wondering if there's a function to get input from the console similar to how Python does this:</p>
<pre><code>var = raw_input()
</code></pre>
<p>Or in C++:</p>
<pre><code>std::cin >> var;
</code></pre>
<p>I've looked around and all I've found so far is how to get input from the browser using the <code>prompt()</code> and <code>confirm()</code> functions.</p> | 3,120,816 | 5 | 0 | null | 2010-06-25 19:09:13.02 UTC | 14 | 2022-03-29 16:54:24.12 UTC | 2021-03-23 18:32:28.087 UTC | null | 6,243,352 | null | 376,590 | null | 1 | 75 | javascript|input|console|spidermonkey | 215,861 | <p>Good old <code>readline();</code>.</p>
<p>See <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell#readline.28.29" rel="noreferrer">MDN</a> (archive).</p> |
3,209,807 | How to do error logging in CodeIgniter (PHP) | <p>I want error logging in PHP CodeIgniter. How do I enable error logging? </p>
<p>I have some questions:</p>
<ol>
<li>What are all the steps to log an error?</li>
<li>How is an error log file created?</li>
<li>How to push the error message into log file (whenever an error occurs)?</li>
<li>How do you e-mail that error to an email address?</li>
</ol> | 3,210,288 | 5 | 0 | null | 2010-07-09 04:21:46.25 UTC | 22 | 2020-07-14 10:11:04.107 UTC | 2014-04-01 16:58:25.287 UTC | null | 445,131 | null | 241,853 | null | 1 | 107 | php|codeigniter|logging|error-handling | 217,038 | <p>CodeIgniter has some error logging functions built in.</p>
<ul>
<li>Make your <em>/application/logs</em> folder writable </li>
<li>In <em>/application/config/config.php</em> set <br><code>$config['log_threshold'] = 1;</code><br> or use a higher number, depending on how much detail you want in your logs</li>
<li>Use <code>log_message('error', 'Some variable did not contain a value.');</code></li>
<li>To send an email you need to extend the core CI_Exceptions class method <code>log_exceptions()</code>. You can do this yourself or use <a href="https://github.com/mikedfunk/CodeIgniter-Email-PHP-Errors" rel="noreferrer">this</a>. More info on extending the core <a href="http://www.codeigniter.com/user_guide/general/core_classes.html" rel="noreferrer">here</a></li>
</ul>
<p>See <a href="http://www.codeigniter.com/user_guide/general/errors.html" rel="noreferrer">http://www.codeigniter.com/user_guide/general/errors.html</a></p> |
3,115,388 | Declaration of Methods should be Compatible with Parent Methods in PHP | <pre>Strict Standards: Declaration of childClass::customMethod() should be compatible with that of parentClass::customMethod()
</pre>
<p>What are possible causes of this error in PHP? Where can I find information about what it means to be <em>compatible</em>?</p> | 3,115,398 | 5 | 4 | null | 2010-06-25 03:37:54.183 UTC | 18 | 2020-04-28 09:33:07.857 UTC | null | null | null | null | 89,334 | null | 1 | 116 | php|methods|standards-compliance | 149,676 | <p><code>childClass::customMethod()</code> has different arguments, or a different access level (public/private/protected) than <code>parentClass::customMethod()</code>.</p> |
2,923,210 | Conditional compilation and framework targets | <p>There are a few minor places where code for my project may be able to be drastically improved if the target framework were a newer version. I'd like to be able to better leverage conditional compilation in C# to switch these as needed.</p>
<p>Something like:</p>
<pre><code>#if NET40
using FooXX = Foo40;
#elif NET35
using FooXX = Foo35;
#else NET20
using FooXX = Foo20;
#endif
</code></pre>
<p>Do any of these symbols come for free? Do I need to inject these symbols as part of the project configuration? It seems easy enough to do since I'll know which framework is being targeted from MSBuild.</p>
<pre><code>/p:DefineConstants="NET40"
</code></pre>
<p>How are people handling this situation? Are you creating different configurations? Are you passing in the constants via the command line?</p> | 2,928,835 | 7 | 4 | null | 2010-05-27 17:05:43.307 UTC | 86 | 2019-11-21 16:58:32.803 UTC | 2019-09-10 13:07:04.41 UTC | null | 63,550 | null | 43,217 | null | 1 | 125 | c#|.net-3.5|msbuild|.net-4.0 | 54,309 | <p>One of the best ways to accomplish this is to create different build configurations in your project:</p>
<pre><code><PropertyGroup Condition=" '$(Framework)' == 'NET20' ">
<DefineConstants>NET20</DefineConstants>
<OutputPath>bin\$(Configuration)\$(Framework)</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Framework)' == 'NET35' ">
<DefineConstants>NET35</DefineConstants>
<OutputPath>bin\$(Configuration)\$(Framework)</OutputPath>
</PropertyGroup>
</code></pre>
<p>And in one of your default configurations:</p>
<pre><code><Framework Condition=" '$(Framework)' == '' ">NET35</Framework>
</code></pre>
<p>Which would set the default if it wasn't defined anywhere else. In the above case the OutputPath will give you a separate assembly each time you build each version.</p>
<p>Then create a AfterBuild target to compile your different versions:</p>
<pre><code><Target Name="AfterBuild">
<MSBuild Condition=" '$(Framework)' != 'NET20'"
Projects="$(MSBuildProjectFile)"
Properties="Framework=NET20"
RunEachTargetSeparately="true" />
</Target>
</code></pre>
<p>This example will recompile the entire project with the Framework variable set to NET20 after the first build (compiling both and assuming that the first build was the default NET35 from above). Each compile will have the conditional define values set correctly.</p>
<p>In this manner you can even exclude certain files in the project file if you want w/o having to #ifdef the files:</p>
<pre><code><Compile Include="SomeNet20SpecificClass.cs" Condition=" '$(Framework)' == 'NET20' " />
</code></pre>
<p>or even references</p>
<pre><code><Reference Include="Some.Assembly" Condition="" '$(Framework)' == 'NET20' " >
<HintPath>..\Lib\$(Framework)\Some.Assembly.dll</HintPath>
</Reference>
</code></pre> |
2,611,852 | imagecreatefrompng() Makes a black background instead of transparent? | <p>I make thumbnails using PHP and GD library but my code turn png transparency into a solid black color, Is there a solution to improve my code?</p>
<p>this is my php thumbnail maker code:</p>
<pre><code>function cropImage($nw, $nh, $source, $stype, $dest) {
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}
$dimg = imagecreatetruecolor($nw, $nh);
$wm = $w/$nw;
$hm = $h/$nh;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h) {
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $half_width - $w_height;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} elseif(($w <$h) || ($w == $h)) {
$adjusted_height = $h / $wm;
$half_height = $adjusted_height / 2;
$int_height = $half_height - $h_height;
imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
} else {
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
imagejpeg($dimg,$dest,100);
}
</code></pre>
<p>Thank you</p> | 2,611,911 | 8 | 0 | null | 2010-04-10 01:10:30.323 UTC | 17 | 2020-10-09 12:10:35.897 UTC | null | null | null | null | 311,493 | null | 1 | 42 | php|gd|thumbnails | 77,214 | <p>After imagecreatetruecolor():</p>
<pre><code><?php
// ... Before imagecreatetruecolor()
$dimg = imagecreatetruecolor($width_new, $height_new); // png ?: gif
// start changes
switch ($stype) {
case 'gif':
case 'png':
// integer representation of the color black (rgb: 0,0,0)
$background = imagecolorallocate($dimg , 0, 0, 0);
// removing the black from the placeholder
imagecolortransparent($dimg, $background);
// turning off alpha blending (to ensure alpha channel information
// is preserved, rather than removed (blending with the rest of the
// image in the form of black))
imagealphablending($dimg, false);
// turning on alpha channel information saving (to ensure the full range
// of transparency is preserved)
imagesavealpha($dimg, true);
break;
default:
break;
}
// end changes
$wm = $w/$nw;
$hm = $h/$nh;
// ...
</code></pre> |
3,090,648 | Django South - table already exists | <p>I am trying to get started with South. I had an existing database and I added South (<code>syncdb</code>, <code>schemamigration --initial</code>).</p>
<p>Then, I updated <code>models.py</code> to add a field and ran <code>./manage.py schemamigration myapp --auto</code>. It seemed to find the field and said I could apply this with <code>./manage.py migrate myapp</code>. But, doing that gave the error: </p>
<pre><code>django.db.utils.DatabaseError: table "myapp_tablename" already exists
</code></pre>
<p><code>tablename</code> is the first table listed in <code>models.py</code>.</p>
<p>I am running Django 1.2, South 0.7</p> | 3,090,857 | 8 | 0 | null | 2010-06-22 06:09:47.847 UTC | 77 | 2017-04-05 08:51:00.06 UTC | 2014-02-01 22:30:22.023 UTC | null | 2,387,772 | null | 372,837 | null | 1 | 188 | django|django-south | 67,065 | <p>since you already have the tables created in the database, you just need to run the initial migration as fake</p>
<pre><code>./manage.py migrate myapp --fake
</code></pre>
<p>make sure that the schema of models is same as schema of tables in database.</p> |
2,497,442 | Is there any online python exercise? | <p>I am teaching a colleague Python and I think he should do some exercises.</p>
<p>Is there any online available other than python challenge? I feel that python challenge is puzzles, not exercises.</p> | 2,497,465 | 9 | 0 | null | 2010-03-23 03:43:44.993 UTC | 9 | 2014-04-03 16:15:41.04 UTC | 2011-12-09 18:18:05.573 UTC | null | 3,043 | null | 134,852 | null | 1 | 13 | python | 14,752 | <p>There is now also <a href="http://code.google.com/edu/languages/google-python-class/" rel="noreferrer">Google's Python Class</a>, which includes lots of exercise.</p> |
3,008,718 | Split String into smaller Strings by length variable | <p>I'd like to break apart a String by a certain length variable.<br>
It needs to bounds check so as not explode when the last section of string is not as long as or longer than the length. Looking for the most succinct (yet understandable) version. </p>
<p>Example: </p>
<pre><code>string x = "AAABBBCC";
string[] arr = x.SplitByLength(3);
// arr[0] -> "AAA";
// arr[1] -> "BBB";
// arr[2] -> "CC"
</code></pre> | 3,008,775 | 12 | 0 | null | 2010-06-09 18:29:25.333 UTC | 10 | 2019-03-15 18:04:21.767 UTC | 2010-06-09 21:15:45.19 UTC | null | 76,337 | null | 36,590 | null | 1 | 41 | c#|.net|algorithm|string | 61,946 | <p>You need to use a loop:</p>
<pre><code>public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
for (int index = 0; index < str.Length; index += maxLength) {
yield return str.Substring(index, Math.Min(maxLength, str.Length - index));
}
}
</code></pre>
<p>Alternative:</p>
<pre><code>public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(true) {
if (index + maxLength >= str.Length) {
yield return str.Substring(index);
yield break;
}
yield return str.Substring(index, maxLength);
index += maxLength;
}
}
</code></pre>
<p>2<sup>nd</sup> alternative: (For those who can't stand <code>while(true)</code>)</p>
<pre><code>public static IEnumerable<string> SplitByLength(this string str, int maxLength) {
int index = 0;
while(index + maxLength < str.Length) {
yield return str.Substring(index, maxLength);
index += maxLength;
}
yield return str.Substring(index);
}
</code></pre> |
2,582,036 | An existing connection was forcibly closed by the remote host | <p>I am working with a commercial application which is throwing a SocketException with the message,</p>
<blockquote>
<p>An existing connection was forcibly closed by the remote host</p>
</blockquote>
<p>This happens with a socket connection between client and server. The connection is alive and well, and heaps of data is being transferred, but it then becomes disconnected out of nowhere.</p>
<p>Has anybody seen this before? What could the causes be? I can kind of guess a few causes, but also is there any way to add more into this code to work out what the cause could be?</p>
<p>Any comments / ideas are welcome.</p>
<p>... The latest ...</p>
<p>I have some logging from some .NET tracing,</p>
<pre><code>System.Net.Sockets Verbose: 0 : [8188] Socket#30180123::Send() DateTime=2010-04-07T20:49:48.6317500Z
System.Net.Sockets Error: 0 : [8188] Exception in the Socket#30180123::Send - An existing connection was forcibly closed by the remote host DateTime=2010-04-07T20:49:48.6317500Z
System.Net.Sockets Verbose: 0 : [8188] Exiting Socket#30180123::Send() -> 0#0
</code></pre>
<p>Based on other parts of the logging I have seen the fact that it says <code>0#0</code> means a packet of 0 bytes length is being sent. But what does that really mean?</p>
<p>One of two possibilities is occurring, and I am not sure which,</p>
<ol>
<li><p>The connection is being closed, but data is then being written to the socket, thus creating the exception above. The <code>0#0</code> simply means that nothing was sent because the socket was already closed.</p>
</li>
<li><p>The connection is still open, and a packet of zero bytes is being sent (i.e. the code has a bug) and the <code>0#0</code> means that a packet of zero bytes is trying to be sent.</p>
</li>
</ol>
<p>What do you reckon? It might be inconclusive I guess, but perhaps someone else has seen this kind of thing?</p> | 2,582,070 | 15 | 2 | null | 2010-04-06 00:54:22.46 UTC | 43 | 2022-09-15 13:02:26.263 UTC | 2021-04-15 18:09:19.497 UTC | null | 241,211 | null | 133,476 | null | 1 | 221 | c#|.net|networking|sockets | 769,850 | <p>This generally means that the remote side closed the connection (usually by sending a TCP/IP <code>RST</code> packet). If you're working with a third-party application, the likely causes are:</p>
<ul>
<li>You are sending malformed data to the application (which could include sending an HTTPS request to an HTTP server)</li>
<li>The network link between the client and server is going down for some reason</li>
<li>You have triggered a bug in the third-party application that caused it to crash</li>
<li>The third-party application has exhausted system resources</li>
</ul>
<p>It's likely that the first case is what's happening.</p>
<p>You can fire up <a href="http://www.wireshark.org/" rel="noreferrer">Wireshark</a> to see exactly what is happening on the wire to narrow down the problem.</p>
<p>Without more specific information, it's unlikely that anyone here can really help you much.</p> |
25,091,791 | Is it possible to use different view resolvers? | <p>I have multiple view resolvers in a Spring configuration and wanted to use different view resolvers for different requests.</p>
<p>Example: For URLs starting with <code>report_*</code>, use Birt view resolver, and for ajax calls use Tiles resolver and so on.</p>
<p>Tried setting order property, but all views are resolved by <code>tilesViewResolver</code>.</p>
<pre><code><beans:bean id="tilesViewResolver" class="org.springframework.js.ajax.AjaxUrlBasedViewResolver">
<beans:property name="viewClass" value="com.example.example.util.AjaxTiles21View"/>
</beans:bean>
<beans:bean id="birtViewResolver" class="org.eclipse.birt.spring.core.BirtViewResolver">
...
<beans:property name="order" value="2" />
</beans:bean>
<beans:bean id="beanNameResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver">
<beans:property name="order" value="1" />
</beans:bean>
</code></pre> | 25,091,839 | 1 | 0 | null | 2014-08-02 04:53:06.05 UTC | 3 | 2017-03-26 19:22:37.56 UTC | 2017-03-26 19:22:37.56 UTC | null | 3,980,929 | null | 3,851,524 | null | 1 | 48 | java|spring-mvc|birt | 2,270 | <p>You absolutely can. <code>ViewResolver</code> has a single method, <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/ViewResolver.html#resolveViewName-java.lang.String-java.util.Locale-"><code>resolveViewName(String)</code></a> which returns</p>
<blockquote>
<p>the View object, or <strong>null if not found</strong> (optional, to allow for ViewResolver chaining)</p>
</blockquote>
<p>Your <code>ViewResolver</code> beans are registered. When a view name is returned by a handler, Spring will iterate through each <code>ViewResolver</code>, invoking their <code>resolveViewName</code> method with the given name. If the method returns non<code>-null</code>, that <code>View</code> is used. If <code>null</code> is returned, then it continues iterating.</p>
<p>So the implementation has to return <code>null</code> if Spring is to skip it.</p>
<p>There are some implementations that never return <code>null</code>. This seems to be the case with your custom <code>ViewResolver</code> classes. If the <code>ViewResolver</code> returns a <code>View</code>, even if that <code>View</code> will eventually fail to be rendered, Spring will use it.</p>
<p>You either need to fix that or order your <code>ViewResolver</code> beans. For example, you can order them with the <code>Ordered</code> interface. Have your classes implement that interface and return an appropriate value.</p> |
10,476,488 | Difference Between session.evict vs clear | <p>what is difference between session.clear and evict methods in hibernate.Both are detatched objects that is instance removed from session.when should i use session.clear and session.evict in hibernate.</p> | 10,476,544 | 1 | 0 | null | 2012-05-07 04:00:29.71 UTC | 9 | 2016-09-12 13:55:59.237 UTC | null | null | null | null | 1,357,722 | null | 1 | 29 | hibernate | 36,111 | <p><a href="http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#evict%28java.lang.Object%29" rel="noreferrer">evict()</a> evicts a single object from the session. <a href="http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#clear%28%29" rel="noreferrer">clear()</a> evicts all the objects in the session. Calling clear() is like calling evict() on every object associated with the session.</p> |
5,935,447 | How can django sql queries use case insensitive and contains at the same time? | <p>Suppose I have two users with username 'AbA' and 'aBa' in the database.
My query word is 'ab'.</p>
<p>I used </p>
<p><code>User.objects.filter(username__contains='ab')</code> </p>
<p>and</p>
<p><code>User.objects.filter(username__iexact='ab')</code></p>
<p>These two queries get empty result. However, I want to use something like <code>username__contains__iexact='ab'</code> that can retrieve both 'AbA' and 'aBa'.</p>
<p>Anyone know how to resolve this problem? Thanks.</p> | 5,935,468 | 2 | 0 | null | 2011-05-09 10:15:18.537 UTC | 5 | 2019-05-17 14:57:03.77 UTC | 2013-04-18 00:41:51.563 UTC | null | 55,562 | null | 674,507 | null | 1 | 40 | python|django | 15,246 | <p>Use:</p>
<pre><code>User.objects.filter(username__icontains='ab')
</code></pre> |
58,519,021 | In AndroidManifest: Expecting android:screenOrientation="unspecified" | <p>Android Studio 3.6.</p>
<p>I want my app to be always in <code>portrait</code> mode. So in my <code>AndroidMainfest.xml</code>:</p>
<pre class="lang-xml prettyprint-override"><code><activity
android:name=".activity.SplashActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</code></pre>
<p>I run the app and <code>SplashActivity</code> shows in <code>portrait</code> mode. Nice.
But the editor shows the following error:</p>
<pre class="lang-none prettyprint-override"><code>Expecting android:screenOrientation="unspecified"
</code></pre>
<p>Why?</p> | 60,400,979 | 10 | 0 | null | 2019-10-23 08:53:21.68 UTC | 9 | 2021-09-02 08:45:39.313 UTC | 2020-02-25 16:22:25.353 UTC | null | 12,820,864 | null | 6,813,231 | null | 1 | 77 | android|android-manifest|screen-orientation | 28,901 | <p>In your manifest tag (just under <code>xmlns:android="http://schemas.android.com/apk/res/android"</code>), put</p>
<pre><code>xmlns:tools="http://schemas.android.com/tools"
</code></pre>
<p>Then inside the application tag, put</p>
<pre><code>tools:ignore="LockedOrientationActivity"
</code></pre> |
40,891,433 | Understanding metaspace line in JVM heap printout | <p>In a Java 8 heap printout, you may see a line that looks like:</p>
<blockquote>
<p>Metaspace <strong>used</strong> 2425K, <strong>capacity</strong> 4498K, <strong>committed</strong> 4864K, <strong>reserved</strong> 1056768K</p>
</blockquote>
<p><a href="https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/considerations.html" rel="noreferrer">https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/considerations.html</a> tries to explain the line:</p>
<blockquote>
<p>In the line beginning with Metaspace, the <strong>used</strong> value is the amount of space used for loaded classes. The <strong>capacity</strong> value is the space available for metadata in currently allocated chunks. The <strong>committed</strong> value is the amount of space available for chunks. The <strong>reserved</strong> value is the amount of space reserved (but not necessarily committed) for metadata.</p>
</blockquote>
<p>Again, from the above link:</p>
<blockquote>
<p>Space is requested from the OS and then divided into chunks. A class loader allocates space for metadata from its chunks (a chunk is bound to a specific class loader).</p>
</blockquote>
<p>I want to know what each field means (used, capacity, committed, reserved), but I am struggling to understand the above definitions.</p>
<p>My understanding is that metaspace is carved out of the JVM process's virtual address space. The JVM reserves an initial size on startup based on -XX:MetaspaceSize, which has an undocumented, platform-specific default. I assume that <strong>reserved</strong> refers to the total size of the metaspace. The space is divided into chunks. I am not sure if each chunk has the same size. Each chunk contains class metadata associated with a single class loader.</p>
<p><strong>Capacity</strong> and <strong>committed</strong> sounds like free space to me (based on the definitions from the link). Since metadata is stored within chunks, then I would assume that used + capacity would equal committed, but it doesn't. Maybe committed means reserved space that is used, but then what would used mean? Used space used by metadata? Then, what other ways are there to use the space?</p>
<p>I hope you see my confusion. I would appreciate clarification on the definitions.</p> | 40,899,996 | 1 | 0 | null | 2016-11-30 14:54:16.613 UTC | 18 | 2016-11-30 23:15:44.78 UTC | null | null | null | null | 7,231,171 | null | 1 | 22 | java|linux|java-8|jvm|metaspace | 9,900 | <p><a href="https://i.stack.imgur.com/qu8N2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qu8N2.png" alt="Metaspace layout"></a></p>
<p>Metaspace consists of one or more Virtual Spaces. Virtual Spaces are areas of contiguous address space obtained from the OS. They are allocated on demand. When allocated, Virtual Space <em>reserves</em> memory from the OS, but not yet <em>commits</em> it. Metaspace <strong>reserved</strong> memory is the total size of all Virtual Spaces.</p>
<p>Allocation unit inside Virtual Space is Metachunk (or simply Chunk). When a new chunk is allocated from a Virtual Space, the corresponding memory is <em>committed</em>. Metaspace <strong>committed</strong> memory is the total size of all chunks.</p>
<p>Chunks may differ in size. When a ClassLoader gets garbage collected, all Metachunks belonging to it are freed. Free chunks are maintained in the global free list. Metaspace <strong>capacity</strong> is the total size of all <em>allocated</em> (i.e. not free) chunks.</p>
<p><strong>New chunk allocation</strong></p>
<ol>
<li>Look for an existing free chunk in the free list.</li>
<li>If there is no suitable free chunk, allocate a new one from the current Virtual Space.</li>
<li>If the current Virtual Space is exhausted, reserve a new Virtual Space.</li>
</ol>
<p>Class metadata is allocated within a chunk. Chunk may not contain data from multiple ClassLoaders, but one ClassLoader may have several chunks. Metaspace <strong>used</strong> is the total size of all class metadata from all chunks.</p> |
32,603,818 | Order of router precedence in express.js | <p>I would like to understand the order precedence in express.js. For example, as bellow code</p>
<pre><code>var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
app.use('/api', api);
app.use('/users', users);
app.use('/:name', function(req, res, next) {
console.log('from app.js name:', req.params.name);
res.render('index', {
title: req.params.name
});
}, routes);
app.use('/', function(req, res, next) {
res.render('index', {
title: 'MainPage'
});
});
</code></pre>
<p>If a request come from client localhost:3000/api/abc and localhost:3000/user/abc, the response from api and user module. But if I make a request like localhost:3000/myName/xyz, the app module return a response. This behavior let me concern about what is precedence of expressjs and what is correct order for router modules. Why routers do not confuse between actions "api", "users" and parameter ":name". Please let me understand clearly how express does and what is precedence.</p> | 32,604,002 | 2 | 0 | null | 2015-09-16 08:51:07.653 UTC | 6 | 2021-03-25 16:00:44.64 UTC | null | null | null | null | 1,121,977 | null | 1 | 35 | node.js|express | 21,700 | <p>The order is first come first serve.</p>
<p>In your case, if user hits /api, he will get response from api, but if you write <code>/:name</code> route before <code>/api</code>, <code>/:name</code> will serve for <code>/api</code> requests also.</p>
<blockquote>
<p><strong>Case1: <code>/api</code> will serve requests for <code>/api</code>.</strong></p>
</blockquote>
<pre><code>var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
app.use('/api', api);
app.use('/users', users);
app.use('/:name', function(req, res, next) {
console.log('from app.js name:', req.params.name);
res.render('index', {
title: req.params.name
});
}, routes);
app.use('/', function(req, res, next) {
res.render('index', {
title: 'MainPage'
});
});
</code></pre>
<blockquote>
<p><strong>Case2: <code>/:name</code> serves requests for <code>/api</code> and <code>/users</code></strong></p>
</blockquote>
<pre><code>var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
app.use('/:name', function(req, res, next) {
console.log('from app.js name:', req.params.name);
res.render('index', {
title: req.params.name
});
}, routes);
app.use('/api', api);
app.use('/users', users);
app.use('/', function(req, res, next) {
res.render('index', {
title: 'MainPage'
});
});
</code></pre> |
21,334,493 | git commit in pre-push hook | <p>I have added something like that in <code>pre-push</code> hook:</p>
<pre><code>gs0=$(git status)
pip-dump
gs1=$(git status)
if [ "gs0" != "gs1" ]
then
git commit -m "pip-dump"
fi
</code></pre>
<p>(this is updating my pip requirements file)</p>
<p>It seems that the push is not pushing the new commit, but the one which the HEAD was on at the beginning of the script.</p>
<p>How to fix that?</p> | 21,334,985 | 2 | 1 | null | 2014-01-24 13:55:29.613 UTC | 3 | 2021-09-17 17:22:16.837 UTC | null | null | null | null | 931,156 | null | 1 | 32 | git|githooks | 6,961 | <p>You can't: the <code>push</code> command figures out which commits to push before invoking the hook, and pushes that if the hook exits 0.</p>
<p>I see three options:</p>
<ol>
<li>Exit nonzero, telling the user "push rejected because I added a commit"</li>
<li>Exit zero, telling the user "push went through but you'll need to push again because I added a commit"</li>
<li>Do another (different) push inside the hook, after adding the new commit, taking care that your hook does not endlessly recurse because the "inner" push runs the hook which decides to do another "inner-again" push, etc. Then, exit nonzero, aborting the "outer" push, after announcing that you had to do an "inner" push to get the extra commit sent through.</li>
</ol>
<p>My personal preference would be the first of these. A pre-push hook is <em>meant</em> as a "verify that this push is OK" operation, not a "change this push to mean some other different push" operation. So that means you're not working against the "intent" of the software. Use the pre-push hook as a verifier; and if you want a script that invokes <code>git push</code> after automatically adding a <code>pip-dump</code> commit if needed, write that as a script, using a different name, such as <code>dump-and-push</code>.</p> |
20,974,383 | SQl query to sum-up amounts by month/year | <p>I have a table "TABLE" like this:</p>
<pre><code>Date(datatime)
Paid(int)
</code></pre>
<p>I have multiple "Paid" amounts per month.
I would like to sum up the Paid amount per month/year.</p>
<p>So far this is what I tried but I get errors in EXTRACT and in MONTH and however I am far to get it done with the years.</p>
<pre><code>SELECT
EXTRACT(MONTH FROM Period) AS reference_month
, SUM(Paid) AS monthly_payments
FROM Paid
GROUP BY EXTRACT(MONTH FROM Period)
ORDER BY EXTRACT(MONTH FROM Period)
</code></pre>
<p>I am not really handy at this and I would really appreciate some help.</p> | 20,974,451 | 2 | 1 | null | 2014-01-07 14:38:02.273 UTC | 2 | 2018-07-19 20:49:53.567 UTC | 2014-01-07 14:42:34.317 UTC | null | 110,933 | null | 3,135,101 | null | 1 | 7 | sql-server | 48,360 | <pre><code>select year(date) as y, month(date) as m, sum(paid) as p
from table
group by year(date), month(date)
</code></pre> |
21,827,267 | MVC 4 - Razor - Pass a variable into a href url | <p>How can I pass a variable into a url?</p>
<p>What I try is this but this is not working. The url only shows this:</p>
<p><code>http://myurltest.com</code> and not the full path</p>
<pre><code>@if(check1 != "d")
{
<li>
<div class="a"></div>
</li>
<li>
<div class="b"></div>
</li>
<li>
<a href="http://myurltest.com/" + @check1 + "/go/5/true">
<div class="c"></div>
</a>
</li>
}
</code></pre> | 21,827,301 | 5 | 0 | null | 2014-02-17 11:01:02.847 UTC | 8 | 2016-05-16 16:12:56.767 UTC | 2014-02-17 11:07:51.283 UTC | null | 1,184,435 | null | 2,232,273 | null | 1 | 38 | c#|asp.net|asp.net-mvc|razor | 88,966 | <p>Like this:</p>
<pre><code><a href='@string.Format("http://myurltest.com/{0}/go/5/true", check1)'>
</code></pre>
<p>The point is to insert the whole URL into the markup, rather than combining markup and code parts.</p> |
19,102,946 | Bootstrap radio button "checked" flag | <p>In case #1 works, in case #2 it do not works. Check the code bellow:</p>
<pre><code><div class="container">
<div class="row">
<h1>Radio Group #1</h1>
<label class="radio-inline">
<input name="radioGroup" id="radio1" value="option1" type="radio"> 1
</label>
<label class="radio-inline">
<input name="radioGroup" id="radio2" value="option2" checked="checked" type="radio"> 2
</label>
<label class="radio-inline">
<input name="radioGroup" id="radio3" value="option3" type="radio"> 3
</label>
</div>
<div class="row">
<h1>Radio Group #2</h1>
<label for="year" class="control-label input-group">Year</label>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input name="year" value="2011" type="radio">2011
</label>
<label class="btn btn-default">
<input name="year" value="2012" type="radio">2012
</label>
<label class="btn btn-default">
<input name="year" value="2013" checked="checked" type="radio">2013
</label>
</div>
</div>
</div>
</code></pre>
<p>You can see it in action here: <a href="http://bootply.com/84165">http://bootply.com/84165</a></p> | 19,103,254 | 5 | 0 | null | 2013-09-30 20:12:18.3 UTC | 13 | 2020-09-26 09:14:24.103 UTC | 2014-01-09 16:27:37.77 UTC | null | 1,022,305 | null | 1,480,162 | null | 1 | 41 | html|twitter-bootstrap|radio-button | 197,256 | <p>Assuming you want a default button checked.</p>
<pre><code><div class="row">
<h1>Radio Group #2</h1>
<label for="year" class="control-label input-group">Year</label>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" name="year" value="2011">2011
</label>
<label class="btn btn-default">
<input type="radio" name="year" value="2012">2012
</label>
<label class="btn btn-default active">
<input type="radio" name="year" value="2013" checked="">2013
</label>
</div>
</div>
</code></pre>
<p>Add the <code>active</code> class to the button (<code>label</code> tag) you want defaulted and <code>checked=""</code> to its <code>input</code> tag so it gets submitted in the form by default.</p> |
19,018,536 | How do I toggle an ng-show in AngularJS based on a boolean? | <p>I have a form for replying to messages that I want to show only when <code>isReplyFormOpen</code> is true, and everytime I click the reply button I want to toggle whether the form is shown or not. How can I do this?</p> | 19,021,489 | 6 | 0 | null | 2013-09-26 02:52:55.547 UTC | 25 | 2018-06-13 19:10:32.4 UTC | null | null | null | null | 453,438 | null | 1 | 114 | javascript|html|angularjs|ng-show | 159,410 | <p>You just need to toggle the value of "isReplyFormOpen" on ng-click event</p>
<pre><code><a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
<div ng-show="isReplyFormOpen" id="replyForm">
</div>
</code></pre> |
18,962,403 | How do I run tox in a project that has no setup.py? | <p>I would like to use <code>tox</code> to run my unittests in two virtualenvs, since my application has to support 2 different Python versions.</p>
<p>My problem is that <code>tox</code> requires a <code>setup.py</code>, but I have none since my application is not a module and has its own installer. For now I don't want to go through the hassle of automating the install process as to work with <code>setup.py</code>, I just want to run my unittests without having to write a <code>setup.py</code>.</p>
<p>Is that possible? Or how can I write an "empty" setup.py that simply does nothing? Can you point me towards some documentation on the subject (the <code>distutils</code> documentation explains how to write a meaningful <code>setup.py</code>, not an empty one)?</p> | 18,985,263 | 4 | 0 | null | 2013-09-23 14:50:46.133 UTC | 13 | 2021-02-06 19:34:37.073 UTC | 2015-02-23 14:24:06.317 UTC | null | 287,030 | null | 287,030 | null | 1 | 83 | python|unit-testing|distutils|tox | 15,315 | <p>After digging inside the source code, I found a scarcely documented option in tox.ini that skips sdist:</p>
<pre><code>[tox]
skipsdist = BOOL # defaults to false
</code></pre>
<p>Setting this to <code>True</code> I got what I wanted, saving me the effort of writing a meaningful <code>setup.py</code></p> |
37,118,385 | Styling ionic 2 toast | <p>Is there any way to style the text message within an ionic 2 toast?</p>
<p>I have tried this:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> let toast = Toast.create({
message: "Some text on one line. <br /><br /> Some text on another line.",
duration: 15000,
showCloseButton: true,
closeButtonText: 'Got it!',
dismissOnPageChange: true
});
toast.onDismiss(() => {
console.log('Dismissed toast');
});
this.nav.present(toast);
}</code></pre>
</div>
</div>
</p>
<p>But clearly you can't use html in the text so I am guessing the answer to my question is no?</p> | 40,762,218 | 11 | 0 | null | 2016-05-09 14:29:06.027 UTC | 5 | 2022-05-30 02:24:18.983 UTC | null | null | null | null | 1,726,579 | null | 1 | 20 | toast|ionic2 | 40,403 | <p>You must add 'cssClass: "yourCssClassName"' in your toastCtrl function.</p>
<pre><code> let toast = Toast.create({
message: "Some text on one line. <br /><br /> Some text on another line.",
duration: 15000,
showCloseButton: true,
closeButtonText: 'Got it!',
dismissOnPageChange: true,
cssClass: "yourCssClassName",
});
</code></pre>
<p>than you can add any feature to the your css class. But your css feature went outside the default page'css. Exmp:</p>
<pre><code> page-your.page.scss.name {
//bla bla
}
.yourCssClassName {
text-align:center;
}
</code></pre> |
28,342,736 | Java GC (Allocation Failure) | <p>Why always "GC (Allocation Failure)"?</p>
<p>Java HotSpot(TM) 64-Bit Server VM (25.25-b02) for linux-amd64 JRE (<strong>1.8.0_25</strong>-b17), </p>
<pre><code>CommandLine flags:
-XX:CMSInitiatingOccupancyFraction=60
-XX:GCLogFileSize=10485760
-XX:+HeapDumpOnOutOfMemoryError
-XX:InitialHeapSize=32212254720
-XX:MaxHeapSize=32212254720
-XX:NewRatio=10
-XX:OldPLABSize=16
-XX:ParallelGCThreads=4
-XX:+PrintGC
-XX:+PrintGCDetails
-XX:+PrintGCTimeStamps
-XX:+PrintStringTableStatistics
-XX:+PrintTenuringDistribution
-XX:StringTableSize=1000003
-XX:SurvivorRatio=4
-XX:TargetSurvivorRatio=50
-XX:+UseCompressedClassPointers
-XX:+UseCompressedOops
-XX:+UseParNewGC
-XX:+UseConcMarkSweepGC
</code></pre>
<pre><code>27.329: [GC (Allocation Failure) 27.329: [ParNew
Desired survivor size 44728320 bytes, new threshold 15 (max 15)
- age 1: 16885304 bytes, 16885304 total
: 349568K->16618K(436928K), 0.2069129 secs] 349568K->16618K(31369920K), 0.2070712 secs] [Times: user=0.78 sys=0.04, real=0.21 secs]
28.210: [GC (Allocation Failure) 28.210: [ParNew
Desired survivor size 44728320 bytes, new threshold 15 (max 15)
- age 1: 28866504 bytes, 28866504 total
- age 2: 12582536 bytes, 41449040 total
: 366186K->47987K(436928K), 0.2144807 secs] 366186K->47987K(31369920K), 0.2146024 secs] [Times: user=0.84 sys=0.01, real=0.22 secs]
29.037: [GC (Allocation Failure) 29.038: [ParNew
Desired survivor size 44728320 bytes, new threshold 2 (max 15)
- age 1: 28443488 bytes, 28443488 total
- age 2: 28386624 bytes, 56830112 total
- age 3: 12579928 bytes, 69410040 total
: 397555K->76018K(436928K), 0.2357352 secs] 397555K->76018K(31369920K), 0.2358535 secs] [Times: user=0.93 sys=0.01, real=0.23 secs]
</code></pre> | 28,357,523 | 3 | 0 | null | 2015-02-05 11:26:42.95 UTC | 28 | 2019-03-18 08:51:17.277 UTC | 2019-03-18 08:44:59.81 UTC | null | 2,361,308 | null | 3,644,708 | null | 1 | 155 | java|garbage-collection | 273,138 | <p>"Allocation Failure" is a cause of GC cycle to kick in.</p>
<p>"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.</p>
<p>Older JVM were not printing GC cause for minor GC cycles.</p>
<p>"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if <code>+XX:+ScavengeBeforeRemark</code> is enabled).</p> |
48,626,193 | logical(0) in if statement | <p>This line: </p>
<pre><code>which(!is.na(c(NA,NA,NA))) == 0
</code></pre>
<p>produces <code>logical(0)</code></p>
<p>While this line</p>
<pre><code>if(which(!is.na(c(NA,NA,NA))) == 0){print('TRUE')}
</code></pre>
<p>generates:</p>
<pre><code>Error in if (which(!is.na(c(NA, NA, NA))) == 0) { :
argument is of length zero
</code></pre>
<p>Why there is an error? What is logical(0)</p> | 48,626,314 | 4 | 3 | null | 2018-02-05 15:42:22.88 UTC | 3 | 2020-03-05 20:37:37.647 UTC | 2018-06-22 15:48:00.033 UTC | null | 7,852,833 | null | 1,700,890 | null | 1 | 21 | r|if-statement|na | 43,589 | <p><code>logical(0)</code> is a vector of base type logical with 0 length. You're getting this because your asking which elements of this vector equal 0:</p>
<pre><code>> !is.na(c(NA, NA, NA))
[1] FALSE FALSE FALSE
> which(!is.na(c(NA, NA, NA))) == 0
logical(0)
</code></pre>
<p>In the next line, you're asking if that zero length vector <code>logical(0)</code> is equal to 0, which it isn't. You're getting an error because you can't compare a vector of 0 length with a scalar.</p>
<p>Instead you could check whether the length of that first vector is 0:</p>
<pre><code>if(length(which(!is.na(c(NA,NA,NA)))) == 0){print('TRUE')}
</code></pre> |
8,556,817 | Uncompile Development Asset Pipeline | <p>I was compiling my asset pipeline for my production environment and it did for all my environments. How can I uncompile my asset pipeline for my development environment?</p>
<p>I have checked my config/development environment and cannot find a fix.</p>
<p>Thanks in advance for any help...</p> | 8,574,752 | 4 | 0 | null | 2011-12-19 03:29:34.683 UTC | 9 | 2017-06-05 17:55:28.52 UTC | null | null | null | null | 976,975 | null | 1 | 45 | ruby-on-rails|ruby|ruby-on-rails-3.1|asset-pipeline | 19,587 | <p>To remove precompiled assets use:</p>
<pre><code>rake assets:clean
</code></pre>
<p>What this basically does is remove the <code>public/assets</code> directory. You may need to include the <code>RAILS_ENV</code> variable if you need to run it for a certain environment.</p> |
27,406,994 | Http requests withCredentials what is this and why using it? | <p>I had a problem with CORS with node and angular and adding this option with true solved my problem.
But I don't find info about what it is and what it is doing.
Please can someone explain?</p> | 27,407,440 | 2 | 2 | null | 2014-12-10 17:16:32.12 UTC | 16 | 2020-11-20 21:17:52.913 UTC | 2019-08-26 10:52:07.37 UTC | null | 3,710,195 | user4207046 | null | null | 1 | 45 | javascript|angularjs|http | 34,613 | <p><strong>Short answer:</strong></p>
<p><code>withCredentials()</code> makes your browser include cookies and authentication headers in your XHR request. If your service depends on any cookie (including session cookies), it will only work with this option set.</p>
<p><strong>Longer explanation:</strong></p>
<p>When you issue an Ajax request to a different origin server, the browser may send an OPTIONS pre-flight request to the server to discover the CORS policy of the endpoint (for non-GET requests).</p>
<p>Since the request may have been triggered by a malicious script, to avoid automatically leaking authentication information to the remote server, the browser applies the following rules :</p>
<p>For GET requests, include cookie and authentication information in the server request :</p>
<ul>
<li>if XHR client is invoked with the <code>withCredentials</code> option is set to true</li>
<li>and if the server reply does not include the CORS header <code>Access-Control-Allow-Credentials: true</code>, discard response before returning the object to Javascript</li>
</ul>
<p>For non GET requests, include cookie and authentication information only:</p>
<ul>
<li>if <code>withCredentials</code> is set to true on the XHR object</li>
<li>and the server has included the CORS header <code>Access-Control-Allow-Credentials: true</code> in the pre-flight OPTIONS</li>
</ul> |
27,057,449 | When switch fragment with SwipeRefreshLayout during refreshing, fragment freezes but actually still work | <p><strong>UPDATE: I thought it worked correctly. But after some test trouble still exists *sniff*</strong></p>
<p>Then I made a simpler version to see what exactly happen and I get to know that the refreshing fragment which should have been detached still left there. Or exactly, the view of the old fragment left there, <strong>on top of</strong> the newer fragment. Since RecyclerView's background of my original app is not transparent, so It turned out what I said before.</p>
<p><strong>END OF UPDATE</strong></p>
<hr>
<p>I have a <code>MainActivity</code> with layout like this:</p>
<pre><code><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start" tools:layout="@layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>The fragment <code>ContentView</code> I use to fill <code>@id/container</code> is configured as:</p>
<pre><code><android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contentView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/tweet_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/grey_300"/>
</android.support.v4.widget.SwipeRefreshLayout>
</code></pre>
<p>And here is <code>onCreateView()</code> of <code>ContentView</code></p>
<pre><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inflatedView = inflater.inflate(R.layout.fragment_content, container, false);
mRecyclerView = (RecyclerView) inflatedView.findViewById(R.id.tweet_list);
mRecyclerView.setHasFixedSize(false);
mLinearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mTweetList = new ArrayList<Tweet>;
mAdapter = new TweetAdapter(mTweetList);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mSwipeRefreshLayout = (SwipeRefreshLayout) inflatedView.findViewById(R.id.contentView);
mSwipeRefreshLayout.setOnRefreshListener(
...
);
return inflatedView;
}
</code></pre>
<p>Then in <code>MainActivity</code> I switch the content to display by switching different <code>ContentView</code>. All looks good except one thing: when I switch <code>ContentView</code> fragments DURING refreshing by navigation drawer, then content freezes. But actually all things work as usual except you cannot see it.</p> | 27,073,879 | 8 | 2 | null | 2014-11-21 08:56:03.553 UTC | 23 | 2017-02-18 12:47:37.967 UTC | 2014-11-21 16:05:33.4 UTC | null | 1,321,916 | null | 1,321,916 | null | 1 | 75 | android|android-fragments|android-recyclerview|swiperefreshlayout | 15,162 | <p>Well... After some struggling I eventually solved this problem by myself, in a tricky way...</p>
<p>I just need to add these in <code>onPause()</code> :</p>
<pre><code>@Override
public void onPause() {
super.onPause();
...
if (mSwipeRefreshLayout!=null) {
mSwipeRefreshLayout.setRefreshing(false);
mSwipeRefreshLayout.destroyDrawingCache();
mSwipeRefreshLayout.clearAnimation();
}
}
</code></pre> |
30,543,409 | How to check if a Docker image with a specific tag exist locally? | <p>I'd like to find out if a Docker image with a specific tag exists locally. I'm fine by using a bash script if the Docker client cannot do this natively.</p>
<p>Just to provide some hints for a potential bash script the result of running the <code>docker images</code> command returns the following:</p>
<pre><code>REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
rabbitmq latest e8e654c05c91 5 weeks ago 143.5 MB
busybox latest 8c2e06607696 6 weeks ago 2.433 MB
rabbitmq 3.4.4 a4fbaad9f996 11 weeks ago 131.5 MB
</code></pre> | 30,543,453 | 13 | 0 | null | 2015-05-30 07:11:39.47 UTC | 29 | 2022-02-03 20:11:48.537 UTC | null | null | null | null | 398,441 | null | 1 | 167 | bash|docker | 158,855 | <p>I usually test the result of <a href="http://docs.docker.com/engine/reference/commandline/images/" rel="noreferrer"><code>docker images -q</code></a> (as in <a href="https://github.com/VonC/b2d/blob/2d671bbe1311b63b24e7b8b495e3055dc5c5f97b/apache/build#L6-L8" rel="noreferrer">this script</a>):</p>
<pre><code>if [[ "$(docker images -q myimage:mytag 2> /dev/null)" == "" ]]; then
# do something
fi
</code></pre>
<p>But <del>since <code>docker images</code> only takes <code>REPOSITORY</code> as parameter, you would need to grep on tag, without using <code>-q</code></del>.</p>
<p><a href="http://docs.docker.com/engine/reference/commandline/images/" rel="noreferrer"><code>docker images</code></a> takes tags now (docker 1.8+) <code>[REPOSITORY[:TAG]]</code></p>
<p>The other approach mentioned below is to use <a href="https://docs.docker.com/engine/reference/commandline/inspect/" rel="noreferrer">docker inspect</a>.<br />
But with docker 17+, the syntax for images is: <strong><a href="https://docs.docker.com/engine/reference/commandline/image_inspect/" rel="noreferrer"><code>docker image inspect</code></a></strong> (on an non-existent image, the <a href="https://github.com/moby/moby/issues/354" rel="noreferrer">exit status will be non-0</a>)</p>
<p>As noted by <a href="https://stackoverflow.com/users/288280/itayb">iTayb</a> in <a href="https://stackoverflow.com/questions/30543409/how-to-check-if-a-docker-image-with-a-specific-tag-exist-locally/30543453?noredirect=1#comment108525095_30543453">the comments</a>:</p>
<ul>
<li>The <code>docker images -q</code> method can get really slow on a machine with lots of images. It takes 44s to run on a 6,500 images machine.</li>
<li>The <code>docker image inspect</code> returns immediately.</li>
</ul>
<hr />
<p>As noted in the comments by <a href="https://stackoverflow.com/users/3150057/henry-blyth">Henry Blyth</a>:</p>
<blockquote>
<p>If you use <code>docker image inspect my_image:my_tag</code>, and you want to ignore the output, you can add <code>--format="ignore me"</code> and it will print that literally.</p>
<p>You can also redirect stdout by adding <code>>/dev/null</code> but, if you can't do that in your script, then the format option works cleanly.</p>
</blockquote> |
55,070,723 | How do I change from a PR to a draft PR at github? | <p>Github release the <a href="https://github.blog/2019-02-14-introducing-draft-pull-requests/" rel="noreferrer">draft PR</a> a while ago.</p>
<p>I have a normal PR and I wanted to change that to a draft PR. How can I do that?</p> | 55,154,745 | 6 | 2 | null | 2019-03-08 20:43:20.273 UTC | 5 | 2020-12-16 18:23:56.317 UTC | null | null | null | null | 7,684,024 | null | 1 | 123 | github|pull-request | 37,115 | <h2>Update - Now Available - Jan 2020</h2>
<h3>Convert Default → Draft</h3>
<p>This is possible now, with an option below "Reviewers" section in PR.</p>
<p><a href="https://i.stack.imgur.com/hSnnw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hSnnw.png" alt="convert to draft screenshot" /></a></p>
<p>See: <a href="https://github.community/t/feature-request-switch-from-ready-to-draft-in-pull-requests/1749/63" rel="noreferrer">Feature Request: Switch from ready to draft in pull requests</a></p>
<h3>Convert Draft → Default</h3>
<p>To answer <a href="https://stackoverflow.com/users/4378314/marsandback">@marsandback</a> comment Draft PR --> PR, just click the Ready for review</p>
<p><a href="https://i.stack.imgur.com/ZrXLu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZrXLu.png" alt="draft screenshot" /></a></p> |
20,381,677 | In a git merge conflict, what are the BACKUP, BASE, LOCAL, and REMOTE files that are generated? | <p>I assume the LOCAL and REMOTE files are just what their name suggests, but what are BASE and BACKUP for?</p> | 20,382,333 | 3 | 0 | null | 2013-12-04 17:14:02.46 UTC | 45 | 2022-05-20 19:41:34.547 UTC | null | null | null | null | 3,015,278 | null | 1 | 169 | git | 80,107 | <p>Git performs a three-way merge, finding the common ancestor (aka "merge base") of the two branches you are merging. When you invoke <code>git mergetool</code> on a conflict, it will produce these files suitable for feeding into a typical 3-way merge tool. Thus:</p>
<ul>
<li><code>foo.LOCAL</code>: the "ours" side of the conflict - ie, your branch (<code>HEAD</code>) that will contain the results of the merge</li>
<li><code>foo.REMOTE</code>: the "theirs" side of the conflict - the branch you are merging into <code>HEAD</code></li>
<li><code>foo.BASE</code>: the common ancestor. useful for feeding into a three-way merge tool</li>
<li><code>foo.BACKUP</code>: the contents of file before invoking the merge tool, will be kept on the filesystem if <code>mergetool.keepBackup = true</code>.</li>
</ul> |
1,374,737 | How can I create a unique index in Oracle but ignore nulls? | <p>I am trying to create a unique constraint on two fields in a table. However, there is a high likelihood that one will be null. I only require that they be unique if both are not null (<code>name</code> will never be null).</p>
<pre><code>create unique index "name_and_email" on user(name, email);
</code></pre>
<p>Ignore the semantics of the table and field names and whether that makes sense - I just made some up.</p>
<p>Is there a way to create a unique constraint on these fields that will enforce uniqueness for two not null values, but ignore if there are multiple entries where <code>name</code> is not null and <code>email</code> is null?</p>
<p>This question is for SQL Server, and I'm hoping that the answer is not the same:
<a href="https://stackoverflow.com/questions/767657/how-do-i-create-unique-constraint-that-also-allows-nulls-in-sql-server">How do I create a unique constraint that also allows nulls?</a></p> | 1,374,806 | 2 | 0 | null | 2009-09-03 17:09:39.417 UTC | 1 | 2020-07-06 13:51:54.463 UTC | 2017-05-23 12:13:37.003 UTC | null | -1 | null | 3,078 | null | 1 | 27 | sql|oracle|ddl | 38,761 | <p>We can do this with a function-based index. The following makes use of <code>NVL2()</code> which, as you know, returns one value if the expression is not null and a different value if it is null. You could use <code>CASE()</code> instead. </p>
<pre><code>SQL> create table blah (name varchar2(10), email varchar2(20))
2 /
Table created.
SQL> create unique index blah_uidx on blah
2 (nvl2(email, name, null), nvl2(name, email, null))
3 /
Index created.
SQL> insert into blah values ('APC', null)
2 /
1 row created.
SQL> insert into blah values ('APC', null)
2 /
1 row created.
SQL> insert into blah values (null, '[email protected]')
2 /
1 row created.
SQL> insert into blah values (null, '[email protected]')
2 /
1 row created.
SQL> insert into blah values ('APC', '[email protected]')
2 /
1 row created.
SQL> insert into blah values ('APC', '[email protected]')
2 /
insert into blah values ('APC', '[email protected]')
*
ERROR at line 1:
ORA-00001: unique constraint (APC.BLAH_UIDX) violated
SQL>
</code></pre>
<p><strong>Edit</strong></p>
<p>Because in your scenario name will always be populated you will only need an index like this:</p>
<pre><code>SQL> create unique index blah_uidx on blah
2 (nvl2(email, name, null), email)
3 /
Index created.
SQL>
</code></pre> |
1,896,102 | Applying Multiple Window Functions On Same Partition | <p>Is it possible to apply multiple window functions to the same partition? (Correct me if I'm not using the right vocabulary)</p>
<p>For example you can do</p>
<pre><code>SELECT name, first_value() over (partition by name order by date) from table1
</code></pre>
<p>But is there a way to do something like:</p>
<pre><code>SELECT name, (first_value() as f, last_value() as l (partition by name order by date)) from table1
</code></pre>
<p>Where we are applying two functions onto the same window?</p>
<p>Reference:
<a href="http://postgresql.ro/docs/8.4/static/tutorial-window.html" rel="noreferrer">http://postgresql.ro/docs/8.4/static/tutorial-window.html</a></p> | 1,896,108 | 2 | 0 | null | 2009-12-13 10:25:38.08 UTC | 11 | 2020-02-16 10:09:44.963 UTC | 2014-10-01 13:38:12.357 UTC | null | 330,315 | null | 84,399 | null | 1 | 27 | sql|postgresql|window-functions | 26,763 | <p>Can you not just use the window per selection</p>
<p>Something like</p>
<pre><code>SELECT name,
first_value() OVER (partition by name order by date) as f,
last_value() OVER (partition by name order by date) as l
from table1
</code></pre>
<p>Also from your reference you can do it like this</p>
<pre><code>SELECT sum(salary) OVER w, avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC)
</code></pre> |
1,523,173 | Decimal(3,2) values in MySQL are always 9.99 | <p>I have a field, justsomenum, of type decimal(3,2) in MySQL that seems to always have values of 9.99 when I insert something like 78.3. Why?</p>
<p>This is what my table looks like:</p>
<pre><code>mysql> describe testtable;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| firstname | varchar(20) | YES | | NULL | |
| lastname | varchar(20) | YES | | NULL | |
| justsomenum | decimal(3,2) | YES | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
</code></pre>
<p>When I insert something like this and the select:</p>
<pre><code>mysql> insert into testtable (firstname, lastname, justsomenum) values ("Lloyd", "Christmas", 83.5);
</code></pre>
<p>I get 9.99 when I select.</p>
<pre><code>mysql> select * from testtable;
+----+-----------+-----------+---------------+
| id | firstname | lastname | justsomenum |
+----+-----------+-----------+---------------+
| 1 | Shooter | McGavin | 9.99 |
| 2 | Lloyd | Christmas | 9.99 |
| 3 | Lloyd | Christmas | 9.99 |
| 4 | Lloyd | Christmas | 9.99 |
+----+-----------+-----------+---------------+
4 rows in set (0.00 sec)
</code></pre>
<p>This is MySQL 5.0.86 on Mac OS X 10.5.8.</p>
<p>Any ideas? Thanks.</p> | 1,523,182 | 2 | 2 | null | 2009-10-06 01:16:25.95 UTC | 8 | 2021-12-15 19:53:42.747 UTC | 2009-10-06 01:31:23.63 UTC | null | 24,643 | null | 24,643 | null | 1 | 37 | sql|mysql | 56,367 | <p>The maximum value for <code>decimal(3, 2)</code> is 9.99, so when you try to insert something larger than that, it is capped to 9.99. Try <code>decimal(5, 2)</code> or something else if you want to store larger numbers.</p>
<p>The first argument is the total number of digits of precision, and the second argument is the number of digits after the decimal point.</p> |
2,158,780 | catching an error and then branching logic | <p>How do I write R code that allows me to execute a different path in my code if an error condition happens? I'm using a function that tends to throw an error. When it meets an error condition I would like to execute a different function. Here's a specific example:</p>
<pre><code>require(SuppDists)
parms <- structure(list(gamma = -0.841109044800762, delta = 0.768672140584442,
xi = -0.359199299528801, lambda = 0.522761187947026, type = "SB"), .Names = c("gamma",
"delta", "xi", "lambda", "type"))
pJohnson(.18, parms)
</code></pre>
<p>the pJohnson function should fail with the following error:</p>
<pre><code> Error in pJohnson(0.18, parms) :
Sb values out of range.
</code></pre>
<p>I can make the error go silent by using:</p>
<pre><code>try( pJohnson(.18, parms), silent=T)
</code></pre>
<p>but what I really want to do is execute the function <code>alternativeFunction()</code> if <code>pJohnson(.18, parms)</code> returns an error. </p>
<p>It seems like the <code>withCallingHandlers()</code> function should help me out, but I can't figure out how to capture the error and make it run the <code>alternativeFunction()</code> only upon an error condition. </p> | 2,158,803 | 2 | 0 | null | 2010-01-28 23:25:22.943 UTC | 16 | 2015-10-25 21:40:31.637 UTC | 2015-10-25 21:40:31.637 UTC | null | 3,671,495 | null | 37,751 | null | 1 | 51 | r|error-handling | 41,215 | <pre><code>t <- try(pJohnson(.18, parms))
if("try-error" %in% class(t)) alternativeFunction()
</code></pre> |
45,812,387 | How to validate structure (or schema) of dictionary in Python? | <p>I have a dictionary with config info:</p>
<pre><code>my_conf = {
'version': 1,
'info': {
'conf_one': 2.5,
'conf_two': 'foo',
'conf_three': False,
'optional_conf': 'bar'
}
}
</code></pre>
<p>I want to check if the dictionary follows the structure I need.</p>
<p>I'm looking for something like this:</p>
<pre><code>conf_structure = {
'version': int,
'info': {
'conf_one': float,
'conf_two': str,
'conf_three': bool
}
}
is_ok = check_structure(conf_structure, my_conf)
</code></pre>
<p>Is there any solution done to this problem or any library that could make implementing <code>check_structure</code> more easy?</p> | 45,812,573 | 10 | 2 | null | 2017-08-22 08:17:40.163 UTC | 19 | 2022-01-20 11:09:01.563 UTC | 2017-08-22 09:38:07.973 UTC | null | 1,550,807 | null | 1,988,428 | null | 1 | 39 | python|validation|dictionary|schema|config | 51,022 | <p>Without using libraries, you could also define a simple recursive function like this:</p>
<pre><code>def check_structure(struct, conf):
if isinstance(struct, dict) and isinstance(conf, dict):
# struct is a dict of types or other dicts
return all(k in conf and check_structure(struct[k], conf[k]) for k in struct)
if isinstance(struct, list) and isinstance(conf, list):
# struct is list in the form [type or dict]
return all(check_structure(struct[0], c) for c in conf)
elif isinstance(struct, type):
# struct is the type of conf
return isinstance(conf, struct)
else:
# struct is neither a dict, nor list, not type
return False
</code></pre>
<p>This assumes that the config can have keys that are not in your structure, as in your example.</p>
<hr>
<p>Update: New version also supports lists, e.g. like <code>'foo': [{'bar': int}]</code> </p> |
6,163,452 | Moving packages eclipse | <p>Maybe a stupid question but I have two packages in eclipse and now I would like to move the one package into the other for better structure.</p>
<p>Now I tried move but that generates a copy into the same package.</p>
<p>And with refactoring -> move I even can't select the packages</p>
<p>Can anyone help me....</p>
<p>thx all</p> | 6,163,710 | 6 | 1 | null | 2011-05-28 18:02:19.2 UTC | 3 | 2019-09-17 09:30:49.447 UTC | null | null | null | null | 753,983 | null | 1 | 47 | eclipse | 28,653 | <p>If you have <code>com.company.foo</code> and <code>com.company.bar</code>, and want to move <code>foo</code> into <code>bar</code>, then just rename <code>com.company.foo</code> to <code>com.company.bar.foo</code>.</p>
<p>If you package happens to have subpackages, tick <code>Rename subpackages</code> to move the subpackages as well.</p> |
6,138,666 | How to unit test constructors | <p>I have a class I am adding unit tests to. The class has several constructors which take different types and converts them into a canonical form, which can then be converted into other types.</p>
<pre><code>public class Money {
public Money(long l) {
this.value = l;
}
public Money(String s) {
this.value = toLong(s);
}
public long getLong() {
return this.value;
}
public String getString() {
return toString(this.value);
}
}
</code></pre>
<p>In reality there are a couple of other types it accepts and converts to.</p>
<p>I am trying to work out what the most appropriate way to test these constructors is.</p>
<p>Should there be a test per-constructor and output type:</p>
<pre><code>@Test
public void longConstructor_getLong_MatchesValuePassedToConstructor() {
final long value = 1.00l;
Money m = new Money(value);
long result = m.getLong();
assertEquals(value, result);
}
</code></pre>
<p>This leads to a lot of different tests. As you can see, I'm struggling to name them.</p>
<p>Should there be multiple asserts:</p>
<pre><code>@Test
public void longConstructor_outputsMatchValuePassedToConstructor() {
final long longValue = 1.00l;
final String stringResult = "1.00";
Money m = new Money(longValue);
assertEquals(longValue, m.getLong());
assertEquals(stringResult, m.getString());
}
</code></pre>
<p>This has multiple asserts, which makes me uncomfortable. It is also testing getString (and by proxy toString) but not stating that in the test name. Naming these are even harder.</p>
<p>Am I going about it completely wrong by focussing on the constructors. Should I just test the conversion methods? But then the following test will miss the <code>toLong</code> method.</p>
<pre><code>@Test
public void getString_MatchesValuePassedToConstructor() {
final long value = 1.00;
final String expectedResult = "1.00";
Money m = new Money(value);
String result = m.getLong();
assertEquals(expectedResult, result);
}
</code></pre>
<p>This is a legacy class and I can't change the original class.</p> | 6,138,724 | 7 | 2 | null | 2011-05-26 12:44:22.187 UTC | 10 | 2018-11-09 16:57:47.07 UTC | 2011-05-26 12:45:16.48 UTC | null | 160,206 | null | 214 | null | 1 | 42 | java|unit-testing | 91,053 | <p>It looks like you've got a canonical way of getting the "raw" value (<code>toLong</code> in this case) - so just test that all the constructors are correct when you fetch <em>that</em> value. Then you can test other methods (such as <code>getString()</code>) based on a single constructor, as you know that once the various constructors have finished, they all leave the object in the same state.</p>
<p>This is assuming somewhat white-box testing - i.e. you <em>know</em> that <code>toLong</code> is really a simple reflection of the internal state, so it's okay to test that + a constructor in a test.</p> |
6,017,987 | How can I list all the deleted files in a Git repository? | <p>I know Git stores information of when files get deleted and I am able to check individual commits to see which files have been removed, but is there a command that would generate a list of every deleted file across a repository's lifespan?</p> | 6,018,043 | 9 | 1 | null | 2011-05-16 13:15:27.38 UTC | 97 | 2022-07-05 05:05:06.86 UTC | 2020-05-13 22:25:24.86 UTC | null | 63,550 | null | 197,302 | null | 1 | 364 | git | 140,886 | <pre><code>git log --diff-filter=D --summary
</code></pre>
<p>See <a href="https://stackoverflow.com/questions/953481/restore-a-deleted-file-in-a-git-repo">Find and restore a deleted file in a Git repository</a></p>
<p>If you don't want all the information about which commit they were removed in, you can just add a <code>grep delete</code> in there.</p>
<pre><code>git log --diff-filter=D --summary | grep delete
</code></pre> |
6,186,770 | Ajax request returns 200 OK, but an error event is fired instead of success | <p>I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns <strong>200 OK</strong>, but <strong>jQuery</strong> executes the error event.<br>
I tried a lot of things, but I could not figure out the problem. I am adding my code below:</p>
<h3>jQuery Code</h3>
<pre><code>var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
</code></pre>
<h3>C# code for <code>JqueryOpeartion.aspx</code></h3>
<pre><code>protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
</code></pre>
<p>I need the <code>("Record deleted")</code> string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?</p> | 6,186,905 | 14 | 10 | null | 2011-05-31 11:17:38.467 UTC | 118 | 2021-03-19 12:18:25.963 UTC | 2020-04-17 18:36:00.723 UTC | user6269864 | 806,202 | null | 165,107 | null | 1 | 895 | javascript|jquery|asp.net|ajax|json | 428,348 | <p><a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer"><code>jQuery.ajax</code></a> attempts to convert the response body depending on the specified <code>dataType</code> parameter or the <code>Content-Type</code> header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.</p>
<hr>
<p>Your AJAX code contains:</p>
<pre><code>dataType: "json"
</code></pre>
<p>In this case jQuery:</p>
<blockquote>
<p>Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.</p>
</blockquote>
<p>Your server-side code returns HTML snippet with <code>200 OK</code> status. jQuery was expecting valid JSON and therefore fires the error callback complaining about <code>parseerror</code>.</p>
<p>The solution is to remove the <code>dataType</code> parameter from your jQuery code and make the server-side code return:</p>
<pre><code>Content-Type: application/javascript
alert("Record Deleted");
</code></pre>
<p>But I would rather suggest returning a JSON response and display the message inside the success callback:</p>
<pre><code>Content-Type: application/json
{"message": "Record deleted"}
</code></pre> |
17,825,677 | Extracting frames of a .avi file | <p>I am trying to write a c# code to extract each frame of a .avi file and save it into a provided directory. Do you know any suitable library to use for such purpose? </p>
<p>Note: The final release must work on all systems regardless of installed codec, or system architecture. It must not require the presence of another program (like MATLAB) on the machine.</p>
<p>Thanks in advance.
Tunc</p> | 17,826,426 | 2 | 0 | null | 2013-07-24 05:12:11.64 UTC | 8 | 2013-08-01 17:48:30.677 UTC | null | null | null | null | 2,591,099 | null | 1 | 12 | c#|video|video-processing | 24,324 | <p>This is not possible, unless you add some restrictions to your input avi files or have control over encoder used to create them. To get an image you will have to decode it first, and for that you will need an appropriate codec installed or deployed with your app. And i doubt its possible to account for every codec out there or install/deploy them all. So no, you won't be able to open <em>just any</em> avi file. You can, however, support the most popular (or common in your context) codecs. </p>
<p>The easiest way to do it is indeed using an FFMPEG, since its alredy includes some of the most common codecs (if you dont mind extra 30+Mb added to your app). As for wrappers, i used <a href="http://www.aforgenet.com/framework/docs/" rel="noreferrer">AForge</a> wrapper in the past and really liked it, because of how simple it is to work with. Here is an example from its docs:</p>
<pre><code>// create instance of video reader
VideoFileReader reader = new VideoFileReader( );
// open video file
reader.Open( "test.avi" );
// read 100 video frames out of it
for ( int i = 0; i < 100; i++ )
{
Bitmap videoFrame = reader.ReadVideoFrame( );
videoFrame.Save(i + ".bmp")
// dispose the frame when it is no longer required
videoFrame.Dispose( );
}
reader.Close( );
</code></pre>
<p>There is also a VfW (which is included in Windows by default) wrapper in AForge, if you want to keep it simple without involving external libraries. You will still need VfW compatible codecs installed tho (some of them are included in Windows by default, most are not).</p> |
27,634,843 | Akka.NET actor system in ASP.NET | <p>I created a service with a RESTful API in ASP.NET, hosted in IIS. Inside this service, I would like to create an actor system with Akka.NET.</p>
<p>Upon creating the actor system:</p>
<pre><code>var actorSystem = ActorSystem.Create("myActorSystem");
</code></pre>
<p>The following exception is thrown:</p>
<blockquote>
<p>A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.dll
Additional information: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.</p>
</blockquote>
<p>The actor system is inherently a concurrent system with asynchronous messages being exchanged between actors. As explained <a href="http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx/" rel="nofollow noreferrer">here</a>, this actor system would not survive IIS taking down the AppDomain, which is probably why the aforementioned exception is thrown.</p>
<p><a href="http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx" rel="nofollow noreferrer">This article</a> explains how to run background tasks in ASP.NET. However, I don't see how I could use this for my actor system, as I have no control over the lifecycle of background tasks that might be created by Akka.NET.</p>
<p>Is there a way to make this work, or should I abandon the idea of having an actor system in an ASP.NET application?</p>
<p>EDIT: I also saw a question on Stackoverflow about <a href="https://stackoverflow.com/questions/6668999/how-to-implement-a-rest-web-service-using-akka">implementing a REST service using Akka</a>. Any advice about a solution similar to the <a href="http://spray.io/" rel="nofollow noreferrer">Spray toolkit</a>, but working for Akka.NET would be welcome.</p> | 27,719,875 | 2 | 2 | null | 2014-12-24 09:47:00.663 UTC | 13 | 2022-03-22 16:10:30.417 UTC | 2017-05-23 12:24:33.133 UTC | null | -1 | null | 852,330 | null | 1 | 13 | asp.net|spray|hangfire|akka.net | 6,188 | <p>Keep your ActorSystem as a shared property in some static class container - this way you may access it from the rest of your application. Actor system initialization/disposal can be done by:</p>
<ul>
<li><strong>Global.asax</strong> - use <code>ActorSystem.Create(...)</code> inside Global.asax <code>Application_Start</code> and dispose it with <code>system.Shutdown()</code> on <code>Application_End</code>.</li>
<li><strong>OWIN</strong> - create actor system in OWIN's <code>Startup.Configuration</code> method and shut it down by binding to <em>host.OnAppDisposing</em> event (<a href="https://stackoverflow.com/questions/23317965/in-self-hosted-owin-web-api-how-to-run-code-at-shutdown">how-to link</a>).</li>
</ul>
<p>Remember that IIS will startup your web app only after first request and tear it down automatically after some time when it's idle. Therefore make sure, that your deployment script will ping application after publishing and set idle timeout (<a href="http://technet.microsoft.com/en-us/library/cc771956%28v=ws.10%29.aspx" rel="nofollow noreferrer">link</a>) for long enough if you want your Akka actor system to run continuously.</p>
<p><strong>Second option</strong></p>
<p>Separate your Actor System logic and deploy it, for example, as a Windows Service (or Linux deamon). Turn on Akka.Remoting for it and create a proxy client, which will forward all application long-running sensitive tasks to external service. Similar solution is often used for things such as schedulers or event buses, when your application logic must be working continuously.</p> |
9,129,959 | How to set a file to this drwxrwsrwx permission on ubuntu | <p>How do I set my file permissions to this drwxrwsrwx? I need it to be the same as my folders.</p>
<p>Thanks</p> | 9,130,236 | 2 | 0 | null | 2012-02-03 14:12:27.033 UTC | 4 | 2012-02-03 19:29:40.313 UTC | null | null | null | null | 1,087,234 | null | 1 | 10 | linux|ubuntu-11.04 | 60,059 | <p><strong><em>Edit: Correct Answer is by user112358132134</em></strong></p>
<hr>
<p>My wrong answer:</p>
<p>The first character of <code>drwxrwsrwx</code> is <code>d</code> and that means directory. You won't be able to set a file so that it's a directory, because it's a file :)</p>
<p>To set all files in the current directory to <code>-rwxrwsrwx</code> you can use <code>chmod 777 *</code></p>
<p>To do this recursively, from the current directory use: <code>chmod -R 777 *</code></p>
<p>Try <code>man chmod</code> for more info. Hope this helps.</p>
<hr>
<p><strong><em>Edit: Correct Answer is by user112358132134</em></strong></p>
<hr>
<p>Edit: Me checking:</p>
<p><img src="https://i.stack.imgur.com/U2D8u.png" alt="enter image description here"></p> |
9,538,868 | Prevent BODY from scrolling when a modal is opened | <p>I want my body to stop scrolling when using the mousewheel while the Modal (from <a href="http://twitter.github.com/bootstrap" rel="noreferrer">http://twitter.github.com/bootstrap</a>) on my website is opened.</p>
<p>I've tried to call the piece of javascript below when the modal is opened but without success</p>
<pre><code>$(window).scroll(function() { return false; });
</code></pre>
<p>AND</p>
<pre><code>$(window).live('scroll', function() { return false; });
</code></pre>
<p>Please note our website dropped support for IE6, IE7+ needs to be compatible though.</p> | 11,013,994 | 50 | 0 | null | 2012-03-02 19:00:08.4 UTC | 125 | 2022-08-23 10:26:36.377 UTC | 2020-02-22 14:16:47.45 UTC | null | 6,904,888 | null | 1,024,322 | null | 1 | 410 | javascript|jquery|css|scroll | 635,428 | <p>Bootstrap's <code>modal</code> automatically adds the class <code>modal-open</code> to the body when a modal dialog is shown and removes it when the dialog is hidden. You can therefore add the following to your CSS:</p>
<pre><code>body.modal-open {
overflow: hidden;
}
</code></pre>
<p>You could argue that the code above belongs to the Bootstrap CSS code base, but this is an easy fix to add it to your site.</p>
<p><strong>Update 8th feb, 2013</strong><br>
This has now stopped working in Twitter Bootstrap v. 2.3.0 -- they no longer add the <code>modal-open</code> class to the body.</p>
<p>A workaround would be to add the class to the body when the modal is about to be shown, and remove it when the modal is closed:</p>
<pre><code>$("#myModal").on("show", function () {
$("body").addClass("modal-open");
}).on("hidden", function () {
$("body").removeClass("modal-open")
});
</code></pre>
<p><strong>Update 11th march, 2013</strong>
Looks like the <code>modal-open</code> class will return in Bootstrap 3.0, explicitly for the purpose of preventing the scroll: </p>
<blockquote>
<p>Reintroduces .modal-open on the body (so we can nuke the scroll there)</p>
</blockquote>
<p>See this: <a href="https://github.com/twitter/bootstrap/pull/6342" rel="noreferrer">https://github.com/twitter/bootstrap/pull/6342</a> - look at the <strong>Modal</strong> section.</p> |
29,944,985 | Is there a way to pass auto as an argument in C++? | <p>Is there a way to pass auto as an argument to another function?</p>
<pre><code>int function(auto data)
{
//DOES something
}
</code></pre> | 60,355,539 | 4 | 5 | null | 2015-04-29 13:17:54.113 UTC | 7 | 2020-03-26 15:03:59.21 UTC | 2015-04-29 22:15:15.54 UTC | null | 1,366,431 | null | 3,639,557 | null | 1 | 63 | c++|function|arguments|auto | 40,762 | <h2>C++20 allows <code>auto</code> as function parameter type</h2>
<p>This code is valid using C++20:</p>
<pre><code>int function(auto data) {
// do something, there is no constraint on data
}
</code></pre>
<p>As an <a href="https://en.cppreference.com/w/cpp/language/function_template#Abbreviated_function_template" rel="noreferrer">abbreviated function template</a>.</p>
<p>This is a special case of a non constraining type-constraint (i.e. <em>unconstrained auto parameter</em>).
Using concepts, the constraining type-constraint version (i.e. <em>constrained auto parameter</em>) would be for example:</p>
<pre><code>void function(const Sortable auto& data) {
// do something that requires data to be Sortable
// assuming there is a concept named Sortable
}
</code></pre>
<p>The wording in the spec, with the help of my friend <a href="https://stackoverflow.com/users/4299382/yehezkel-b">Yehezkel Bernat</a>:</p>
<blockquote>
<p><strong>9.2.8.5 Placeholder type specifiers</strong> <a href="http://eel.is/c++draft/dcl.spec.auto#:auto" rel="noreferrer">[dcl.spec.auto]</a></p>
<p><strong>placeholder-type-specifier:</strong></p>
<blockquote>
<p>type-constraint<sub>opt</sub> auto</p>
<p>type-constraint<sub>opt</sub> decltype ( auto )</p>
<blockquote>
<ol>
<li><p>A placeholder-type-specifier designates a
placeholder type that will be replaced later by deduction from an
initializer.</p></li>
<li><p>A placeholder-type-specifier of the form
type-constraint<sub>opt</sub> auto can be used in the decl-specifier-seq of a
parameter-declaration of a function declaration or lambda-expression
and signifies that the function is an <em>abbreviated function template</em>
(9.3.3.5) ...</p></li>
</ol>
</blockquote>
</blockquote>
</blockquote> |
30,759,367 | Apply list of functions to list of values | <p>In reference to <strong><a href="https://stackoverflow.com/questions/30758043/handling-na-values-in-apply-functions-returning-more-than-one-value">this question</a></strong>, I was trying to figure out the simplest way to apply a list of functions to a list of values. Basically, a nested <code>lapply</code>. For example, here we apply <code>sd</code> and <code>mean</code> to built in data set <code>trees</code>:</p>
<pre><code>funs <- list(sd=sd, mean=mean)
sapply(funs, function(x) sapply(trees, x))
</code></pre>
<p>to get:</p>
<pre><code> sd mean
Girth 3.138139 13.24839
Height 6.371813 76.00000
Volume 16.437846 30.17097
</code></pre>
<p>But I was hoping to avoid the inner <code>function</code> and have something like:</p>
<pre><code>sapply(funs, sapply, X=trees)
</code></pre>
<p>which doesn't work because <code>X</code> matches the first <code>sapply</code> instead of the second. We can do it with <code>functional::Curry</code>:</p>
<pre><code>sapply(funs, Curry(sapply, X=trees))
</code></pre>
<p>but I was hoping maybe there was a clever way to do this with positional and name matching that I'm missing.</p> | 30,764,197 | 4 | 2 | null | 2015-06-10 14:29:44.63 UTC | 16 | 2016-08-28 06:43:11.453 UTC | 2017-05-23 12:17:02.33 UTC | null | -1 | null | 2,725,969 | null | 1 | 31 | r|apply | 9,290 | <p>Since <code>mapply</code> use ellipsis <code>...</code> to pass vectors (atomics or lists) and not a named argument (X) as in <code>sapply, lapply, etc ...</code> you don't need to name the parameter <code>X = trees</code> if you use mapply instead of sapply : </p>
<pre><code>funs <- list(sd = sd, mean = mean)
x <- sapply(funs, function(x) sapply(trees, x))
y <- sapply(funs, mapply, trees)
> y
sd mean
Girth 3.138139 13.24839
Height 6.371813 76.00000
Volume 16.437846 30.17097
> identical(x, y)
[1] TRUE
</code></pre>
<p>You were one letter close to get what you were looking for ! :)</p>
<p>Note that I used a list for <code>funs</code>because I can't create a dataframe of functions, I got an error.</p>
<pre><code>> R.version.string
[1] "R version 3.1.3 (2015-03-09)"
</code></pre> |
31,205,640 | What is the difference between polyfill and transpiler? | <p>What is the difference between a polyfill and transpiler? </p>
<p>I often read the same term used in similar context.</p> | 31,206,361 | 6 | 2 | null | 2015-07-03 11:22:10.383 UTC | 14 | 2022-05-10 23:37:12.38 UTC | null | null | null | null | 339,167 | null | 1 | 46 | javascript | 10,874 | <p>Both approaches serve the same purpose: You can write code, that uses some features, which are not yet implemented in your target environment. They do this, however, by using different techniques.</p>
<p>A <strong>polyfill</strong> will try to emulate certain APIs, so can use them as if they were already implemented. </p>
<p>A <strong>transpiler</strong> on the other hand will transform your code and replace the respective code section by other code, which can already be executed.</p>
<p>Typically you use a polyfill, if your target browser did not yet implement the latest bleeding edge feature (read browser APIs) you want to use.
A transpiler on the other hand will let you use language features, the target environment does not support yet, e.g. some ES6 features like <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions">fat arrow functions</a>.</p> |
34,331,102 | How to display wrapping flex items as space-between with last row aligned left? | <p>I have a fixed-width container into which several variable-width elements must appear in a row, which can spill over into additional rows as necessary. </p>
<p>However, the beginning of each element must be aligned with the one on top of it, so in ASCII art it would look like so (say, padding of 1):</p>
<pre><code> /----------------------------------\
| |
| # One # Two # Three # Four |
| # Five # Six |
| |
\----------------------------------/
</code></pre>
<p>In other words:</p>
<ul>
<li>The first element of every row must be left-aligned</li>
<li>The last element of every row (except for the final row) must be right-aligned</li>
<li>Every element must be left-aligned to the element above it</li>
</ul>
<p>I'm trying to use flexbox for this without success.</p>
<p><a href="http://codepen.io/anon/pen/yeOLVK" rel="noreferrer">This</a> is the best I've come so far, using <code>flex-wrap: wrap</code> for the container and <code>flex-grow: 1</code> for the elements.</p>
<p>Problem is that the last row fills out to the edge.</p>
<pre><code>justify-content: flex-start; // this does nothing
</code></pre>
<p>If I take away <code>flow-grow: 1</code> then the elements aren't distributed equally. I also tried fiddling around with <code>last-of-type</code> on the elements but it's also not enough.</p>
<p>Is this even possible with <code>flexbox</code>, or am I going about it the wrong way?</p> | 34,335,559 | 12 | 2 | null | 2015-12-17 09:34:44.047 UTC | 5 | 2021-11-18 15:04:57.367 UTC | 2019-02-21 16:19:13.477 UTC | null | 2,756,409 | null | 4,551,542 | null | 1 | 55 | html|css|flexbox | 43,576 | <p>After trying the suggestions here (thanks!) and searching the web long and wide, I've reached the conclusion that this is simply not possible with flexbox. Any by that I mean that others have reached this conclusion while I stubbornly tried to make it work anyway, until finally giving up and accepting the wisdom of wiser people.</p>
<p>There are a couple of links I came across that might explain it better, or different aspects of the requirements, so I'm posting them here for... posterity.</p>
<p><a href="https://stackoverflow.com/questions/23274338/how-to-keep-wrapped-flex-items-the-same-width-as-the-elements-on-the-previous-ro">How to keep wrapped flex-items the same width as the elements on the previous row?</a></p>
<p><a href="http://fourkitchens.com/blog/article/responsive-multi-column-lists-flexbox" rel="noreferrer">http://fourkitchens.com/blog/article/responsive-multi-column-lists-flexbox</a></p> |
22,640,175 | Bootstrap Align Image with text | <p>I am trying to align an image on the left side with text using boostrap, and when page is viewed on mobile devices the images becomes centred on top of the text !</p>
<pre><code><div class="container">
<div class="row">
<h1>About Me</h1>
</class>
<div class="col-md-4">
<div class="imgAbt">
<img width="220" height="220" src="img/me.jpg">
</div>
</div>
<div class="col-md-8"><p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p></div>
</div>
</div>
</code></pre>
<p>I have also tried <code>.col-md-3 .col-md-pull-9</code> along with <code>.col-md-9 .col-md-push-3</code> , however I still was not able to achieve desired results, <a href="http://i.stack.imgur.com/e0Lu2.jpg">similar to this design</a></p> | 22,640,983 | 7 | 2 | null | 2014-03-25 16:09:04.403 UTC | 4 | 2020-05-14 10:36:48.98 UTC | 2014-03-27 23:08:19.027 UTC | null | 2,680,216 | null | 1,863,201 | null | 1 | 12 | html|css|twitter-bootstrap | 137,254 | <p>You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('http://getbootstrap.com/dist/css/bootstrap.css');</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<h1>About Me</h1>
<div class="row">
<div class="col-md-4">
<div class="imgAbt">
<img width="220" height="220" src="img/me.jpg" />
</div>
</div>
<div class="col-md-8">
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Or, if you wish the text to closely wrap the image, change your markup to:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('http://getbootstrap.com/dist/css/bootstrap.css');</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<h1>About Me</h1>
<div class="row">
<div class="col-md-12">
<img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>
</div>
</div></code></pre>
</div>
</div>
</p> |
7,078,282 | Remove all Gearman jobs from the Gearman Job Server | <p>Is there a way to remove all Gearman jobs from the Gearman Job Server? I have a PHP application that runs Gearman jobs in the background. For my unit tests I need to ensure that a) there are no jobs waiting for a worker that executes it and b) that there is no worker working. The latter is not that important because it is easy to kill the workers but the former--I don't know how to implement this.</p> | 8,850,243 | 2 | 3 | null | 2011-08-16 12:36:36.38 UTC | 9 | 2012-11-08 13:41:27.877 UTC | null | null | null | null | 865,334 | null | 1 | 14 | php|unit-testing|gearman | 18,354 | <h2>Removing all jobs of single type</h2>
<p>Use the following command (just replace <code>FUNCTION_NAME</code>):</p>
<pre><code>gearman -n -w -f FUNCTION_NAME > /dev/null
</code></pre>
<p>To remove only <code>n</code> number of jobs add <code>-c n</code> param, i.e. to remove 20 jobs:</p>
<pre><code>gearman -c 20 -n -w -f FUNCTION_NAME > /dev/null
</code></pre>
<p><br></p>
<h2>Removing all jobs from server</h2>
<p>If you want to remove all jobs, run the following loop:</p>
<pre><code>for MATCH in $(echo status | nc 127.0.0.1 4730 | grep -v \\. | grep -Pv '^[^\t]+\t0\t' | cut -s -f 1-2 --output-delimiter=\,);
do
gearman -n -w -f ${MATCH%\,*} -c ${MATCH#*\,} > /dev/null;
done
</code></pre>
<p>Replace <code>127.0.0.1 4730</code> with your gearmand server address and port.
<br><br></p>
<blockquote>
<blockquote>
<p>ps: removing jobs from persistent storage (i.e. sqlite) will not remove them from gearmand until it is restarted (because gearmand process has in-memory cache)</p>
</blockquote>
</blockquote> |
7,202,603 | jquery $.ajax jsonp | <pre><code>$.ajax({
type : "GET",
dataType : "jsonp",
url : '/',
data : {}
success: function(obj){
}
});
</code></pre>
<p>How can i use $.ajax dataType: jsonp cross-domain to post data?</p> | 7,202,641 | 2 | 5 | null | 2011-08-26 09:22:33.597 UTC | 8 | 2015-08-26 14:49:28.75 UTC | 2011-08-26 10:56:35.207 UTC | null | 855,395 | null | 767,177 | null | 1 | 16 | jquery|ajax|cross-domain|jsonp | 43,812 | <p>It's not possible with simple jsonp. Read <strong><a href="http://www.markhneedham.com/blog/2009/08/27/jquery-post-jsonp-and-cross-domain-requests/" rel="nofollow">this</a></strong></p> |
7,304,182 | Detecting SSL With PHP | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1175096/how-to-find-out-if-you-are-using-https-without-serverhttps">How To Find Out If You are Using HTTPS Without $_SERVER['HTTPS']</a> </p>
</blockquote>
<p>I went looking around the web for ways to detect if a server is using an HTTPS connection, but no one site seemed to have all the answers (and some different ones). What exactly are all the ways to detect if a server is using an HTTPS connection with PHP? I need to know several ways to detect SSL as some of my scripts are redistributed and various servers handle things differently.</p> | 7,304,205 | 2 | 3 | null | 2011-09-05 05:32:39.823 UTC | 4 | 2013-06-19 14:14:18.347 UTC | 2017-05-23 12:26:11.43 UTC | null | -1 | null | 793,770 | null | 1 | 31 | php|ssl|https | 66,213 | <blockquote>
<p><code>$_SERVER['HTTPS']</code></p>
<p>Set to a non-empty value if the script was queried through the HTTPS protocol.<br>
Note: Note that when using ISAPI with IIS, the value will be <em>off</em> if the request was not made through the HTTPS protocol.</p>
<p><a href="http://www.php.net/manual/en/reserved.variables.server.php" rel="noreferrer">http://www.php.net/manual/en/reserved.variables.server.php</a></p>
</blockquote>
<p>Ergo, this'll do:</p>
<pre><code>if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
// SSL connection
}
</code></pre> |
18,888,131 | Print PDF File in IFrame using javascript getting one page only | <p>here is my code to print a pdf file. here while printing time iam getting one page only i need a solution for that</p>
<pre><code> function printPdf(){
var ifr = document.getElementById("frame1");
//PDF is completely loaded. (.load() wasn't working properly with PDFs)
ifr.onreadystatechange = function () {
if (ifr.readyState == 'complete') {
ifr.contentWindow.focus();
ifr.contentWindow.print();
}
}
}
</code></pre> | 18,890,500 | 2 | 1 | null | 2013-09-19 07:00:05.007 UTC | 8 | 2016-03-27 17:38:30.43 UTC | 2014-02-10 12:24:38.437 UTC | null | 318,054 | null | 2,787,438 | null | 1 | 8 | javascript|internet-explorer|pdf | 26,942 | <p>I suspect that's because the whole window gets printed (which has the current view of the <code>iframe</code> with the 1st page of the PDF rendered). Use <code><object></code> instead:</p>
<pre><code><!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
function PrintPdf() {
idPrint.disabled = 0;
idPdf.Print();
}
function idPdf_onreadystatechange() {
if (idPdf.readyState === 4)
setTimeout(PrintPdf, 1000);
}
</script>
</head>
<body>
<button id="idPrint" disabled=1 onclick="PrintPdf()">Print</button>
<br>
<object id="idPdf" onreadystatechange="idPdf_onreadystatechange()"
width="300" height="400" type="application/pdf"
data="test.pdf?#view=Fit&scrollbar=0&toolbar=0&navpanes=0">
<span>PDF plugin is not available.</span>
</object>
</body>
</code></pre>
<p>This code is verified with IE. Other browsers will still render the PDF, but may not print it. </p>
<p><strong>[UPDATE]</strong> If you need dynamic loading and printing, the changes to the above code are minimal:</p>
<pre><code><!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
function PrintPdf() {
idPdf.Print();
}
function idPdf_onreadystatechange() {
if (idPdf.readyState === 4)
setTimeout(PrintPdf, 1000);
}
function LoadAndPrint(url)
{
idContainer.innerHTML =
'<object id="idPdf" onreadystatechange="idPdf_onreadystatechange()"'+
'width="300" height="400" type="application/pdf"' +
'data="' + url + '?#view=Fit&scrollbar=0&toolbar=0&navpanes=0">' +
'<span>PDF plugin is not available.</span>'+
'</object>';
}
</script>
</head>
<body>
<button id="idPrint" onclick="LoadAndPrint('http://localhost/example.pdf')">Load and Print</button>
<br>
<div id="idContainer"></div>
</body>
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.