_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d501 | train | When you divide $valueAsCents = 54780 / 100 then it becomes a float which is not always accurate in digital form because of the way they are stored. In my tests I got
547.7999999999999545252649113535881042480468750000
When multiplied by 100 this is would be
54779.9999999999927240423858165740966796870000
When PHP casts to int, it always rounds down.
When converting from float to integer, the number will be rounded towards zero.
This is why the int value is 54779
Additionally, the PHP manual for float type also includes a hint that floating point numbers may not do what you expect.
Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118.... | unknown | |
d502 | train | You need to bind to a list of int instead of a list of Label on your view model. Then, you'll need to use that list of selected ids to fill your list of labels on the Team entity you're persisting:
public class CreateTeamViewModel
{
[Required]
public string TeamName { get; set; }
public string ProjectName { get; set; }
public string ProjectDescription { get; set; }
[Required]
public string RepositoryLink { get; set; }
public List<int> SelectedLabels { get; set; } = new List<int>();
}
Then, you'll need to modify your form to bind your checkboxes to this list:
@foreach (var label in labels)
{
<input asp-for="SelectedLabels" id="Label@(label.Id)" value="@label.Id" type="checkbox" />
<label id="Label@(label.Id)">
<span class="badge badge-@label.ColorPalette">@label.Name</span>
</label>
}
Notice that I removed the hidden inputs. You should never post anything that the user should not be able to modify, as even hidden inputs can be tampered with.
After posting, server-side you'll end up with a list of label ids that were selected by the user. Simply query the associated labels out of your database and then assign that to the team you're creating:
team.Labels = await _context.Set<Label>().Where(x => model.SelectedLabels.Contains(x.Id)).ToListAsync(); | unknown | |
d503 | train | You need to use as below
MenuItem menuTest2 = new MenuItem(); // Main Manu 2
menuTest2.Text = " SMS ";
menuTest2.NavigateUrl = "javascript:void(0)";
//menuTest2.Value = "something";
Menu1.Items.Add(menuTest2);
The problem as I think was that the page get redirected to the same page when clicked. And as I guess the menu is created on page load event.
Using menuTest2.NavigateUrl = "javascript:void(0)"; will stop the menu to postback when it is clicked. | unknown | |
d504 | train | If it is a logical column, no need to == TRUE. Also, when subsetting a single column, directly subset instead of subsetting it from the data.frame which is inefficient
x[(x$a %in% y$b | x$a %in% y$d[y$c]), ]
Or make it a bit more compact
x[(x$a %in% c(y$b, y$d[y$c])),]
A: It might be worth to give subset a try.
subset(x, a %in% b | a %in% y[y$c, 'd']) | unknown | |
d505 | train | How about using YCbCr?
Y is intensity, Cb is the blue component relative to the green component and Cr is the red component relative to the green component.
So I think YCbCr can differentiate between multiple pixels with same grayscale value. | unknown | |
d506 | train | The Android build process already specifies all the necessary -injars/-libraryjars/-outjars options for you. You should never specify them in your configuration file; you'd only get lots of warnings about duplicate classes.
You can find an explanation of their purpose in the ProGuard manual > Introduction. | unknown | |
d507 | train | Yes, that's a function pointer. This is a current limitation of C interoperability:
Note that C function pointers are not imported in Swift.
You might consider filing a bug if you'd like this to work. (Note that block-based APIs are fine and work with Swift closures.) | unknown | |
d508 | train | You shouldn't use the FileSystemObject and String/RegExp operations to edit an XML file. Using the canonical tool - msxml2.domdocument - is less error prone and scales much better.
See here for an example (edit text); or here for another one (edit attribute).
If you publish (the relevant parts of) your .XML file, I'm willing to add same demo code specific for your use case here. | unknown | |
d509 | train | I think the error says it quite well. You have a syntax error.
Perhaps this is what you wanted?
exec('sed -i \'1i MAILTO=""\' /var/spool/cron/'.$clientName); | unknown | |
d510 | train | As you are already iterating from end to start you can just append the characters to the fresh and empty string builder. setChar() is only intended to replace existing characters.
public class StringBuilders {
public static void main(String[] args) {
String str = "Shubham";
StringBuilder str2 = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
str2.append(str.charAt(i));
}
System.out.println(str2.toString());
}
}
gives
$ java StringBuilders.java
mahbuhS
A: You haven't declared a value to the str2 string.
The for loop is trying to find a character at index j=0 in str2 to set value i of str2, which it cannot find.
Hence the error.
For this to work, you need declare a value of str2 to a length >= str1. i.e., if str1 = "0123456", str2 should be at least 0123456 or more.
Instead of using StringBuilder to set the char, you can use String to just append to it.
String str1 = new String("Shubham");
String str2 = new String();
int iter = str1.length() -1;
for(int i=iter; i>=0; i--) {
str2 += str1.charAt(i);
}
System.out.println(str2) | unknown | |
d511 | train | Refer this great write up: http://blog.webbb.be/command-not-found-node-npm/
This can happen when npm is installing to a location that is not the standard and is not in your path.
To check where npm is installing, run: npm root -g
It SHOULD say /usr/local/lib/node_modules, If it doesn't then follow this:
Set it to the correct PATH:
*
*run: npm config set prefix /usr/local
*Then reinstall your npm package(s) with -g:
npm install -g cordova etc
If this doesn't work then try adding the global path of cordova(where it got installed) to your $PATH variable. | unknown | |
d512 | train | This is not REST.
REST is about using HTTP, not XML!
A typical HTTP REQUEST to create an item would be like this
PUT http://mysite/items/ HTTP/1.1
Host: xxxxx
<myitem>
<text> asdasdas </text>
</myitem>
And you can use whatever you want in the body of the request. XML, JSON, PHP SERIALIZE or your own data format.
A: If you truly want to be RESTful about this, you'd definitely want to use a POST request to create records. That's if you care to be strict about the standard, but it would also help you because I'm reading that your array's length could vary tremendously - sometimes 1 ID, perhaps 30 other times, etc. URI query strings do (or used to?) have a maximum character limit that you could conceivably bump up against.
If you roll with a POST request, you could easily passing in a comma-delimited list (think about how a field name with multiple checkboxes is passed) or, my favorite mechanism, a JSON-encoded array (represented as a string that can easily be JSON-decoded on the other side.
A: This actually applies to any web page, not just CakePHP.
Any web page which wants to send a large number of fields has to include them all in their POST request.
If you had a web page form with 50 inputs and a submit at the bottom, the page would by default serialise the data and send it in the form request.
If you don't want all the data sent in seperate bars, then using a seperator would work fine too and would mean they all went in 1 parameter.
Somthing like:
http://mysite/items/create?mydata=23-45-65-32-43-54-23-23-656-77
A: another option:
$safedata = base64_encode(serialize($arrayofdata));
and pass it to URL as safe string.
then uncompress it:
$data = unserialize(base64_decode($safedata); | unknown | |
d513 | train | If you know that the list is the value associated to the 'result' key, simply call dct['result'].
>>> dct = {'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct
{'result': ['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']}
>>> dct['result']
['activeaddresses', 'exchangevolume(usd)', 'marketcap(usd)', 'mediantxvalue(usd)', 'price(usd)', 'txcount', 'txvolume(usd)']
Converting the values to a list is unneeded, inefficient and might return the wrong value if your dict has more than 1 (key, value) pair.
A: Your dictionary have only one value and that itself is a list of elements. So just call the result key and you will get the list value.
If you want the list from your code add the index [0] like,
dList = list(dct.values())[0]
Hope this helps! Cheers! | unknown | |
d514 | train | Use FileReader to access the lines of the file.
while (line) {
clientSearchPage();
}
Use element.sendKeys(line) to input the data to the text-boxes
Use explicit waits:
WebDriverWait and ExpectedConditions.elementToBeClickable(element) / (ExpectedCondition<Boolean>) driver -> element.isDisplayed()
instead of Thread.sleep()
Make an attempt yourself before asking on SO, nobody is gonna do your job for you | unknown | |
d515 | train | You can use useState hook from react. check the docs here: https://reactjs.org/docs/hooks-state.html | unknown | |
d516 | train | print(len(set(sortedPrimes))) # Count of unique keys: 336
Dictionaries hash values to keys. Those key aren't duplicated. There's 336 unique items in sortedPrimes so there's 336 keys in new
A: You have a situation where one key is mapping to multiple values. In that case, one reasonable data structure is a dict of lists:
import collections
d = collections.defaultdict(list)
for v1, v2 in zip(sortedPrimes, a):
d[v1].append(v2)
for k in sorted(d):
print k, d[k]
# Output
0013 [3001]
0014 [4001]
0017 [7001]
0019 [1009, 9001]
0023 [2003]
0034 [4003]
0035 [5003]
0047 [4007]
0059 [5009]
0067 [6007]
0079 [9007]
0089 [8009]
0112 [1021, 1201, 2011]
0113 [1013, 1031, 1103, 1301, 3011]
0115 [1051, 5011, 5101]
etc. for all 336 keys ... | unknown | |
d517 | train | No, it's currently not possible to do dynamic configuration updates.
There's a Jira ticket for that exact issue here, and the accompanying KIP (Kafka Improvement Proposal). | unknown | |
d518 | train | dcast from the devel version of data.table i.e., v1.9.5 can cast multiple columns simultaneously. It can be installed from here.
library(data.table) ## v1.9.5+
dcast(setDT(mydatain), SitePoint~Year_Rotation,
value.var=c('MR_Fire', 'fire_seas', 'OptTSF'))
A: You can use reshape to change the structure of your dataframe from long to wide using the following code:
reshape(mydatain,timevar="Year_Rotation",idvar="SitePoint",direction="wide") | unknown | |
d519 | train | find . -size +20000
The above one should work.
A: I guess you want to find files bigger than 1 Mb, then do
$ find . -size +1M
A: On Ubuntu, this works:
find . -type f -size +10k
The above would find all files in the current directory and below, being at least 10k.
A: This command tell you "the size" too :-)
find . -size +1000k -exec du -h {} \; | unknown | |
d520 | train | Try this:
echo date("H:i A, F jS, Y", strtotime("2020-08-05T11:45:10.3159677Z")); | unknown | |
d521 | train | You printed two extra space characters between each strings and numbers.
Try Replacing
System.out.printf("%1$-16s %2$03d\n",sb,x);
with
System.out.printf("%1$-15s%2$03d \n",sb,x);
Also you should remove the line sc.nextLine(); to avoid extra reading and causing an exceition. | unknown | |
d522 | train | Note that the property names are in camel-case and not kebab-case while setting the style using elt.style. (i.e. elt.style.fontSize, not elt.style.font-size)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
So there should be backgroundColor instead of background-color in your bookmarklet JavaScript code. | unknown | |
d523 | train | The Entity Framework uses only the information in the attribute to convert the method call to SQL. The implementation is not used in this case.
A: The EdmFunction attribute calls the specified method in SQL. The implementation you have in C# will be ignored. So in your case STR method is called at SQL end.
You can have your method as:
[EdmFunction("SqlServer", "STR")]
public static string ConvertToString(double? number)
{
throw new NotSupportedException("Direct calls not supported");
}
and still it would work.
See: EDM and Store functions exposed in LINQ
How it works
When a method with the EdmFunction attribute is detected within a LINQ
query expression, its treatment is identical to that of a function
within an Entity-SQL query. Overload resolution is performed with
respect to the EDM types (not CLR types) of the function arguments.
Ambiguous overloads, missing functions or lack of overloads result in
an exception. In addition, the return type of the method must be
validated. If the CLR return type does not have an implicit cast to
the appropriate EDM type, the translation will fail.
As a side note, you can also use SqlFunctions.StringConvert like:
var student = (from s in Students
where SqlFunctions.StringConvert((double) s.LanguageId)).Trim() == "2"
select s).FirstOrDefault(); | unknown | |
d524 | train | There are several things here:
*
*You need to define area as being a square length with type area = radius * radius. Otherwise the compiler has no way to match your input and output units.
*Pi, when used like this, is dimensionless, which is represented in F# as <1> or just no unit suffix.
[<Measure>] type radius
[<Measure>] type area = radius * radius
let convertRadiusToArea (r:float<radius>) : float<area> =
let pi = System.Math.PI
r * r * pi
A: A better example of using F#'s unit of measure would be this:
[<Measure>] type cm
let convertRadiusToArea(r:float<cm>) : float<cm^2> =
r * r * System.Math.PI
The idea being that you get benefits of the units of measurement in your calculations and derivations. You're not getting that by creating a unit of measure called 'radius'. Is it in meters? Feet? Centimetres? And that is why you would introduce them into an F# function, to be non-ambiguous about the unit of measurement for the inputs and outputs.
Units of measure in F# should IMO be modelled the way we use units of measurement in any other calculations or real world example like speed, temperature, force etc. | unknown | |
d525 | train | Is there a way of making this work from Azure Pipelines?
From your description, you need to access the azure container registry and azure container app in different Resource Groups.
To meet your requirement, you need to create a Service Connection at Subscription Level.
Navigate to Project Settings -> Service Connections -> Select Azure Resource Manager Service Connection. Then you can only select Azure Subscription.
In this case, the Service Connection will have access to whole Azure Subscription.
For example: | unknown | |
d526 | train | Make sure that your line separator is equal to \n on your system.
This is not the case on Windows.
To fix the test, modify it to take system-specific separator into account
assertEquals("Hello World" + System.lineSeparator(), outContent.toString()); | unknown | |
d527 | train | This is not possible in Dart as it stands today.
Parameterized types (things like List<int>) can take literal types (e.g., List<Chicken>) or type parameters (e.g., List<T> where T is declared as a type parameter in a generic, as it in Cage) as arguments. They cannot take arbitrary expressions, even if those are of type Type.
A variable such as t might hold a Type (as in your example) but in general it is really hard to be sure of that. It could just as easily hold a non-type value such as the number 3, because Dart's type system does not guarantee that something with static type Type really is a Type.
If we let these through, the system would be thoroughly corrupted. We could add runtime checks for that, but that would hit performance.
A: This is not (yet) supported.
There was some explanation somewhere, I'll have to look it up.... | unknown | |
d528 | train | As you mentioned you will have an error raised if you have a major dtypes error (for example using int64 when the column is float64). However, you won't have an error if for example you use int8 instead of int16 and the range of your values does not match the range of int8 (i.e -128 to 127)
Here is a quick example:
from io import StringIO
import pandas as pd
s = """col1|col2
150|1.5
10|2.5
3|2.5
4|1.2
8|7.5
"""
pd.read_csv(StringIO(s),sep='|', dtype={"col1": "int8"})
And the output is:
col1 col2
0 -106 1.5
1 10 2.5
2 3 2.5
3 4 1.2
4 8 7.5
So as you can see, the first value in the column col1 has been converted from 150 to -106 without any error / warning from pandas.
The same is applied to float types, I just used int for convenience.
EDIT I add an example with floats since this is what you were asking:
from io import StringIO
import pandas as pd
s = """col1|col2
150|32890
10|2.5
3|2.5
4|1.2
8|7.5
"""
If you read it without specifying the dtype:
pd.read_csv(StringIO(s),sep='|'))
col1 col2
0 150 32890.0
1 10 2.5
2 3 2.5
3 4 1.2
4 8 7.5
If you read it with specifying the "wrong" dtype for the columns:
pd.read_csv(StringIO(s),sep='|', dtype={"col1": "int8", "col2": "float16"})
col1 col2
0 -106 32896.000000
1 10 2.500000
2 3 2.500000
3 4 1.200195
4 8 7.500000
If you have a large CSV file and you want to optimize the dtypes, you can load the CSV file column by column (this should not take too much memory) with no dtype then infer the optimal dtype thanks to the values inside the column and load the full CSV with the optimized dtypes. | unknown | |
d529 | train | $foo is a local (uninitialized) variable inside a function. It is different from the global variable $foo ($GLOBALS['foo']).
You have two ways:
$foo;
$bar;
$array = array();
function foobar(){
global $foo, $array, $bar;
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
or by using the $GLOBAL array …
This is not really good practice though and will become a maintenance nightmare with all those side effects
A: Functions in php can be given arguments that have default values. The code you posted as written will give you notices for undefined variables. Instead, you could write:
function foobar($foo = null) {
if($foo) { // a value was passed in for $foo
}
else { // foo is null, no value provided
}
}
Using this function, neither of the below lines will produce a notice
foobar();
foobar('test'); | unknown | |
d530 | train | It is not a issue with setTimeout method. This is the issue with window.close() . It is not a good practice to close the window within itself.Still if you its very necessary you can try the below code:
window.open('','_parent',''); //fool the browser that it was opened with a script
window.close();
You can put this in a function and call it use in setTimeout .Helpful link | unknown | |
d531 | train | Your session variables are always set to null;
Use:
s_name=(String)request.getParameter("s_name");
s_password=(String)request.getParameter("s_password");
s_location=(String)request.getParameter("s_location");
To get the values before setting them in the session
A: Maybe that is the problem?
String s_name=null, s_password=null, s_location=null;
And then you set session to this null values.
A: You have to first request that parameter before setSession statement;
so in ShopRegister3.jsp, after s_name initialization to `null´.
Request that parameter like:
s_name = request.getParameter("s_name");
Now you can setSession for this variable; it will not return null for s_name variable now. | unknown | |
d532 | train | select
replace(
replace(
replace(
replace(<input>,
'KV', 'V'),
'KM', 'M'),
'PE', 'R'),
'PP', 'N')
from
....
A: This cannot be solved by SQL, say with several REPLACE functions. The reason for this is that for instance PPP can mean PP-P or P-PP and thus be substituted either by PN or NP. Same for xxxKVxxx; is this KV or is it a trailing K and a leading V?
You will have to write a database function (PL/SQL) that loops through the string and replaces part by part. You will certainly know how to interpret PPP :-)
(BTW: Seems like a bad idea to store the classifications as a concatenated string of letters rather than in a separate table. You are using a relational database system without making use of the relational part. Hence the problem now.) | unknown | |
d533 | train | Instead of a complex for loop or forEach you can just use a simple map.
Just handle it similiar to a for loop, the map will go for all your elements in your array like below.
map(p => (!this.personTypeFilter.map((x:any) => x)) ? p:p.filter(((i:any) => this.getPersonTypesBezeichnung(i.personentyp).includes(this.personTypeFilter.map((x:any) => x).join(', '))))), | unknown | |
d534 | train | if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
//do it
}
IMHO this code could be simplified:
if(boolean1 != boolean2)
{
//do it
}
A: With code clarity in mind, my opinion is that using XOR in boolean checks is not typical usage for the XOR bitwise operator. From my experience, bitwise XOR in Java is typically used to implement a mask flag toggle behavior:
flags = flags ^ MASK;
This article by Vipan Singla explains the usage case more in detail.
If you need to use bitwise XOR as in your example, comment why you use it, since it's likely to require even a bitwise literate audience to stop in their tracks to understand why you are using it.
A: You can simply use != instead.
A: I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.
A: I find that I have similar conversations a lot. On the one hand, you have a compact, efficient method of achieving your goal. On the other hand, you have something that the rest of your team might not understand, making it hard to maintain in the future.
My general rule is to ask if the technique being used is something that it is reasonable to expect programmers in general to know. In this case, I think that it is reasonable to expect programmers to know how to use boolean operators, so using xor in an if statement is okay.
As an example of something that wouldn't be okay, take the trick of using xor to swap two variables without using a temporary variable. That is a trick that I wouldn't expect everybody to be familiar with, so it wouldn't pass code review.
A: I think it'd be okay if you commented it, e.g. // ^ == XOR.
A: You could always just wrap it in a function to give it a verbose name:
public static boolean XOR(boolean A, boolean B) {
return A ^ B;
}
But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.
You can also use XOR to swap the values in two variables without using a third temporary variable.
// Swap the values in A and B
A ^= B;
B ^= A;
A ^= B;
Here's a Stackoverflow question related to XOR swapping.
A: I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.
If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".
For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:
if (isDifferent(boolean1, boolean2))
{
//do it
}
Your "isDifferent(boolean1, boolean2)" function would look like:
private boolean isDifferent(boolean1, boolean2)
{
return boolean1 ^ boolean2;
}
Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!
A: != is OK to compare two variables. It doesn't work, though, with multiple comparisons.
A: str.contains("!=") ^ str.startsWith("not(")
looks better for me than
str.contains("!=") != str.startsWith("not(")
A: If the usage pattern justifies it, why not? While your team doesn't recognize the operator right away, with time they could. Humans learn new words all the time. Why not in programming?
The only caution I might state is that "^" doesn't have the short circuit semantics of your second boolean check. If you really need the short circuit semantics, then a static util method works too.
public static boolean xor(boolean a, boolean b) {
return (a && !b) || (b && !a);
}
A: As a bitwise operator, xor is much faster than any other means to replace it. So for performance critical and scalable calculations, xor is imperative.
My subjective personal opinion: It is absolutely forbidden, for any purpose, to use equality (== or !=) for booleans. Using it shows lack of basic programming ethics and fundamentals. Anyone who gives you confused looks over ^ should be sent back to the basics of boolean algebra (I was tempted to write "to the rivers of belief" here :) ). | unknown | |
d535 | train | You configured a firewall that match every /admin* urls, but that don't mean that every URL requires authentication. You can be an anonymous user, and that would be fine. If you want tell silex that "the user need the ROLE_ADMIN to be allowed here", you need to add
$app['security.access_rules'] = array(
array('^/admin', 'ROLE_ADMIN'),
); | unknown | |
d536 | train | You have missed one property to stretch iframe (height):
.liveStream {
&__play {
position: relative;
z-index: 10;
}
&__player {
display: flex;
height: 100%;
width: 100%;
flex-grow: 1;
align-items: center;
justify-content: center;
position: relative;
overflow: hidden;
// make sure wrapper has necessary sizes
// min-height: 100vh;
// just for example purposes:
height: 300px;
width: 300px;
}
&__preview {
position: absolute;
top: 0;
left: 0;
width: 100%;
pointer-events: none;
// add height prop to stretch iframe to parent height
height: 100%;
}
}
Also make sure wrapper has necessary sizes.
You can check codes in Codepen.io example. | unknown | |
d537 | train | Why not bundle a prebuilt Realm file as part of your application instead? To do this you'll need to:
*
*Create the prebuilt Realm file, either using Realm Browser or a simple Mac app of your own creation.
*Add the prebuilt Realm file to your app target in your Xcode project, ensuring that it appears in the Copy Bundle Resources build phase.
*Add code similar to that found in the above link to your app to have it open the prebuilt Realm file as read-only. Alternatively, you could copy the file out of your app bundle into the user's documents or cache directory and open it read-write. | unknown | |
d538 | train | Yes its quite obvious that you are using old style of joining, still if you need to avoid NULL value to show on data then you can use IFNULL() function for avoiding NULL.
Example :-
select ifnull(members.username,'this is null part') as username from table_name;
This query will print the null part ,if the username is null either it will print the username only.
You can apply to your all column when you are fetching the column data in your query.
Hope it will help you. | unknown | |
d539 | train | Hibernate ORM 5.3 implements the JPA 2.2 standard.
Supported types from the Java 8 Date and Time API
The JPA 2.2 specification says that the following Java 8 types are supported:
*
*java.time.LocalDate
*java.time.LocalTime
*java.time.LocalDateTime
*java.time.OffsetTime
*java.time.OffsetDateTime
Hibernate ORM supports all these types, and even more:
*
*java.time.ZonedDateTime
*java.time.Duration
Entity mapping
Assuming you have the following entity:
@Entity(name = "DateTimeEntity")
public static class DateTimeEntity {
@Id
private Integer id;
@Column(name = "duration_value")
private Duration duration = Duration.of( 20, ChronoUnit.DAYS );
@Column(name = "instant_value")
private Instant instant = Instant.now();
@Column(name = "local_date")
private LocalDate localDate = LocalDate.now();
@Column(name = "local_date_time")
private LocalDateTime localDateTime = LocalDateTime.now();
@Column(name = "local_time")
private LocalTime localTime = LocalTime.now();
@Column(name = "offset_date_time")
private OffsetDateTime offsetDateTime = OffsetDateTime.now();
@Column(name = "offset_time")
private OffsetTime offsetTime = OffsetTime.now();
@Column(name = "zoned_date_time")
private ZonedDateTime zonedDateTime = ZonedDateTime.now();
//Getters and setters omitted for brevity
}
The DateTimeEntity will have an associated database table that looks as follows:
CREATE TABLE DateTimeEntity (
id INTEGER NOT NULL,
duration_value BIGINT,
instant_value TIMESTAMP,
local_date DATE,
local_date_time TIMESTAMP,
local_time TIME,
offset_date_time TIMESTAMP,
offset_time TIME,
zoned_date_time TIMESTAMP,
PRIMARY KEY (id)
)
Source: Mapping Java 8 Date/Time entity attributes with Hibernate
A: Since version 2.2, JPA offers support for mapping Java 8 Date/Time API, like LocalDateTime, LocalTime, LocalDateTimeTime, OffsetDateTime or OffsetTime.
Also, even with JPA 2.1, Hibernate 5.2 supports all Java 8 Date/Time API by default.
In Hibernate 5.1 and 5.0, you have to add the hibernate-java8 Maven dependency.
So, let's assume we have the following Notification entity:
@Entity(name = "Notification")
@Table(name = "notification")
public class Notification {
@Id
private Long id;
@Column(name = "created_on")
private OffsetDateTime createdOn;
@Column(name = "notify_on")
private OffsetTime clockAlarm;
//Getters and setters omitted for brevity
}
Notice that the createdOn attribute is a OffsetDateTime Java object and the clockAlarm is of the OffsetTime type.
When persisting the Notification:
ZoneOffset zoneOffset = ZoneOffset.systemDefault().getRules()
.getOffset(LocalDateTime.now());
Notification notification = new Notification()
.setId(1L)
.setCreatedOn(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset)
).setClockAlarm(
OffsetTime.of(7, 30, 0, 0, zoneOffset)
);
entityManager.persist(notification);
Hibernate generates the proper SQL INSERT statement:
INSERT INTO notification (
notify_on,
created_on,
id
)
VALUES (
'07:30:00',
'2020-05-01 12:30:00.0',
1
)
When fetching the Notification entity, we can see that the OffsetDateTime and OffsetTime
are properly fetched from the database:
Notification notification = entityManager.find(
Notification.class, 1L
);
assertEquals(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset),
notification.getCreatedOn()
);
assertEquals(
OffsetTime.of(7, 30, 0, 0, zoneOffset),
notification.getClockAlarm()
); | unknown | |
d540 | train | Do you get an error back? I suggest you change your -i to -v, in order to get a verbose response to give you more information.
Also your curl command uses PUT and not POST as you say; please clarify if the question is about one or the other?
Finally, try to remove the quote marks from you numeric values, you don't need them. | unknown | |
d541 | train | You are getting key-value pair data.
access like this
let data = [
{"_id":{"$oid":"5def1f22b15556e4e9bdb345"},
"Time":{"$numberDouble":"1616180000000"},
"Image_Path":"1575946831220.jpg","permission":"Read:Write"},
{"_id":{"$oid":"5def1f22b15556e4e9bdb346"},
"Time":{"$numberDouble":"727672000000000000"},
"Image_Path":"8398393839313893.jpg","permission":"Read:Write"},
{"_id":{"$oid":"5def1f22b15556e4e9bdb347"},
"Time":{"$numberDouble":"84983500000000"},
"Image_Path":"82492849284984.jpg","permission":"Read:Write"}
]
let json = Object.values(data);
in reactjs
return (
<div>
{json.map(a =>
<div key={a.id}>
<h4>image path --{a.Image_Path}</h4>
<h6>Permission-- {a.permission}</h6>
</div>
)}
</div>
); | unknown | |
d542 | train | <br> is outdated. Use the self-closing <br /> instead. The names should be wrapped in something (p, span, h3, something). There are 2 styles (one inline (inside the document) and one attached to #header) that are adding around 500px of space there. That's why there is a large gap.
Consider making it easier on yourself.. use 1 class to define each TYPE of object.
#people {
styles for container div
}
.box {
styles for the individual boxes
}
.photo {
styles for <img>
}
.title {
styles for names of people
}
Then just apply the classes to the appropriate item like so
<div id="people">
<div class="box">
<img src="path/image.jpg" class="photo" />
<h3 class="title">Position, name</h3>
</div>
<div class="box">
<img src="path/image.jpg" class="photo" />
<h3 class="title">Position, name</h3>
</div>
etc...
</div>
A: Make the following changes:
.pres {
/* display: inline (remove) */
display: inline-block;
width: 270px;
text-align: center;
}
.captain {
/* display: inline (remove) */
display: inline-block;
width: 270px;
text-align: center;
} | unknown | |
d543 | train | One way to go around this:
$('#modal-window').on('hide.bs.modal', function () {
$('#modal-window').css("display", "none");
})
$('#modal-window').on('show.bs.modal', function () {
$('#modal-window').css("display", "block");
})
$("#modal-window").html("<%= escape_javascript(render partial: 'shared/profile_modal', locals: { profile: @profile }) %>");
$("#profile_modal").modal();
And disable backdrop:
<%= link_to profile.full_name, { :action => :profile_modal,
:profile_id_param => profile.id },
{ remote: true, 'data-toggle' => 'modal',
'data-target' => '#modal-window',
'data-backdrop' => "false"} %>
Also noticed that #modal-window gets z-index 1050 even after modal being closed, but this:
$('#modal-window').on('hide.bs.modal', function () {
$('#modal-window').css("display", "0");
Didnt fixed it.
I keep this issue open for:
a) a better way to fix this
b) How to pass locals to this modal? | unknown | |
d544 | train | Try this
I have done for two column problem_ID and date_of_entry you can add the other two column in pivot.
fiidle demo here
http://sqlfiddle.com/#!3/ef8e8e/1
CREATE TABLE #Products
(
ID INT,
NAME VARCHAR(30),
problem_ID INT,
date_of_entry DATE,
elem_id VARCHAR(30),
staff_id INT
);
INSERT INTO #Products
VALUES (1,'abc',456,'2014/12/12',789,32),
(1,'abc',768,'2014/12/01',896,67),
(1,'abc',897,'2014/02/14',875,98),
(2,'bcd',723,'2014/02/17',287,09),
(2,'bcd',923,'2014/09/13',879,01),
(2,'bcd',878,'2014/08/23','hgd',34)
DECLARE @problm VARCHAR(MAX)='',
@daofenty_id VARCHAR(MAX)='',
@aggproblm VARCHAR(MAX)='',
@aggdaofenty_id VARCHAR(MAX)='',
@sql NVARCHAR(max)
SET @problm = (SELECT DISTINCT Quotename('problm'+CONVERT(VARCHAR(50), Row_number() OVER(partition BY ID ORDER BY problem_ID)))
+ ','
FROM #Products
FOR XML PATH(''))
SET @aggproblm = (SELECT DISTINCT ' max('
+ Quotename('problm'+CONVERT(VARCHAR(50), Row_number() OVER(partition BY ID ORDER BY problem_ID)))
+ ') problm'
+ CONVERT(VARCHAR(50), Row_number() OVER(partition BY ID ORDER BY problem_ID))
+ ','
FROM #Products
FOR XML PATH(''))
SET @daofenty_id =(SELECT DISTINCT
+ Quotename('daofenty_id'+CONVERT(VARCHAR(50), Row_number() OVER(partition BY ID ORDER BY date_of_entry)))
+ ','
FROM #Products
FOR XML PATH(''))
SET @aggdaofenty_id = (SELECT DISTINCT + ' max('
+ Quotename('daofenty_id'+CONVERT(VARCHAR(50), Row_number() OVER(partition BY ID ORDER BY date_of_entry)))
+ ') daofenty_id'
+ CONVERT(VARCHAR(50), Row_number() OVER(partition BY ID ORDER BY date_of_entry))
+ ','
FROM #Products
FOR XML PATH(''))
SET @problm = LEFT(@problm, Len(@problm) - 1)
SET @daofenty_id = LEFT(@daofenty_id, Len(@daofenty_id) - 1)
SET @aggproblm = LEFT(@aggproblm, Len(@aggproblm) - 1)
SET @aggdaofenty_id = LEFT(@aggdaofenty_id, Len(@aggdaofenty_id) - 1)
SET @sql = 'SELECT Id,name,' + @aggproblm + ','
+ @aggdaofenty_id + '
FROM (select * from (SELECT ''problm''+convert(varchar(50),row_number() over(partition by ID order by problem_ID)) problm_id, ''daofenty_id''+convert(varchar(50),row_number() over(partition by ID order by date_of_entry)) daofenty_id ,
''elemid''+convert(varchar(50),row_number() over(partition by ID order by elem_id)) elemid , ''staffid''+convert(varchar(50),row_number() over(partition by ID order by staff_id)) staffid,*
FROM #Products) A
) AS T
PIVOT
(max(problem_id) FOR problm_id IN
(' + @problm + ')) AS P1
PIVOT
(max(date_of_entry) FOR daofenty_id IN
('
+ @daofenty_id + ')) AS P1
group by id,name'
--PRINT @sql
EXEC Sp_executesql
@sql
to limit the no. of columns
SET @problm = (SELECT DISTINCT TOP N Quotename('problm'+CONVERT(VARCHAR(50), Row_number() OVER(partition BY ID ORDER BY problem_ID)))
+ ','
FROM #Products
FOR XML PATH(''))
Similarly do the same for other columns.. | unknown | |
d545 | train | Check Nick's post about tagging blog posts. It covers all main tagging issues.
A: There is a modified django-tagging, probably it might work. | unknown | |
d546 | train | Like @smarx said, you would return the Promise at getLocationId() and execute then branch:
class Geolocator {
// ...
/* returns a promise with 1 argument */
getLocationId(lat, lon) {
return this._geocoder.reverse({ lat, lon })
}
}
// calling from outside
geolocator
.getLocationId(lat, lon)
.then((res) => {
// whatever
})
.catch((err) => {
// error
}) | unknown | |
d547 | train | You'd need to add a listener to each row so that when the price or quantity are updated, you can get the new quantity and price and update the total column.
In jQuery, something like:
$('.row').on('change', function() {
var quantity = $('.quantity', this).val(), // get the new quatity
price = $('.price', this).val(), // get the new price
total = price*quantity;
$('.total', this).val(total); //set the row total
var totals = $.map($('.row .total'), function(tot) {
return tot.val(); // get each row total into an array
}).reduce(function(p,c){return p+c},0); // sum them
$('#total').val(totals); // set the complete total
});
This assumes that each order form row container has the class row, each quantity has the class quantity, each row total has the class total and the order form total has the id total. | unknown | |
d548 | train | Would it help to put the alert in a CDATA tag? So
<script type="text/javascript">
<![CDATA[alert('Only in Firefox');]]>
</script>
I've started doing that for all javascript that I include in xslt templates | unknown | |
d549 | train | To elaborate: destroying a QList will destroy the elements of the list. If the elements are pointers, the pointers themselves are destroyed, not the pointees. You can use qDeleteAll to delete the pointees.
(That will use operator delete, which is the right choice if and only if you're using operator new; malloc will always require free and operator new[] will always require operator delete[]).
That having been said, returning a QList by value won't destroy it, as its refcount won't drop to 0. Getting a crash there means it's very likely that you have some memory corruption. Use valgrind or similar tools to debug that. | unknown | |
d550 | train | I have had this error yesterday. The Error caused by SSL which has a problem on the server. So, I changed the SSL method to TLS to avoid the problem SSL. Configure your config with these rules.
$config['protocol'] = "smtp";
$config['smtp_host'] = "smtp.gmail.com";
$config['smtp_port'] = "587";
$config['smtp_user'] = "*your@email.com*";
$config['smtp_pass'] = "*yourpassword*";
$config['smtp_timeout'] = "4";
$config['charset'] = "utf-8";
$config['newline'] = "\r\n";
$config['smtp_crypto'] = "tls"; // This is an important part of changing to TLS
$config['validate'] = TRUE;
It's Works for me, Email is sent via TLS protocol. Maybe this is not the best solution for security. | unknown | |
d551 | train | I have built several mini-SPA apps using both Knockout.js and Ember.js. There are a lot of good reasons for serving a mini-Single-Page-Application rather than converting your entire app, mainly that client-side code doesn't do everything better.
In my experience, both Angular and Ember.js are very useable without making your whole app client-side. Ember gives you some very useful tools for making "widgets".
For example, if I want my Ember application to render on a part of my server-side page, I can do this:
var App = Ember.Application.create({
// Set the rootElement property to the div that I want my ember app to render inside
rootElement: "#your-root-element",
Resolver: Ember.DefaultResolver.extend({
resolveTemplate: function(parsedName) {
// Override this method to make this app look for its templates in a subdirectory
}
}),
});
// Don't render the app on any page by default
App.deferReadiness();
// Instead, check to see if the #rootElement is present on the page before rendering.
$(document).ready(function() {
if ( $(App.get('rootElement')).length > 0 ) {
App.advanceReadiness();
}
});
I'm sure you can do similarly with Angular.js. I prefer Ember for the following reasons:
*
*A genuine class/mixin system. This is really helpful when you want to share code: it should be very familiar to anyone who is used to working on the server side.
*Very flexible templating.
*Clear separation of concerns, allowing many different views and such to be handled elegantly. | unknown | |
d552 | train | The Jquery plugin hide the original select <select id="combobox"> and apply other HTML tags. So, write CSS for the hidden ones won't change a thing.
You should use ui-autocomplete.ui-menu as the css selector to style the dropdown.
Try:
.ui-autocomplete.ui-menu {
z-index: 3001;
} | unknown | |
d553 | train | You will need a xul browser object to load the content into.
Load the "view-source:" version of your page into a the browser object, in the same way as the "View Page Source" menu does. See function viewSource() in chrome://global/content/viewSource.js. That function can load from cache, or not.
Once the content is loaded, the original source is given by:
var source = browser.contentDocument.getElementById('viewsource').textContent;
Serialize a DOM Document
This method will not get the original source, but may be useful to some readers.
You can serialize the document object to a string. See Serializing DOM trees to strings in the MDC. You may need to use the alternate method of instantiation in your extension.
That article talks about XML documents, but it also works on any HTML DOMDocument.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(document);
This even works in a web page or the firebug console.
A: really looks like there is no way to get "all the sourcecode". You may use
document.documentElement.innerHTML
to get the innerHTML of the top element (usually html). If you have a php error message like
<h3>fatal error</h3>
segfault
<html>
<head>
<title>bla</title>
<script type="text/javascript">
alert(document.documentElement.innerHTML);
</script>
</head>
<body>
</body>
</html>
the innerHTML would be
<head>
<title>bla</title></head><body><h3>fatal error</h3>
segfault
<script type="text/javascript">
alert(document.documentElement.innerHTML);
</script></body>
but the error message would still retain
edit: documentElement is described here:
https://developer.mozilla.org/en/DOM/document.documentElement
A: You can get URL with var URL = document.location.href and navigate to "view-source:"+URL.
Now you can fetch the whole source code (viewsource is the id of the body):
var code = document.getElementById('viewsource').innerHTML;
Problem is that the source code is formatted. So you have to run strip_tags() and htmlspecialchars_decode() to fix it.
For example, line 1 should be the doctype and line 2 should look like:
<<span class="start-tag">HTML</span>>
So after strip_tags() it becomes:
<HTML>
And after htmlspecialchars_decode() we finally get expected result:
<HTML>
The code doesn't pass to DOM parser so you can view invalid HTML too.
A: Maybe you can get it via DOM, using
var source =document.getElementsByTagName("html");
and fetch the source using DOMParser
https://developer.mozilla.org/En/DOMParser
A: The first part of Sagi's answer, but use document.getElementById('viewsource').textContent instead.
A: More in line with Lachlan's answer, but there is a discussion of the internals here that gets quite in depth, going into the Cpp code.
http://www.mail-archive.com/mozilla-embedding@mozilla.org/msg05391.html
and then follow the replies at the bottom. | unknown | |
d554 | train | You want the array intersection, and you can obtain it via the & operator:
Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.
[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ] | unknown | |
d555 | train | that is that when an image is not found on the server, the instance of a controller is created
Not really. What I believe is happening is that, since you're using a relative path for the image (and calling it directly inside a controller, which is wrong because you're ouputting something before headers), your browser attach the image directly to the CI url, thus making this request to the server:
index.php/doesntexist.png
Which is (correctly) interpreted by CI as a request to a controller, which doesn't exists, and therefore it issues the error class.
You could do, in your actual code (I'd put the images in a view, though):
echo '<img src="/doesntexist.png" />'
using an absoluth path, or using the base_url() method from the url helper:
echo '<img src="'.base_url().'doesntexist.png" />
This should tell the server to fetch the right request (/test/doesntexist.png) and won't trigger that error. | unknown | |
d556 | train | Do you have a local proxy (e.g. Fiddler) running? If so, you'll need to disable it.
Also, check the certificate is installed properly and in the right place: follow, to the letter, the instructions here:
http://msdn.microsoft.com/en-us/gg271300
in particular noting there are no line breaks or spaces in the path for (get-Item cert:\CurrentUser\MY\XXXXX). | unknown | |
d557 | train | Of course you can send patches to anyone (git diff >file). However, branches contain commits (really, they're just a name for one commit and its ancestors come along for the ride), so it's meaningless to talk about sharing a branch without having committed anything. | unknown | |
d558 | train | The ENTER should be changed with Return, and the function should accept an event
Also, don't forget in a 'class' to use self in the method and self.method to call it.
def up_R(self, event):
print('Makes it here')
self.R.update_disp(self.e.get())
self.rl.config(text=self.R.dkey)
self.e.bind('<Return>', self.up_R) | unknown | |
d559 | train | Output:
Full code:
Column(
children: <Widget>[
Container(
margin: EdgeInsets.only(top: 16.0),
child: Center(
child: Text(
'Circles',
style: TextStyle(fontSize: 18),
),
),
),
Container(
height: 200,
margin: EdgeInsets.only(top: 8.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width * 0.25,
height: MediaQuery.of(context).size.height * 0.2,
margin: EdgeInsets.symmetric(horizontal: 8.0),
child: Center(child: Text('Circle')),
decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
),
Spacer(),
AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return GestureDetector(
onTap: () {
_animationController.forward();
},
child: Container(
width: MediaQuery.of(context).size.width * _animation.value,
height: MediaQuery.of(context).size.height * _animation.value,
margin: EdgeInsets.symmetric(horizontal: 8.0),
child: Center(child: Text('Circle')),
decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
),
);
},
),
Spacer(),
Container(
width: MediaQuery.of(context).size.width * 0.25,
height: MediaQuery.of(context).size.height * 0.2,
margin: EdgeInsets.symmetric(horizontal: 8.0),
child: Center(child: Text('Circle')),
decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
)
],
),
),
],
);
A: first i suggest you delete mainAxisSize: MainAxisSize.min, if that didn't work, try to wrap the animated builder with a container and give it the same proprities as those | unknown | |
d560 | train | I now found my error, it had nothing to do with the resttemplate.
The bootstrap had an error which caused the app to send the request to itself.
The client denied its' own request and Spring did all the errorhandling automatically, so it did not show in the console output as logged by my application, which is why i overlooked it.
After fixing this, the request in the OP worked just fine.
Sorry. | unknown | |
d561 | train | You can use xargs with -P option to run any command in parallel:
seq 1 200 | xargs -n1 -P10 curl "http://localhost:5000/example"
This will run curl command 200 times with max 10 jobs in parallel.
A: Using xargs -P option, you can run any command in parallel:
xargs -I % -P 8 curl -X POST --header "http://localhost:5000/example" \
< <(printf '%s\n' {1..400})
This will run give curl command 400 times with max 8 jobs in parallel.
A: Adding to @saeed's answer, I created a generic function that utilises function arguments to fire commands for a total of N times in M jobs at a parallel
function conc(){
cmd=("${@:3}")
seq 1 "$1" | xargs -n1 -P"$2" "${cmd[@]}"
}
$ conc N M cmd
$ conc 10 2 curl --location --request GET 'http://google.com/'
This will fire 10 curl commands at a max parallelism of two each.
Adding this function to the bash_profile.rc makes it easier. Gist
A: Add “wait” at the end, and background them.
for ((request=1;request<=20;request++))
do
for ((x=1;x<=20;x++))
do
time curl -X POST --header "http://localhost:5000/example" &
done
done
wait
They will all output to the same stdout, but you can redirect the result of the time (and stdout and stderr) to a named file:
time curl -X POST --header "http://localhost:5000/example" > output.${x}.${request}.out 2>1 &
A: Wanted to share my example how I utilised parallel xargs with curl.
The pros from using xargs that u can specify how many threads will be used to parallelise curl rather than using curl with "&" that will schedule all let's say 10000 curls simultaneously.
Hope it will be helpful to smdy:
#!/bin/sh
url=/any-url
currentDate=$(date +%Y-%m-%d)
payload='{"field1":"value1", "field2":{},"timestamp":"'$currentDate'"}'
threadCount=10
cat $1 | \
xargs -P $threadCount -I {} curl -sw 'url= %{url_effective}, http_status_code = %{http_code},time_total = %{time_total} seconds \n' -H "Content-Type: application/json" -H "Accept: application/json" -X POST $url --max-time 60 -d $payload
.csv file has 1 value per row that will be inserted in json payload
A: Update 2020:
Curl can now fetch several websites in parallel:
curl --parallel --parallel-immediate --parallel-max 3 --config websites.txt
websites.txt file:
url = "website1.com"
url = "website2.com"
url = "website3.com"
A: This is an addition to @saeed's answer.
I faced an issue where it made unnecessary requests to the following hosts
0.0.0.1, 0.0.0.2 .... 0.0.0.N
The reason was the command xargs was passing arguments to the curl command. In order to prevent the passing of arguments, we can specify which character to replace the argument by using the -I flag.
So we will use it as,
... xargs -I '$' command ...
Now, xargs will replace the argument wherever the $ literal is found. And if it is not found the argument is not passed. So using this the final command will be.
seq 1 200 | xargs -I $ -n1 -P10 curl "http://localhost:5000/example"
Note: If you are using $ in your command try to replace it with some other character that is not being used.
A: Based on the solution provided by @isopropylcyanide and the comment by @Dario Seidl, I find this to be the best response as it handles both curl and httpie.
# conc N M cmd - fire (N) commands at a max parallelism of (M) each
function conc(){
cmd=("${@:3}")
seq 1 "$1" | xargs -I'$XARGI' -P"$2" "${cmd[@]}"
}
For example:
conc 10 3 curl -L -X POST https://httpbin.org/post -H 'Authorization: Basic dXNlcjpwYXNz' -H 'Content-Type: application/json' -d '{"url":"http://google.com/","foo":"bar"}'
conc 10 3 http --ignore-stdin -F -a user:pass httpbin.org/post url=http://google.com/ foo=bar | unknown | |
d562 | train | I found the answer to my question and record it here for others:
*
*It has been asked before and a first answer can be found here.
*The following information can be found on this MSDN page:
Your application obtains credentials by calling the AcquireCredentialsHandle function, which returns a handle to the requested credentials. Because credentials handles are used to store configuration information, the same handle cannot be used for both client-side and server-side operations. This means that applications that support both client and server connections must obtain a minimum of two credentials handles.
Therefore it can be assumed safe to re-use the same credential handle for multiple connections. And I verified that it indeed makes Schannel re-use the SSL/TLS session. This has been tested on Windows 7 Professional SP1. | unknown | |
d563 | train | Is it possible that you accidentally cleared the "Shows Navigation Bar" setting in the Navigation Controller itself?
A: Have you tried deleting your current Navigation Controller in Storyboard and re-embedding your controller in it (or dragging a new Navigation Controller out and setting its default controller by control-dragging to your VC?) | unknown | |
d564 | train | These are the steps I took:
*
*Copied seed logic to the Migrations Configuration.cs file.
*Excluded an old migration from the project
*Within package console manager performed add-migration and gave it a name
*Then ran update-database -verbose -force AFTER making sure that WebMatrix.WebData reference properties had 'CopyLocal = true'
I hope this helps someone. | unknown | |
d565 | train | Using a sub-query, this can be achieved as following:
q = (select([Item.identifier_id, func.count(Item.id).label("cnt")]).
group_by(Item.identifier_id).having(func.count(Item.id)>1)).alias("subq")
qry = (session.query(Item).join(q, Item.identifier_id==q.c.identifier_id))
print qry # prints SQL statement generated
items = qry.all() # result
A: Here is the version I am finally using:
from sqlalchemy.sql.functions import count
from sqlalchemy.orm import subqueryload
# …
repeats = (
select(
(Item.identifier,
count(Item.identifier)))
.group_by(Item.identifier)
.having(count(Item.identifier) > 1)
.alias())
for identifier in (
sess.query(Identifier)
.join(repeats, repeats.c.identifier==Identifier.value)
.options(subqueryload(Identifier.items))
):
for item in identifier.items:
pass
(Identifier is now mapped against a select and not backed by a database table, which makes import a bit faster too) | unknown | |
d566 | train | This wlil achieve what you want:
contentHeight: contentItem.children[0].childrenRect.height
From Qt docs
Items declared as children of a Flickable are automatically parented to the Flickable's contentItem. This should be taken into account when operating on the children of the Flickable; it is usually the children of contentItem that are relevant.
But I must say it is bad practice for a component to make assumptions about things outside its own QML file, as it makes the component difficult to reuse. Specifically in this case the Flickable is making the assumption that its first child is of a Component type that makes use of the childrenRect property. Your MyFlow component does, but many other components do not, for example an Image. | unknown | |
d567 | train | You could simply add anchor tags with the ID name of the slide to automatically scroll to them:
pills (with anchor tag)
<div class="pills">
<a href="#image-3">
<div class="circle" id="circle-1"></div>
</a>
</div> | unknown | |
d568 | train | Parse the string to form an array between each of the : using something like split()
*
*For the first set multiply by the number of seconds in an hour
*For the second set multiply by the number of seconds in a minute
*For the third set add the number to the total
In other words
totalseconds = array(0)*3600 + array(1)*60 + array(2)
Or in vb.net Code
Dim time As String = "000:3:7"
Dim a() As String
a = longstring.Split(":")
Dim TotalSeconds as Integer = (a(0) * 86400) + (a(1) * 3600) + a(2))
Trace.WriteLine(TotalSeconds.toString)
From the Tag definition of mathmatica
Not to be confused with mathematics (math).
OOPs..
A: Just as harper89 described, in Mathematica:
FromDigits[ToExpression /@ StringSplit[time, ":"], 60]
A: Try the following:
AbsoluteTime[{"000:03:07.447",
{"Hour", ":", "Minute", ":", "Second", ".", "Millisecond"}}]
(* ==> 187.447 *)
The key was giving an explicit date format (see the docs of DateList[])
This solution works in Mathematica 8. It appears that in version 7 (and possibly also in version 6) one needs to correct the result, like this:
AbsoluteTime[{"000:03:07.447",
{"Hour", ":", "Minute", ":", "Second", ".", "Millisecond"}}] -
AbsoluteTime[{"0", {"Hour"}}] | unknown | |
d569 | train | Yes. In-app purchase given by Microsoft is enough for selling apps in windows store. You don't need to worry about third party payment gateway etc.
refer to this link https://msdn.microsoft.com/en-in/library/windows/apps/jj206949(v=vs.105).aspx
examples given on this page are useful. | unknown | |
d570 | train | As mentioned in the comment before I got an answer from another direction:
You have to use DataflowOverrides in the ODBC-Source in BIML. For my example you have to do something like this:
`<OdbcSource Name="mySource" Connection="mySourceConnection">
<DirectInput>SELECT description::varchar(4000) from mySourceTable</DirectInput>
<DataflowOverrides>
<OutputPath OutputPathName="Output">
<Columns>
<Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" />
</Columns>
</OutputPath>
<OutputPath OutputPathName="Error">
<Columns>
<Column ColumnName="description" SsisDataTypeOverride="DT_WSTR" DataType="String" Length="4000" />
</Columns>
</OutputPath>
</DataflowOverrides>
</OdbcSource>`
You won't have to do the Overrides for all columns, only for the ones you have mapping-Issues with.
Hope this solution can help anyone who passes by.
Cheers | unknown | |
d571 | train | The following example disables the resizing of a tkinter GUI using the resizable method.
import tkinter as tk
class App(tk.Frame):
def __init__(self,master=None,**kw):
tk.Frame.__init__(self,master=master,**kw)
tk.Canvas(self,width=100,height=100).grid()
if __name__ == '__main__':
root = tk.Tk()
App(root).grid()
root.resizable(width=False,height=False)
root.mainloop()
A: Even though you have an answer, here's a shortened code, without classes (if you want):
from tkinter import Tk
root = Tk()
root.geometry("500x500")
root.resizable(False, False)
root.mainloop()
A: try this. It should help.
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width='you can decide', height='you can decide')
canvas.pack()
canvas.mainloop() | unknown | |
d572 | train | In terms of libraries, the only one I know of is OpenSAML.
I wouldn't call things like OpenAM a framework. They are actually products. Both these work with ADFS. Be warned that it is not a trivial task to install and configure these.
Another good product is Ping Identity.
There's also a set of Step-by-Step and How To Guides.
A: In case your are considering openam here is the link.
https://wikis.forgerock.org/confluence/display/openam/Integrate+OpenAM+with+Shibboleth
Also there are few more links on how to install openam as IDP
https://wikis.forgerock.org/confluence/pages/viewpage.action?pageId=688150
-Ram | unknown | |
d573 | train | Why don't you use an npm package for screen recording?
Also your while loop doesn't represent seconds but discrete steps. If you want a time based recording you need some implementation which respects time based steps with step delta to allow adjustment for different rendering speeds. (This is similar to game loops, the only difference is that your action is screen captures and not moving game characters.)
A good screen recording package should do that, as well as providing an API for export. Save your time and effort and use a package for that.
Good point to start: https://www.npmjs.com/search?q=screen+recording | unknown | |
d574 | train | I have created one demo APP for this. In this APP, i am posting status and uploading photo but i have never got fail error.
- (IBAction)btnSocialSharing:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Social Media"
delegate:self
cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil
otherButtonTitles:@"Facebook", @"Twitter" ,nil];
// actionSheet.tag = 100;
[actionSheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *buttonTitle=[actionSheet buttonTitleAtIndex:buttonIndex];
// NSString *image=[UIImage imageNamed:chooseImage];
if ([buttonTitle isEqualToString:@"Facebook"])
{
SLComposeViewController *controller = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock =
^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled)
{
NSLog(@"Cancelled");
}
else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:self.txtStatus.text];
[controller addImage:chooseImage];
[self presentViewController:controller animated:YES completion:nil];
}
else if ([buttonTitle isEqualToString:@"Twitter"])
{
SLComposeViewController *controller = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
SLComposeViewControllerCompletionHandler myBlock =
^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled)
{
NSLog(@"Cancelled");
}
else
{
NSLog(@"Done");
}
[controller dismissViewControllerAnimated:YES completion:nil];
};
controller.completionHandler =myBlock;
[controller setInitialText:self.txtStatus.text];
[controller addImage:chooseImage];
[self presentViewController:controller animated:YES completion:nil];
}
}
- (IBAction)btnSelectPhoto:(id)sender {
NSLog(@"Select Photos button");
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
//Image Picker Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
chooseImage = info[UIImagePickerControllerEditedImage];
[picker dismissViewControllerAnimated:YES completion:NULL];
[self displayImage];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)displayImage
{
self.viewImage.image = chooseImage;
} | unknown | |
d575 | train | Why do you want to make it synchronous?
If you want to do something after members, just do it in callback function.
var callback=function(res){
retrived=retrieved.concat(res);
//continue do other things
};
client.smembers("offer", function (err, replies) {
if(!err){
callback(replies);
}
})
If you want to do something after a loop,you can try _.after of underscore.js,for example:
var times=10;
var arrayOfReplies=[]; //store all replies
var callback=function(){
//do something with arrayOfReplies
}
var afterAll = _.after(times,callback); //afterAll's callback is a function which will be run after be called 10 times
for(var i=0;i<10;i++){
client.smembers("offer", function (err, replies) {
if(!err){
arrayOfReplies=arrayOfReplies.concat(replies);
afterAll();
}
})
}
see more:http://underscorejs.org/#after | unknown | |
d576 | train | Even if it doesn't make Apple reject your app, think of the users not being used to the tab bar being at the top and how that is going to affect how well the app does in the Store.
Every platform has its own design patterns and there is a reason for that. If you stick to them there is a higher chance that the first-time users have an easier time using your app, which results in a higher chance that they keep using it. If they don't know how to use it or find it hard, they will move to another one.
Take a look at the Human Interface Guidelines and apply them. It will do good. | unknown | |
d577 | train | Don't use a regex for this. Instead, use parse_url() and parse_str().
$params = array();
$url= "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food";
$url_query = parse_url($url, PHP_URL_QUERY);
parse_str($url_query, $params);
echo $params['q']; // Outputs food
Demo
A: A perfect tutorial for what you're trying to accomplish:
$parts = parse_url('http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food');
parse_str($parts['query'], $query);
echo $query['q']; | unknown | |
d578 | train | You could do this with the redirectTo property or the authenticated method:
redirectTo property: docs
If the redirect path needs custom generation logic you may define a
redirectTo method instead of a redirectTo property:
protected function redirectTo()
{
$user = Auth::user();
if($user->first_time_login){
$user->first_time_login = false;
$user->save();
return '/users/edit';
}else{
return '/home';
}
}
authenticated method:
protected function authenticated(Request $request, $user)
{
if ($user->first_time_login) {
$url = '/users/edit';
$user->first_time_login = false;
$user->save();
} else {
$url = $this->redirectTo;
}
return redirect($url);
}
A: I have found the problem, i had to add return redirect()->to('/users/edit'); on the bottom of the auth function that $this->redirrectTo is the default if the user has not already navigated to a different authed route.
My code now looks like this:
if ($user->first_time_login == true || $user->first_time_login == 1) {
$this->redirectTo = '/users/edit';
$user->first_time_login = false;
$user->save();
return redirect()->to('/users/edit');
} | unknown | |
d579 | train | The code below uses pandas.duplicate(), pandas.merge(), pandas.groupby/sum and pandas.cumsum() to come to the desired output:
# creates a series of weights to be considered and rename it to merge
unique_weights = df['weight'][~df.duplicated(['weight'])]
unique_weights.rename('consider_cum', inplace = True)
# merges the series to the original dataframe and replace the ignored values by 0
df = df.merge(unique_weights.to_frame(), how = 'left', left_index=True, right_index=True)
df.consider_cum = df.consider_cum.fillna(0)
# sums grouping by date and time
df = df.groupby(['date', 'time']).sum().reset_index()
# create the cumulative sum column and present the output
df['weight_cumsum'] = df['consider_cum'].cumsum()
df[['date', 'time', 'weight_cumsum']]
Produces the following output: | unknown | |
d580 | train | A Karnaugh map as suggested by paddy, will give you a set of minterms which fulfil the expression. That is the classical way to tackle such problems.
By inspection of the truth-table you can convince yourself, that the output is true whenever In_1 is unequal In_3 or In_1 is unequal In_2:
f = (In_1 xor In_2) or (In_1 xor In_3) | unknown | |
d581 | train | Yes, you can if test3 is public structure type nested inside public structure type test2 which is nested inside test1
struct test1{
public struct test2{
public struct test3{
public test3(string p1,string p2) {/*do something*/}
//some params
}
//some params
//some params
}
Also test1 and test2 could be namespaces. | unknown | |
d582 | train | In MySQL, the DATE type maps to the Java class java.sql.Timestamp. So you should be working with this type to build your query, and not java.util.Date. Here is code which generates the two timestamps you will need:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date startDate = formatter.parse(startDate);
java.util.Date endDate = formatter.parse(endDate);
java.sql.Timestamp start = new Timestamp(startDate.getTime());
java.sql.Timestamp end = new Timestamp(endDate.getTime());
Then use your first BETWEEN query to get your result:
PreparedStatement ps = con.prepareStatement("SELECT * FROM project.order
WHERE PO_Date BETWEEN ? AND ?");
ps.setTimestamp(1, start);
ps.setTimestamp(2, end)
Note here that I am using a parametrized PreparedStatement, which avoids (or at least greatly lessens) the possibility of SQL injection.
A: Try this
SELECT * FROM project.order po
WHERE po.PO_Date IS NOT NULL
AND TO_DATE(PO_Date, 'DD/MM/RRRR') >=
TO_DATE('17/02/2015', 'DD/MM/RRRR')
AND TO_DATE(PO_Date, 'DD/MM/RRRR') <=
TO_DATE('20/06/2015', 'DD/MM/RRRR'); | unknown | |
d583 | train | ExecuteReader doesn't actually perform the query. The first call to .Read() will throw the error.
If you want to only catch the SqlException you can do the following:
Try
TestReader = TestSqlCommand.ExecuteReader()
TestReader.Read()
Catch ex As SqlException
Console.WriteLine("SQL error.")
Catch ex As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally")
End Try
A: For me this fixes the SSMS
exec sp_executesql N'select 1 where N''a'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'
exec sp_executesql N'select 1 where N''1'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'
I totally disagree with Rene Reader.
On my system it executes on ExecuteReader.
ExecuteReader would be a real bad name if it did not actually execute.
Did you consider that it is not catching and exception because it is not throwing an exception.
I know you see an error in SQL Profiler but if I introduce a syntax error it is caught.
This is C# but is is not throwing an exception for me.
And if I change it to:
"select 1 where N'a' = @p1";
Then it returns a row.
If I introduce a syntax error:
"select 1 whereX 1 = @p1";
Then it does throw an exception and it throws it on the ExecuteReader line.
If you want 1 to be a literal you should use:
"select 1 where '1' = @p1";
SQLcmd.CommandType = CommandType.Text;
SQLcmd.CommandText = "select 1 where N'1' = @p1";
SqlParameter TestSqlParameter = new SqlParameter();
TestSqlParameter.ParameterName = "@p1";
TestSqlParameter.SqlDbType = SqlDbType.NChar;
TestSqlParameter.Value = "a";
SQLcmd.Parameters.Add(TestSqlParameter);
try
{
rdr = SQLcmd.ExecuteReader();
Int32 waste;
if (rdr.HasRows)
{
while (rdr.Read())
{
waste = rdr.GetInt32(0);
}
}
}
catch (Exception Ex)
{
Debug.WriteLine(Ex.Message);
}
A: I solved this problem if the sql string passed used EXEC sp_executesql by ensuring I read every result and result set... like so:
....
using (var conn = new SqlConnection(_connectionString))
{
try
{
conn.Open();
using (var cmd = new SqlCommand(sql, conn))
{
cmd.CommandTimeout = 0;
using (var rdr = cmd.ExecuteReader())
{
// TODO: Do stuff with the rdr here.
FlushReader(rdr);
}
}
}
catch (Exception ex)
{
_logger.Fatal("Exception: {0}\r\nSQL:\r\n{1}", ex.Message, sql);
throw;
}
finally
{
conn.Close();
}
}
...
/// <summary>
/// Continue trying to read in case the server threw an exception.
/// </summary>
private static void FlushReader(IDataReader rdr)
{
while (rdr.Read())
{
}
while (rdr.NextResult())
{
while (rdr.Read())
{
}
}
}
Without calling the FlushReader method the application continues without throwing an exception of any kind. Even if I use a SQL THROW statement. Running the same sql in SQL management studio will show the error.
Hope this helps. | unknown | |
d584 | train | MPI covers most of your needs via the MPI Profiling Interface (aka PMPI).
Simply redifines the MPI_* subroutines you need, and have them call the original PMPI_* corresponding subroutine.
In you case:
int MPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
{
printf(" Calling MPI_Send ************** \n");
PMPI_Send(buf, count, datatype, dest, tag, comm);
}
Since you want to print the line and file of the caller, you might have to use macros and rebuild your app:
#define MPI_Send(buf,count,MPI_Datatype, dest, tag, comm) \
myMPI_Send(buf, count, MPI_Datatype, dest, tag, comm, __func__, __FILE__, __LINE__)
int myMPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, char *func, char *file, int line)
{
printf(" Calling MPI_Send ************** from %s at %s:%d\n", func, file, line);
return PMPI_Send(buf, count, datatype, dest, tag, comm);
} | unknown | |
d585 | train | Just loop the number generation until it generated a new number:
int[] randomNum = new int[20];
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int number;
do
{
number = RandomNumber.Next(1, 80);
} while(randomNum.Contains(number));
randomNum[i] = number;
}
foreach (int j in randomNum)
{
Console.WriteLine("First Number:{0}", j);
Thread.Sleep(200);
}
A: According to your last comment, I would say:
for (int i = 0; i < 20; i++)
{
int num;
do
{
num = RandomNumber.Next(1, 80);
} while (randomNum.Contains(num));
randomNum[i] = num;
}
A: Why you used array for this? If you want to print random numbers, you can write this.
Random RandomNumber = new Random();
for (int i = 0; i < 20; i++)
{
int randomNum = RandomNumber.Next(1, 80);
Console.WriteLine("Number:{0}", randomNum);
Thread.Sleep(200);
}
A: you don't need in randomNum. Just do it so:
for (int i = 0; i < 20; i++)
{
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}
If you wanna avoid dublication, do so:
List<int> intList = new List();
for (int i = 0; i < 20; i++)
{
int r = RandomNumber.Next(1, 80);
foreach(int s in intList) if(s!=r){
intList.Add(s);
Console.WriteLine("First Number:{0}", RandomNumber.Next(1, 80));
}else i--;
} | unknown | |
d586 | train | I only dabbled with WiX a little, and it's been some years since then, but I think you need to put your code in a function:
<CustomAction Id="EXENotFound" Script="vbscript" Return="check">
<![CDATA[
Function AskUser
AskUser = 0
If session.Property("REMINDEX_SHORTCUT") = "" Then
AskUser = MsgBox(session.Property("TextProp"), 1)
End If
End Function
]]>
</CustomAction>
A: If you're in the UI sequence, then the correct way to do this is to show a standard dialog built using your MSI development tool, and wire up the Cancel logic if that's one of the choices. That's mostly covered by other answers. The correct way to show a message in the execute sequence (from a custom action) is to call MsiProcessMessage (or installer object or DTF managed CA equivalents). Return IDCANCEL if appropriate.
https://msdn.microsoft.com/en-us/library/aa370354(v=vs.85).aspx
http://microsoft.public.platformsdk.msi.narkive.com/oKHfPSZc/using-msiprocessmessage-in-a-c-custom-action | unknown | |
d587 | train | The documentation page explains quite well how to setup d3 in your localhost.
You have to:
*
*include d3.js in your page using:
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
*start a python server if you want to access local files using:
python -m SimpleHTTPServer 8888 &
A: Thanks a lot for your suggestion.
But actually, The problem was that i did not put my javascript code in
$(document).ready(function(){//here})
It works great now :) ..
Thank you Christopher and FernOfTheAndes for all the help | unknown | |
d588 | train | You might want to try this service from the NIST:
NIST Internet Time Service. They have a list of servers here. and tips on how to engage with their system from Windows, OSX, and Linux. The response might be quick enough to hold you over until your NTP client can receive its response. | unknown | |
d589 | train | You can map with sum, and get the sum of the result:
sum(map(sum, t))
# 6
Or if you prefer it with a for loop:
res = 0
for i in t:
res += sum(i)
print(res)
# 6
A: You can use simple iteration (works in python3.8, I assume it works on older versions as well).
t = ((1, 1), (1, 1), (1, 1))
sum_tuples = 0
for a,b in t:
sum_tuples += a # First element
sum_tuples += b # Second Element
print(sum_tuples) # prints 6
A: You could use itertools.chain
>>> import itertools
>>> t = ((1, 1), (1, 1), (1, 1))
>>> sum(itertools.chain.from_iterable(t))
6
A: You can loop tuple to sum all. This code is long but it can sum tuple in tuple.
t = ((1, 1), (1, 1), (1, 1))
# Tuple in tuple:
t = ((1, 1, (1, 1, (1, 1))))
def getsum(var, current = 0):
result = current
if type(var) == tuple:
for i in range(len(var)):
x = var[i]
result = getsum(x, result)
else:
result += var
return result
print(getsum(t)) | unknown | |
d590 | train | Found my answer from Microsoft support guys. Office Store enrollment is still separate from Marketplace enrollment. You must be enrolled in Office Store program to see Office add-in option in the Offers dropdown.
If you've already signed up for Partner Center, you can find information about creating a Developer account for Microsoft Office Store on the following page:
https://learn.microsoft.com/en-in/azure/marketplace/open-a-developer-account#create-an-account-using-an-existing-partner-center-enrollment | unknown | |
d591 | train | Here is the code for an example 3d graph:
public void plot3d() {
JGnuplot jg = new JGnuplot();
Plot plot = new Plot("") {
{
xlabel = "x";
ylabel = "y";
zlabel = "z";
}
};
double[] x = { 1, 2, 3, 4, 5 }, y = { 2, 4, 6, 8, 10 }, z = { 3, 6, 9, 12, 15 }, z2 = { 2, 8, 18, 32, 50 };
DataTableSet dts = plot.addNewDataTableSet("3D Plot");
dts.addNewDataTable("z=x+y", x, y, z);
dts.addNewDataTable("z=x*y", x, y, z2);
jg.execute(plot, jg.plot3d);
}
It produces the following figure:
Here are more examples: 2D Plot, Bar Plot, 3D Plot, Density Plot, Image Plot... | unknown | |
d592 | train | You have two syntax errors in your code:
*
*create function does not support if exists
*character is a reserved SQL keyword.
The below appears to work for me. I'd suggest using an SQL 'ide' such as MySQL workbench. It will show you syntax errors straight away.
DROP function IF EXISTS LeaveNumber;
delimiter //
create function LeaveNumber(str varchar(50)) returns varchar(50)
no sql
begin
declare verification varchar(50);
declare result varchar(50) default '';
declare nextChar varchar(2);
declare i integer default 1;
if char_length(str) > 0 then
while(i <= char_length(str)) do
set nextChar = substring(str,i,1);
set verification = find_in_set(nextChar,'1,2,3,4,5,6,7,8,9,0');
if verification > 0 then
set result = concat(result,nextChar);
end if;
set i = i + 1;
end while;
return result;
else
return '';
end if;
end //
delimiter ; | unknown | |
d593 | train | You can try sum(axis=1) by slicing the datetime like columns to calculate YTD and just use loc to get MTD
EndDate = '31/03/2022'
date_cols = df.filter(regex='\d{2}/\d{2}/\d{4}')
date_cols.columns = pd.to_datetime(date_cols.columns, dayfirst=True)
df['YTD_Column'] = date_cols.loc[:, :pd.to_datetime(EndDate, dayfirst=True)].sum(axis=1)
df['MTD_Column'] = df[EndDate]
Account Names 31/01/2022 28/02/2022 31/03/2022 30/04/2022 YTD_Column MTD_Column
0 Cash At Bank 100 150 100 150 350 100
1 Debtors 50 50 50 100 150 50
2 Inventory 250 250 350 100 850 350
3 PAYG Withheld 50 50 10 150 110 10 | unknown | |
d594 | train | Object reference not set to an instance of an object means that you're trying to access some member of an uninstantiated object. What that means is that you forgot to create the object (via new).
In your case, you're probably trying to use frmD or Picture1 before it has been created. | unknown | |
d595 | train | Solution is to use pdflatex and Sumatra PDF, since this viewer auto-reloads the file. | unknown | |
d596 | train | Solved by transforming the image (OpenCV, pillow ...) into bytes
import base64
import cv2
import streamlit as st
retval, buffer = cv2.imencode('.jpg', img )
binf = base64.b64encode(buffer).decode()
st.image("data:image/png;base64,%s"%binf, channels="BGR", use_column_width=True) | unknown | |
d597 | train | This is the Docs from https://msdn.microsoft.com/en-us/library/windows/desktop/gg537710(v=vs.85).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
IShellDispatch.BrowseForFolder( _
ByVal Hwnd As Integer, _
ByVal sTitle As BSTR, _
ByVal iOptions As Integer, _
[ ByVal vRootFolder As Variant ] _
) As FOLDER
and these are the flags see BIF_BROWSEINCLUDEURLS and BIF_SHAREABLE
ulFlags
Type: UINT
Flags that specify the options for the dialog box. This member can be 0 or a combination of the following values. Version numbers refer to the minimum version of Shell32.dll required for SHBrowseForFolder to recognize flags added in later releases. See Shell and Common Controls Versions for more information.
BIF_RETURNONLYFSDIRS (0x00000001)
0x00000001. Only return file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
Note The OK button remains enabled for "\\server" items, as well as "\\server\share" and directory items. However, if the user selects a "\\server" item, passing the PIDL returned by SHBrowseForFolder to SHGetPathFromIDList fails.
BIF_DONTGOBELOWDOMAIN (0x00000002)
0x00000002. Do not include network folders below the domain level in the dialog box's tree view control.
BIF_STATUSTEXT (0x00000004)
0x00000004. Include a status area in the dialog box. The callback function can set the status text by sending messages to the dialog box. This flag is not supported when BIF_NEWDIALOGSTYLE is specified.
BIF_RETURNFSANCESTORS (0x00000008)
0x00000008. Only return file system ancestors. An ancestor is a subfolder that is beneath the root folder in the namespace hierarchy. If the user selects an ancestor of the root folder that is not part of the file system, the OK button is grayed.
BIF_EDITBOX (0x00000010)
0x00000010. Version 4.71. Include an edit control in the browse dialog box that allows the user to type the name of an item.
BIF_VALIDATE (0x00000020)
0x00000020. Version 4.71. If the user types an invalid name into the edit box, the browse dialog box calls the application's BrowseCallbackProc with the BFFM_VALIDATEFAILED message. This flag is ignored if BIF_EDITBOX is not specified.
BIF_NEWDIALOGSTYLE (0x00000040)
0x00000040. Version 5.0. Use the new user interface. Setting this flag provides the user with a larger dialog box that can be resized. The dialog box has several new capabilities, including: drag-and-drop capability within the dialog box, reordering, shortcut menus, new folders, delete, and other shortcut menu commands.
Note If COM is initialized through CoInitializeEx with the COINIT_MULTITHREADED flag set, SHBrowseForFolder fails if BIF_NEWDIALOGSTYLE is passed.
BIF_BROWSEINCLUDEURLS (0x00000080)
0x00000080. Version 5.0. The browse dialog box can display URLs. The BIF_USENEWUI and BIF_BROWSEINCLUDEFILES flags must also be set. If any of these three flags are not set, the browser dialog box rejects URLs. Even when these flags are set, the browse dialog box displays URLs only if the folder that contains the selected item supports URLs. When the folder's IShellFolder::GetAttributesOf method is called to request the selected item's attributes, the folder must set the SFGAO_FOLDER attribute flag. Otherwise, the browse dialog box will not display the URL.
BIF_USENEWUI
Version 5.0. Use the new user interface, including an edit box. This flag is equivalent to BIF_EDITBOX | BIF_NEWDIALOGSTYLE.
Note If COM is initialized through CoInitializeEx with the COINIT_MULTITHREADED flag set, SHBrowseForFolder fails if BIF_USENEWUI is passed.
BIF_UAHINT (0x00000100)
0x00000100. Version 6.0. When combined with BIF_NEWDIALOGSTYLE, adds a usage hint to the dialog box, in place of the edit box. BIF_EDITBOX overrides this flag.
BIF_NONEWFOLDERBUTTON (0x00000200)
0x00000200. Version 6.0. Do not include the New Folder button in the browse dialog box.
BIF_NOTRANSLATETARGETS (0x00000400)
0x00000400. Version 6.0. When the selected item is a shortcut, return the PIDL of the shortcut itself rather than its target.
BIF_BROWSEFORCOMPUTER (0x00001000)
0x00001000. Only return computers. If the user selects anything other than a computer, the OK button is grayed.
BIF_BROWSEFORPRINTER (0x00002000)
0x00002000. Only allow the selection of printers. If the user selects anything other than a printer, the OK button is grayed.
In Windows XP and later systems, the best practice is to use a Windows XP-style dialog, setting the root of the dialog to the Printers and Faxes folder (CSIDL_PRINTERS).
BIF_BROWSEINCLUDEFILES (0x00004000)
0x00004000. Version 4.71. The browse dialog box displays files as well as folders.
BIF_SHAREABLE (0x00008000)
0x00008000. Version 5.0. The browse dialog box can display sharable resources on remote systems. This is intended for applications that want to expose remote shares on a local system. The BIF_NEWDIALOGSTYLE flag must also be set.
BIF_BROWSEFILEJUNCTIONS (0x00010000)
0x00010000. Windows 7 and later. Allow folder junctions such as a library or a compressed file with a .zip file name extension to be browsed. | unknown | |
d598 | train | I think that the reason of your issue is this line sheet2.getRange(row, 1, 1, 9).copyTo(sheet2.getRange(row, 1, 48, 9), SpreadsheetApp.CopyPasteType.PASTE_VALUES). In this line, the value is copied to 48 rows. But at the next loop, the value is copied to the row of (48 + 1).
In order to remove this issue, how about the following modification?
Pattern 1:
In this modification pattern, the for loop is modified by adjusting the row number.
From:
for (var CR = 1 ; CR < sheet2LastRow; CR++) {
Logger.log(CR); // 1 > 46
sheet2.getRange((CR + 1), 1, 1, 59).moveTo(sheet2.getRange((CR * 49), 1));
// transpose data from rows to columns for Data Studio
sheet2.getRange(1, 12, 1, 48).copyTo(sheet2.getRange((CR * 49), 10), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true); // Dimension
sheet2.getRange((CR * 49), 12, 1, 48).copyTo(sheet2.getRange((CR * 49), 11), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true); // Opportunity
sheet2.getRange((CR * 49), 1, 1, 9).copyTo(sheet2.getRange((CR * 49), 1, 48, 9), SpreadsheetApp.CopyPasteType.PASTE_VALUES); // Respondent Info
}
To:
for (var CR = 1 ; CR < sheet2LastRow; CR++) {
var row = (CR * 49) - (CR - 1);
sheet2.getRange((CR + 1), 1, 1, 59).moveTo(sheet2.getRange(row, 1));
sheet2.getRange(1, 12, 1, 48).copyTo(sheet2.getRange(row, 10), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);
sheet2.getRange(row, 12, 1, 48).copyTo(sheet2.getRange(row, 11), SpreadsheetApp.CopyPasteType.PASTE_VALUES, true);
sheet2.getRange(row, 1, 1, 9).copyTo(sheet2.getRange(row, 1, 48, 9), SpreadsheetApp.CopyPasteType.PASTE_VALUES);
}
Pattern 2:
In this modification pattern, the for loop is not modified. After all values were copied, the empty rows are deleted.
From:
sheet2.deleteRows(2, 47);
var sheet2NewLastRow = sheet2.getLastRow();
To:
sheet2.deleteRows(2, 47);
var values = sheet2.getRange("A2:DL").getValues();
for (var i = values.length - 1; i >= 0; i--) {
if (values[i].every(e => !e.toString())) sheet2.deleteRow(i + 2);
}
var sheet2NewLastRow = sheet2.getLastRow(); | unknown | |
d599 | train | This should work for you:
notes_service.js
app.factory ('NoteService', function($http) {
return {
getAll: function() {
return $http.get('/notes.json').then(function(response) {
return response.data;
});
}
}
});
navCtrl.js
NotesService.getAll().then(function(res){
$scope.cleanArrayOfNotes = res.data;
});
Or, if you want to return the result rather than the promise, you can:
notes_service.js
app.factory ('NoteService', function($http) {
var notes = [];
var promise = $http.get('/notes.json').then(function(response) {
angular.copy(response.data, notes);
return notes;
});
return {
getAll: function() {
return notes;
},
promise: promise
}
});
navCtrl.js
// get array of notes
scope.cleanArrayOfNotes = NotesService.getAll();
// or use promise
NoteService.promise.then(function(response) {
scope.cleanArrayOfNotes = response.data;
}); | unknown | |
d600 | train | use instead of every <a> tags from <span> tag.
<div class="row">
<h3 style="margin-right: 14px;">مشخصات شاگرد</h3>
<div class="col-md-4" style="padding-left: 0px;" id="student_info">
<div class="list-group">
<span href="" class="list-group-item disabled student_details">نام</span>
<span href="" class="list-group-item student_details">تخلص</span>
<span href="" class="list-group-item disabled student_details">نام پدر</span>
<span href="" class="list-group-item student_details">جنسیت</span>
<span href="" class="list-group-item disabled student_details">سن</span>
<span href="" class="list-group-item student_details">تلیفون</span>
<span href="" class="list-group-item student_details disabled">آدرس</span>
<span href="" class="list-group-item student_details">ایمیل</span>
<span href="" class="list-group-item student_details disabled">حالت مدنی</span>
<span href="" class="list-group-item student_details">نمبر تذکره</span>
</div>
</div>
<div class="col-md-8" style="padding-right: 0px;" id="student_info_date">
<div class="list-group">
<span href="" class="list-group-item student_details disabled"> {{ $student->first_name }} </span>
<span href="" class="list-group-item student_details">{{ $student->last_name }}</span>
<span href="" class="list-group-item student_details disabled"> {{ $student->father_name }} </span>
<span href="" class="list-group-item student_details">{{ $student->gender }}</span>
<span href="" class="list-group-item student_details disabled"> {{ $student->age }} </span>
<span href="" class="list-group-item student_details">{{ $student->phone }}</span>
<span href="" class="list-group-item student_details disabled"> {{ $student->address }} </span>
<span href="" class="list-group-item student_details"> {{ $student->email_address }} </span>
<span href="" class="list-group-item student_details disabled"> {{ $student->marital_status }} </span>
<span href="" class="list-group-item student_details"> {{ $student->ssn_number }} </span>
</div>
</div>
</div> | unknown |