_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d2701 | train | You should be able to simply put your number to call in the href attribute of your a element and precede it with 'tel:as a protocol indicator. If you want to make it stick to the bottom of your page, use thefixed` position CSS style. For example:
<style>
a.phoneMe {
position: fixed;
right: 0px;
bottom: 0px;
left: 0px;
height: 30px;
background: green;
color: white;
}
</style>
<a href="tel:1234567890" class="phoneMe">Call Now!</a> | unknown | |
d2702 | train | This is the way SharePoint works, canceling a workflow deletes all related tasks, but the workflow history is kept. Do not rely on tasks as a proof that something did or did not happen. | unknown | |
d2703 | train | As pointed out by Danizavtz, the issue was that I had two variables named res. Changed the variable name in bcrypt.compare() from res to result and now everything works perfectly. | unknown | |
d2704 | train | first do you know what was the default layout for both of your panel's ?
and the shortest work solution is to make the root panel use BorderLayout and when adding the counter call on your root panel object
add(BorderLayout.NORTH,theCounterObject);
and for the button's panel call this on the root panel too
add(BorderLayout.CENTER,theButtonsPanel);
this would solve it in shortened version but it's better to learn not a sip or part but all about layout managers as they are very important for swing , here is start A Visual Guide to Layout Managers.
the pack() method is not necessary but it's a great way to fetch the perfect size it was a good idea from the comment but the problem was about your layout witch was FlowLayout and it's the default for panel but you should do it after changing the layout . | unknown | |
d2705 | train | nextTick simply schedules your function to be invoked on the next tick of the event loop. It does not give that function magical non-blocking properties; JavaScript is still single-threaded. If the function blocks (by performing a lot of CPU-bound work), it will still cause I/O events to queue until the function finishes.
If you need to do CPU-intensive work, do it in a worker process.
A: nextTick is a blocking call (in node v0.10.29 at least, where I tested this), it prevents other events from running. use setImmediate()
A: setImmediate will work better as explained in my blog post setTimeout and Friends as it will allow IO tasks to run before again locking up the main execution thread for a full run of compute. But as the other answers posted suggest, the way to think of this is not "nextTick doesn't work", but perhaps "oops I'm trying to do one of the only things you absolutely must not do in a node.js app and I'm getting the result I was warned about". You can't hog the execution thread in node as it is cooperative multitasking. Break computation into small chunks, use external process helpers, split something off into a supporting C++ library, etc.
A: I'll rewrite your code a little bit. Say we need to process 1000000s of items, and there is a (cpu bound, but ok to call sometimes) function computeItem() and io-bound postItem(). We want to process as much items as possible in the background, but still have responsive event loop. For simplicity, no external workers / queues / services used. Possible solution:
var desiredLatency = 10; // ms
function doBackgroundWork() {
var start = new Date();
var end;
var item;
while (item = computeItem()) {
postItem(item);
if (end - start >= desiredLatency) {
setImmediate(doBackgroundWork); // resume at next event loop invocation after processing other handlers
}
}
}
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
}).listen(5000, '127.0.0.1');
doBackgroundWork(); | unknown | |
d2706 | train | *
*choose an x at random between -100 and 100
*a circle is defined by x^2 + y^2 = r^2, which in your case equals 100^2 = 10000
*From this equation you can get that y^2 = 10000 - x^2 , therefore the points with a chosen x and y = +/-sqrt(10000 - x^2) will lye on the circle.
*choose an y at random between the two coordinates found at point 3
*You're set!
EDIT:
In JS:
var radius = 100;
x = Math.random() * 2 * radius - radius;
ylim = Math.sqrt(radius * radius - x * x);
y = Math.random() * 2 * ylim - ylim;
Another edit: a jsFiddle Example
A: If you want equidistributed coordinates you better go for
var radius = 100
var center_x = 0
var center_y = 0
// ensure that p(r) ~ r instead of p(r) ~ constant
var r = radius*Math.sqrt(Math.random(1))
var angle = Math.sqrt(2*Math.PI)
// compute desired coordinates
var x = center_x + r*Math.cos(angle);
var y = center_y + r*Math.sin(angle);
If you want more points close to the middle then use
var r = radius*Math.random(1)
instead.
A: not sure what you mean for javascript but
x = R*cos(theta) and y = R*sin(theta) are the Cartesian points for a circle. R is the radius of course and theta is the angle which goes from 0 to 2*Pi.
A: I'm posting this as a solution because this question was the only relevant result in google.
My question/problem was how to add cartesian coordinates inside a circle where x and y would not exceed r.
Examples:
*
*plot: (45,75) inside a circle with a radius of 100 (this would normally fall inside the circle, but not the correct position)
*plot: (100,100) inside a circle with a radius of 100 (this would normally fall outside the circle
Solution
// The scale of the graph to determine position of plot
// I.E. If the graph visually uses 300px but the values only goto 100
var scale = 100;
// The actual px radius of the circle / width of the graph
var radiusGraph = 300;
// Plot the values on a cartesian plane / graph image
var xCart = xVal * radiusGraph;
var yCart = yVal * radiusGraph;
// Get the absolute values for comparison
var xCartAbs = Math.abs( xCart );
var yCartAbs = Math.abs( yCart );
// Get the radius of the cartesian plot
var radiusCart = Math.sqrt( xCart * xCart + yCart * yCart );
// Compare to decide which value is closer to the limit
// Once we know, calculate the largest possible radius with the graphs limit.
// r^2 = x^2 + y^2
if ( xCartAbs > yCartAbs ) { // Less than 45°
diff = scale / xCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( yCartAbs * diff, 2) );
} else if ( yCartAbs > xCartAbs ) { // Greater than 45°
diff = scale / yCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( xCartAbs * diff, 2) );
} else { // 45°
radiusMaximum = Math.sqrt( 2 * ( radiusGraph * radiusGraph ) );
}
// Get the percent of the maximum radius that the cartesian plot is at
var radiusDiff = radiusCart / radiusMaximum;
var radiusAdjusted = radiusGraph * radiusDiff;
// Calculate the angle of the cartesian plot
var theta = Math.atan2( yCart, xCart );
// Get the new x,y plot inside the circle using the adjust radius from above
var xCoord = radiusAdjusted * Math.cos( theta );
var yCoord = radiusAdjusted * Math.sin( theta );
A: Not sure if this is correct JavaScript code, but something like this:
for (x = -r; x < r; x++) {
for (y = -r; x < r; y++) {
if ((x * x + y * y) < (r * r)) {
// This x/y coordinate is inside the circle.
// Use <= if you want to count points _on_ the circle, too.
}
}
} | unknown | |
d2707 | train | UMD modules, by definition, are CommonJS. The code above is just IIFE and relies on mak global.
IIFE wrapper function can be replaced with default or named ES module export:
const mak = {};
mak.MessageKindEnum = { ... };
...
export default mak;
Or with CommonJS export:
const mak = {};
mak.MessageKindEnum = { ... };
...
module.exports = mak;
A: did you try:
(function (mak) {
...
}(module.exports));
// instead of
// } (this.mak = this.mak || {})); | unknown | |
d2708 | train | Loop through all recipients in the MailItem.Recipients collection. If you only need To recipients, check the Recipient.Type property - it ca be olTo, olCC, olBCC
for each recip in OutlookMail .Recipients
if recip.Type = olTo Then
MsgBox recip.Name & ": " & recip.Address
End If
next
As a sidenote, the condition If OutlookMail.ReceivedTime >= Range("From_date").Value will never be satisfied - you cannot use equality comparison for the datetime values, you only only use a range: (value < const1) and (value > const2) | unknown | |
d2709 | train | I hear and understand your rant, but this is bordering on being a SuperUser-type question and not a programming question (saved only by the fact you said you would like to implement this yourself).
From the description, it sounds like the Finder bailed when it couldn't copy one particular file (my guess is that it was looking for admin and/or root permission for some priviledged folder).
For massive copies like this, you can use the Terminal command line:
e.g.
cp
or
sudo cp
with options like "-R" (which continues copying even if errors are detected -- unless you're using "legacy" mode) or "-n" (don't copy if the file already exists at the destination). You can see all the possible options by typing in "man cp" at the Terminal command line.
If you really wanted to do this programatically, there are options in NSWorkspace (the performFileoperation:source:destination:files:tag: method (documentation linked for you, look at the NSWorkspaceCopyOperation constant). You can also do more low level stuff via "NSFileManager" and it's copyItemAtPath:toPath:error: method, but that's really getting to brute-force approaches there. | unknown | |
d2710 | train | You have a number of misconceptions here.
Firstly, the password is not hashed because you are not calling any method that hashes it. When you create a user, you must always call create_user, not create; it is the former that hashes the password.
user1 = User.objects.create_user(username='username', email='[email protected]', password='password')
Secondly, the reason user1_s is invalid is clearly explained in the error message: when you want to pass data into a serializer and get a User object out, you need to actually pass a dictionary of data in and not a User object.
So, as a test, this would work:
user1_serialize = UserModelSerializer(user1)
data = user1_serialize.data
user1_deserialize = UserModelSerializer(data=data)
user1_deserialize.is_valid() | unknown | |
d2711 | train | For each subplot, find the x/y/width/height. Then adjust the second (or both) to be the same height and the same "y"
get(gca,'position')
set(gca, 'position', [0.1300 0.15 0.3347 0.3412]) %x y width height, dummy numbers | unknown | |
d2712 | train | The short answer to your first question is YES.
MongoDB uses ObjectID to generate the unique identifier that is assigned to the _id field.
ObjectID is a 96-bit number
Use ObjectID as a unique identifier at mongodb site
Doing math with this, we could have 2^96 or 7.9228163e+28 unique id.
Secondly, the answer to your second question is YES too!
The scenario that comes here is when you had used all 2^96 unique ids that mongo gave you.
If you going to build a super big application that literary exceeds the limit. You could set the _id on your own. Mongo would notice you whether if _id set is duplicated. | unknown | |
d2713 | train | I found here that table from model django.contrib.sites.models.Site can be populate using
[
{
"model": "sites.site",
"pk": 1,
"fields": {
"domain": "myproject.mydomain.com",
"name": "My Project"
}
}
]
So model allauth.socialaccount.models.SocialApp probably can by populated by:
[
{
"model":"socialaccount.socialapp",
"pk":1,
"fields":{
"id":"1",
"provider":"facebook",
"name":"facebook",
"client_id":"0011223344556677",
"key":"",
"secret":"012345678901234567890123456"
}
}
]
A: Full fixture example, tested with django-allauth 0.19 and Django 1.8:
[
{
"model": "sites.site",
"pk": 1,
"fields": {
"domain": "localhost",
"name": "localhost"
}
},
{
"model":"socialaccount.socialapp",
"pk":1,
"fields":{
"id":"1",
"provider":"facebook",
"name":"facebook",
"client_id":"0011223344556677",
"secret":"012345678901234567890123456",
"key":""
}
},
{
"model":"socialaccount.socialapp_sites",
"pk":1,
"fields":{
"id":1,
"socialapp_id":1,
"site_id":1
}
}
] | unknown | |
d2714 | train | WireMock.NET does not currently support simulating HTTP/2 servers. This would require a change to the library to allow configuring the Protocol on the WireMockServer and a change to the internal ResponseMessage to better support stream bodies and trailing headers. | unknown | |
d2715 | train | The documentation has a section on null handling. An empty string is treated the same as null, and you cannot compare nulls (of any type) with equality - as the table in the documentation shows, the result of comparing anything with null is unknown - neither true nor false. You have to use is [not] null to compare anything with null.
In this case you could spell it out explicitly, by seeing is one variable is null and the other isn't, and vice versa, and only compare the actual values if that tells you neither are null:
DECLARE
v_notnull varchar2(30):='this string is never null';
v_input varchar2(30):='';
BEGIN
IF (trim(v_input) is null and trim(v_notnull) is not null)
or (trim(v_input) is not null and trim(v_notnull) is null)
or trim(v_input) != trim(v_notnull) THEN
dbms_output.put_line('the strings do NOT match');
ELSE
dbms_output.put_line('the strings DO match');
END IF;
END;
/
the strings do NOT match
PL/SQL procedure successfully completed.
I've added the missing varchar2 sizes; presumably you based this on a procedure that took arguments without running what you were posting stand-alone...
A: '' is NULL in oracle. So, any comparison with null will always result in false.
Demo:
SQL> DECLARE
2 v_notnull varchar2(1000):='this string is never null';
3 v_input varchar2(1000):='';
4 BEGIN
5 IF v_input is null THEN
6 dbms_output.put_line('v_input is null'); -- should print because v_input is actually null
7 END IF;
8
9 IF trim(v_input) = trim(v_notnull) THEN -- always false because of null
10 dbms_output.put_line('the strings do NOT match');
11 ELSE
12 dbms_output.put_line('the strings DO match'); -- so should print this
13 END IF;
14 END;
15 /
v_input is null -- verified
the strings DO match -- verified
PL/SQL procedure successfully completed.
SQL>
A: Often you only care whether the values match, in which case null values make no difference:
declare
v_notnull varchar2(50) := 'this string is never null';
v_input varchar2(50) := '';
begin
if trim(v_input) = trim(v_notnull) then
dbms_output.put_line('the strings DO match');
else
dbms_output.put_line('the strings do NOT match');
end if;
end;
In some cases you can simplify a comparison of nullable values using a coalesce() or nvl() expression:
if nvl(v_yesno,'N') <> 'Y' then ...
You might be able to use a dummy comparison value (although of course there is a risk that it will match an actual value, depending on the situation):
if nvl(somevalue, chr(0)) <> nvl(othervalue, chr(0)) then ...
By the way, you can distinguish between null and '' by copying the value to a char variable, as a '' will trigger its normally unhelpful blank-padding behaviour. I can't really think of a situation where this would be useful, but just for fun:
declare
v1 varchar2(1) := null;
v2 varchar2(1) := '';
c char(1);
begin
c := v1;
if v1 is null and c is not null then
dbms_output.put_line('v1 = ''''');
elsif c is null then
dbms_output.put_line('v1 is null');
end if;
c := v2;
if v2 is null and c is not null then
dbms_output.put_line('v2 = ''''');
elsif c is null then
dbms_output.put_line('v2 is null');
end if;
end;
Output:
v1 is null
v2 = '' | unknown | |
d2716 | train | This isn't a function, But a way to aggregate all scores at once.
Run through the dictionary and sum the values as you go.
final_dict = {}
for team, scores in qualifier_2.items():
final_dict[team] = 0 # initialize score to 0
for player, score in scores.items():
final_dict[team] += score # accumulate score as you loop
print(final_dict)
Outputs:
{'KKR': 117, 'MI': 117}
A: You call your function with the name of the dictionary
total_runs(qualifier_2,KKR)
Then you try to compare that to a string
if x == 'qualifier_2' and ........ :
Identity comparisons: If you really want/need to ensure that it is the specific dictionary, change it to
if x is qualifier_2 and y == 'KKR':
In a function, you want to use the name of the parameters used in the definition. Inside your function (inside the function's scope) the dictionary you passed as the first argument has been assigned to x and the key you passed as the second argument was assigned to y.
c = sum(x[y].values())
def total_runs(x,y):
if x is qualifier_2 and y == 'KKR':
c = sum(x[y].values())
return c
Your dictionary keys are strings so you need to paa a string for that argument
total_runs(qualifier_2,'KKR')
Functions are used to make a process more generic so that process can be reused with different arguments/values passed to it's parameters. While there may be some reasons to check for specific parameter values (maybe for debugging), usually it defeats the purpose of a function.
You could have written it like this:
def total_runs(x,y):
c = sum(x[y].values())
return c
or
def total_runs(x,y):
return sum(x[y].values())
A: You can use dict.values() to get a list of the numbers, then pass it through sum to get the total:
qualifier_2 = {'KKR' : {'Chris Lynn': 4,
'Sunil Narine': 10,
'Gautam Gambhir (c)': 12,
'Robin Uthappa (wk)': 1,
'Ishank Jaggi': 28,
'Colin Grandhomme': 0,
'Suryakumar Yadav': 31,
'Piyush Chawla': 2,
'Nathan Coulter-Nile': 6,
'Umesh Yadav': 2,
'Ankit Rajpoot': 4,
'Extra runs': 7,
'Total batted': 10},
'MI': {'Lendl Simmons': 3,
'Parthiv Patel (wk)': 14,
'Ambati Rayudu': 6,
'Rohit Sharma (c)': 26,
'Krunal Pandya': 45,
'Kieron Pollard': 9,
'Extra runs': 8,
'Total batted': 6}}
def total_runs(team):
# If team is not found in the data, return 0.
if team not in qualifier_2:
return 0
# Otherwise, find the team and return a sum of their values.
return sum(qualifier_2[team].values())
print total_runs("KKR") # Output: 117
print total_runs("MI") # Output: 117
You can even simplify it as a one liner, though it might be less readable:
def total_runs(team):
return sum((qualifier_2.get(team) or {}).values())
print total_runs("KKR") # Output: 117
print total_runs("MI") # Output: 117
print total_runs("FOOBAR") # Output: 0 | unknown | |
d2717 | train | MS Word can edit html document so by adding Content-Type=application/msword record in header will make browser open your page in browser unfortunately without css and images.
Add following code in prerender event on your page
Response.AddHeader("Content-Type", "application/msword"); | unknown | |
d2718 | train | You didn't pass the data in the Chart Object correctly. You can transform the object in php or js.
Example in js below.
const ctx = document.getElementById("myChart").getContext("2d");
const xValues = [
{ date: "2021-12-10" },
{ date: "2021-12-11" },
{ date: "2021-12-12" },
{ date: "2021-12-13" },
{ date: "2021-12-14" },
{ date: "2021-12-15" },
{ date: "2021-12-16" },
{ date: "2021-12-17" },
{ date: "2021-12-18" },
{ date: "2021-12-19" },
{ date: "2021-12-20" },
];
const yValues = [
{ attendance: "65" },
{ attendance: "58" },
{ attendance: "56" },
{ attendance: "78" },
{ attendance: "51" },
{ attendance: "54" },
{ attendance: "69" },
{ attendance: "35" },
{ attendance: "68" },
{ attendance: "43" },
{ attendance: "52" },
];
const x = xValues.map(item => item.date);
const y = yValues.map(item => item.attendance);
new Chart(ctx, {
type: "line",
data: {
labels: x,
datasets: [
{
label: "Dataset 1",
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: y,
},
],
},
options: {
responsive: true,
plugins: {
legend: {
position: "top",
},
title: {
display: true,
text: "Chart.js Line Chart",
},
},
},
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
EDIT
Full php example
<?php
$con = new mysqli($servername, $username, $password, $db);
$myquery1 = "select date from Table_attendance";
$result1 = mysqli_query($con, $myquery1);
$rowsDate = mysqli_fetch_all($result1, MYSQLI_ASSOC);
$xValues = array_map(function ($item) {
return $item['date'];
}, $rowsDate);
$myquery2 = "select attendance from Table_attendance";
$result2 = mysqli_query($con, $myquery2);
$rowsAtd = mysqli_fetch_all($result2, MYSQLI_ASSOC);
$yValues = array_map(function ($item) {
return $item['attendance'];
}, $rowsAtd);
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
const x = <?php echo json_encode($xValues) ?>;
const y = <?php echo json_encode($yValues) ?>;
new Chart(ctx, {
type: "line",
data: {
labels: x,
datasets: [{
label: "Dataset 1",
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: y,
}, ],
},
options: {
responsive: true,
plugins: {
legend: {
position: "top",
},
title: {
display: true,
text: "Chart.js Line Chart",
},
},
},
});
</script>
A: As mentioned in an answer the problem was in encoding. In fact the array that should be passed should be in the var xValues = [1,2,3,4,5,6] format. But what I got was in var xValues = [{1},{2},{3},{4},{5},{6}] format. Anyhow I will post my whole code if in case will be needed for someone in the future. Thank you very much for those who tried to help me.
The full code is as follows
$con = new mysqli($servername, $username, $password, $db);
// getting date column from Table_attendance table
$myquery1 = "select date from Table_attendance";
$query1 = mysqli_query($con, $myquery1);
if ( ! $query1 ) {
echo mysqli_error();
die;
}
$a1 ="";
for ($x = 0; $x < mysqli_num_rows($query1); $x++) {
$data1 = mysqli_fetch_assoc($query1);
if($a1 != ""){
$a1 = $a1.",'".$data1['date']."'";
}
else {
$a1 = "'".$data1['date']."'";
}
}
// getting attendance column from Table_attendance table
$my1 = "select attendance from Table_attendance";
$qu1 = mysqli_query($con, $my1);
if ( ! $qu1 ) {
echo mysqli_error();
die;
}
$a2 ="";
for ($x = 0; $x < mysqli_num_rows($qu1); $x++) {
$data2 = mysqli_fetch_assoc($qu1);
if($a2 != ""){
$a2 = $a2.",".$data2['attendance'];
}
else {
$a2 = $data2['attendance'];
}
}
?>
<?php //ploting the graph ?>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="myChart" style="width:100%;max-width:600px"></canvas>
<script>
var xValues = <?php echo '['.$a1.']'; ?>;
var yValues = <?php echo '['.$a2.']'; ?>;
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
fill: false,
lineTension: 0,
backgroundColor: "rgba(0,0,255,1.0)",
borderColor: "rgba(0,0,255,0.1)",
data: yValues
}]
},
options: {
title: {display: true, text: 'Total attendance'},
legend: {display: false},
scales: {
yAxes: [{ticks: {min: 10, max:100}}],
}
}
});
</script> | unknown | |
d2719 | train | There are different options to achieve what you need. You need to start with an identity template that would copy the input XML as is to output.
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>
Next you can declare separate templates for modifying country and company where the year != 1985.
<xsl:template match="cd[year != '1985']/country">
<country>MyCountry</country>
</xsl:template>
<xsl:template match="cd[year != '1985']/company">
<company>MyCompany</company>
</xsl:template>
Another option is to change the values of both elements in a single template cd whose child element year != 1985.
<xsl:template match="cd[year != '1985']">
<xsl:copy>
<xsl:apply-templates select="title | artist" />
<country>MyCountry</country>
<company>MyCompany</company>
<xsl:apply-templates select="price | year" />
</xsl:copy>
</xsl:template>
Hope this helps. However you need to go online and do some reading / hands on tutorials related to XSLT.
A: <xsl:template match="catalog">
<catalog>
<xsl:for-each select="cd">
<cd>
<title>
<xsl:value-of select="title"/>
</title>
<artist>
<xsl:value-of select="artist"/>
</artist>
<xsl:choose>
<xsl:when test="not(year = 1985)">
<country>MY Country</country>
<company>My Company</company>
</xsl:when>
<xsl:otherwise>
<country><xsl:value-of select="country"/></country>
<company><xsl:value-of select="company"/></company>
</xsl:otherwise>
</xsl:choose>
<price><xsl:value-of select="price"/></price>
<year><xsl:value-of select="year"/></year>
</cd>
</xsl:for-each>
</catalog>
</xsl:template>
Check it, I may be helful for you | unknown | |
d2720 | train | Is this what you want?
SELECT TOP (1) v.DoorNo,v.NewDoorNo, v.GarageName, c.VersionDate, v.OperatorName as Operator, v.OperatorId, c.DeviceId, c.VehicleId, c.ProgramVersionNo,
c.ParameterFileVersionNo, c.TariffFileVersionNo, c.BlaclistFileVersionNo, c.LineNoFileVersionNo, c.ScreenProgramVersion,
c.SoapProgramVersiyon
FROM dbo.vValidator AS v RIGHT JOIN
dbo.CDeviceVersion AS c with(nolock) ON (v.DoorNo = c.DoorNo
or v.NewDoorNo=c.DoorNo)
where v.NewDoorNo='O1211'
ORDER BY c.VersionDate | unknown | |
d2721 | train | if ($groupmembers.samaccountname -notmatch $users) {
Should be
if ($groupmembers.samaccountname -notmatch $user) {
Since you never define $users I think this is the error | unknown | |
d2722 | train | The newer Ninja Forms can use shortcode, so I just changed this:
<?php
if( function_exists( 'ninja_forms_display_form' ) ){ ninja_forms_display_form( 1 ); }
?>
to this:
<?php echo do_shortcode( '[ninja_form id=1]' ); ?>
(And as a public service advice.. just make sure that you don't have the bootstrap js pulled in twice, or the modal window won't stay displayed after you click the button. I found that the bootstrap shortcode plugin added another bootstrap.js) | unknown | |
d2723 | train | You can install the extension unaccent:
CREATE EXTENSION unaccent;
And then you are able to do:
SELECT * FROM person WHERE unaccent(name) ILIKE '%hasan%' ORDER BY name ASC | unknown | |
d2724 | train | The answer is inevitably compiler and target specific, but even if 1ULL is wider than a pointer on whatever target architecture, a good compiler should optimize it away. Which 2's complement integer operations can be used without zeroing high bits in the inputs, if only the low part of the result is wanted? explains why a wider computation truncated to pointer width will give identical results as doing computation with pointer width in the first place. This is why compilers can optimize it away even on 32bit machines (or x86-64 with the x32 ABI) when 1ULL leads to promotion of the + operands to a 64bit type. (Or on some 64bit ABI for some architecture where long long is 128b).
1ULL looks optimal for 64bit, and for 32bit with clang. You don't care about 32bit anyway, but gcc wastes an instruction in the return p[u + 1ULL];. All the other cases are compiled to a single load with scaled-index+4+p addressing mode. So other than one compiler's optimization failure, 1ULL looks fine for 32bit as well. (I think it's unlikely that it's a clang bug and that optimization is illegal).
int v1ULL(std::uint32_t u) { return p[u + 1ULL]; }
// ... load u from the stack
// add eax, 1
// mov eax, DWORD PTR p[0+eax*4]
instead of
mov eax, DWORD PTR p[4+eax*4]
Interestingly, gcc 5.3 doesn't make this mistake when targeting the x32 ABI (long mode with 32bit pointers and a register-call ABI similar to SySV AMD64). It uses a 32bit address-size prefix to avoid using the upper 32b of edi.
Annoyingly, it still uses an address-size prefix when it could save a byte of machine code by using a 64bit effective address (when there's no chance of overflow/carry into the upper32 generating an address outside the low 4GiB). Passing the pointer by reference is a good example:
int x2 (char *&c) { return *c; }
// mov eax, DWORD PTR [edi] ; upper32 of rax is zero
// movsx eax, BYTE PTR [eax] ; could be byte [rax], saving one byte of machine code
Err, actually I forget. 32bit addresses might sign-extend to 64b, not zero-extend. If that's the case, it could have used movsx for the first instruction, too, but that would have cost a byte because movsx has a longer opcode than mov.
Anyway, x32 is still an interesting choice for pointer-heavy code that wants more registers and a nicer ABI, without the cache-miss hit of 8B pointers.
The 64bit asm has to zero the upper32 of the register holding the parameter (with mov edi,edi), but that goes away when inlining. Looking at godbolt output for tiny functions is a valid way to test this.
If we want to make doubly sure that the compiler isn't shooting itself in the foot and zeroing the upper32 when it should know it's already zero, we could make test functions with an arg passed by reference.
int v1ULL(const std::uint32_t &u) { return p[u + 1ULL]; }
// mov eax, DWORD PTR [rdi]
// mov eax, DWORD PTR p[4+rax*4] | unknown | |
d2725 | train | The problem you're having with regards to classloaders is to be expected : if the dependencies of your Eclipse plugins/OSGi bundles are A -> B, with the Clojure jar bootstraped from B, then not being able to see resources of A from B is normal.
There can be no cycles among dependencies of Eclipse plugins, so there can be no cycles among classloader hierarchies.
This is the same problem that you would face if you were to write extensions to B from A with regular Eclipse machinery : plugin B would declare an interface, and an extension point. Then plugin A could implement the interface, and declare an extension to the extension point. This last part allows the Eclipse framework to do some tricks with the bundles: it sees that A declares an extension to B, thus instanciates a class from A implementing the interface declared in B (this works since A depends on B), and gives B the implementation instance from A which is also OK since it implements the interface in B !
(Not sure this is clear).
Anyway, back to plugins written in Clojure.
With Clojure, you don't have, out of the box, such separate environments provided by classloaders, because everything gets aggregated in one "Clojure environment" living in the classloader realm of the plugin embedding the clojure jar.
So one possibility would just be, when plugin A starts, to load the relevant namespaces from A. Then they would be loaded at the right time, and available to any other Clojure code.
Another possibility would be to use the Extension Point/Extension machinery. Eclipse provides a way to use "factories" to create instances of extension points. In Counterclockwise, we leverage this feature, and have a generic factory class (written in java, so no AOT) which takes care of loading the right namespace from the right bundle.
Here are more detail concerning how to extend extension points.
An example from Counterclockwise:
There is an existing Extension Point in the Eclipse framework for contributing hyperlink detectors for the Console contents. Counterclockwise extends this extension point to add nrepl hyperlinks.
In the java world, you would have to directly declare, in your extension, some class of yours which implements interface IPatternMatchListenerDelegate.
But with CCW, for probably the same reasons as you, I try to avoid AOT at all costs, so I can't give a java class name in the extension, or I would have either had to write it in java and compile it, or write a gen-class in Clojure and AOT-compile it.
Instead, CCW leverages a hidden gem of plugin.xml's possibilities: in almost every place, when you have to provide a class name, you can instead provide an instance of IExecutableExtensionFactory whose create() method will be called by the Eclipse framework to create an instance of the desired class.
This allowed me to write a generic class for calling into the Clojure world: I just use, in place of the class name I should have written, the class name ccw.util.GenericExecutableExtension
Extract from plugin.xml :
<extension point="org.eclipse.ui.console.consolePatternMatchListeners">
<consolePatternMatchListener
id="ccw.editors.clojure.nREPLHyperlink"
regex="nrepl://[^':',' ']+:\d+">
<class class="ccw.util.GenericExecutableExtension">
<parameter
name="factory"
value="ccw.editors.clojure.nrepl-hyperlink/factory">
</parameter>
</class>
</consolePatternMatchListener>
Note the class attribute, and how I can give parameters to the factory via the parameter element (the factory has to implement interface IExecutableExtension for being able to be initialized with the parameters).
Finally, you can see that in namespace ccw.editors.clojure.nrepl-hyperlink, the function factory is rather simple and just calls the make function:
(defn make []
(let [state (atom nil)]
(reify org.eclipse.ui.console.IPatternMatchListenerDelegate
(connect [this console] (dosync (reset! state console)))
(disconnect [this] (reset! state nil))
(matchFound [this event] (match-found event @state)))))
(defn factory "plugin.xml hook" [ _ ] (make))
Please note that I'm showing this as an example, and the relevant code in Counterclockwise is not ready to be released as an independant library "ready for consumption".
But you should nonetheless be able to roll your own solution (it's quite easy once you get all the pieces in place in your head).
Hope that helps,
--
Laurent
A: Another solution occured to me: it is possible, in Eclipse, despite what I said in my previous answer, to create cyclic dependencies between the classloaders!
Eclipse guys needed to introduce this so that certain types of libraries (log4j, etc.) could work in an OSGi environment (which is what Eclipse is based upon).
This requires to leverage the Eclipse-BuddyPolicy mechanism (Third Party libraries and classloading).
It's quite easy: if you want plugin B to see all classes and resources of plugin A, just add this to plugin B's META-INF/MANIFEST.MF file:
Eclipse-BuddyPolicy: dependent
The line above indicates that plugin B's classloader will be able to access what its dependents classloaders have access to.
I created a sample set of plugins named A and B where B has 2 commands (visible in the top menu) : the first applies a text transformation on the "hello" hard coded string by calling clojure code in B. The second dynamically loads an new text transformation from plugin A, so that when you invoke the first command again, you see the result of applying transformations from B and transformations from A.
In your case, it may not even be required to use Eclipse Extension Point / Extension mechanism at all, after all. It will all depend on how you intent plugin B to "discover" plugin A relevant information.
The github repository showing this in action: https://github.com/laurentpetit/stackoverflow-12689605
HTH,
--
Laurent | unknown | |
d2726 | train | use text watcher and Input Filter interface implemetation | unknown | |
d2727 | train | When you create a transaction through the GetTransaction method, the DataProvider just creates a new connection and gives you the transaction. You would then need to manually use that transaction to perform whatever action you're going to take against the database. There isn't a way to pass that transaction so that it gets used by, for example, CreatePortal, or any other built-in DNN function. That functionality appears to be just for any additional database access you might make.
In terms of how to wrap a call from the DNN core in a transaction, I don't think you can. The cleanest solution I know to recommend (which, unfortunately, still isn't very clean) is to manually call the stored procedure, using a transaction, rather than going through the controller class.
What's your use case, maybe I can recommend a solution that solves the problem some other way...
A: I was able to use Transactions in DNN with the help of this article.
It doesn't apply to your case, but will help others trying to leverage transactions in DNN. | unknown | |
d2728 | train | You can use jQuery's .ready() event on the document:
$(document).ready(function () {
// Whatever you want to run
});
This will run as soon as the DOM is ready.
If you need your javascript to run after everything is loaded (including images) than use the .load() event instead:
$(window).load(function () {
// Whatever you want to run
});
A: I'd suggest keeping your original click-handler, and triggering it with:
$(".Display a").click(function() {
$.ajax({
url: $(this).attr("href"),
success: function(msg){
$("#results").html(msg);
}
});
return false;
});
$(document).ready(
function(){
$('.Display a').trigger('click');
});
A: Have you tried just using the $.ajax() outside of the click event?
Instead of --
$(".Display a").click(function() {
$.ajax({
url: $(this).attr("href"),
success: function(msg){
$("#results").html(msg);
}
});
return false;
});
Try this --
$(document).ready(function () {
$.ajax({
url: $(this).attr("href"),
success: function(msg){
$("#results").html(msg);
}
});
});
A: $(function(){ //jQuery dom ready event
$(".Display a").click(function() {
///you code
}).click(); //trigger it at the page load
}); | unknown | |
d2729 | train | Try to use this way
string imagepath = "File:///" + "C:\\image.jpg";
this.reportViewer1.LocalReport.EnableExternalImages = true;
ReportParameter[] param = new ReportParameter[1];
param[0] = new ReportParameter("Path", imagepath);
this.reportViewer1.LocalReport.SetParameters(param);
this.reportViewer1.RefreshReport(); | unknown | |
d2730 | train | This is not a good idea, in general.
Splitting out your CSS and JavaScript files means that they can be cached independently. You will likely be using a common CSS and JavaScript across many pages. If you don't allow those to be cached, and instead store them in each page, then the user is effectively downloading a new copy of those files for every page they visit.
Now, it is a good idea to served minified versions of these files. Also make sure to add gzip or deflate transfer encoding so that they are compressed. Text compresses nicely... usually around a ratio of 1/8.
(I should note that there has been one occasion where I have loaded everything into a single file. I was working on a single-page web application for the Nintendo Wii, which had no caching capability at all. This is about the only instance where putting everything into a single file made sense. Even then, it is only worth the effort if you automate it server-side.)
A: I don't recommend to concat CSS with JS.
Just put your css at the top of the page and js at the bottom.
To minify your CSS and JS you have to use gruntjs
Also I recommend you to read this article: Front-end performance for web designers and front-end developers
A: If your intention is to load the pages faster:
*
*For images: try to use image sprites or images from different domains because browsers love downloading resources from different domains instead of just one domain.
*For scripts as well as css: use online minifiers that can reduce white-spaces and reduce the size (if you are on a web hosting, your host may be already compressing the scripts for you using gzip etc)
*For landing pages like index pages: If you have less styles then try inserting them inside the <style></style> tag, this will make the page load very fast, Facebook mobile does it that way.
A: If it wasn't a good idea, google wasn't be using it!
If you put everything in single file, you'll get less HTTP requests when the browser will check if the newer version of file is available.
You also get read of the problem that some resources are not refreshed, which is the headache for 'normal' developers, but it's a disaster in AJAX applications.
I don't know of any publicly available tool doing it all, surely Google is having its own. Note also that, for example in GWT, many such embedding was done by compiler.
What you can do is to search for:
CSS image embedder - for encoding images into CSS
CSS and JS minifier - for building single CSS/JS and minimizing it
And you need some simple tool that will embed it into HTML. | unknown | |
d2731 | train | The call to request is asynchronous.
Therefore, calling console.log(stations) in the line immediately after your call to request will print the empty list while your request continues to run in the background.
It prints too quickly - before the stations list has been populated.
Whatever you need to do with stations, you either need to do it in a success callback passed to request, or you need to await the request.
As Dai says above, push is actually mutating the stations array.
I am not sure what implementation of request you are using but it may return a value so you may be able to do something like const response = await request(...) (this could work in conjunction with fixing the error Dai pointed out - one way would be to move the declaration of stations inside the else clause, and then return stations at the end of the else clause).
If you can't await it, you will need to pass a callback that performs the pushes to stations defined as is. | unknown | |
d2732 | train | Here is my suggestion:
you can use an layout to replace the menu:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="52dp"
android:orientation="horizontal">
<FrameLayout
android:id="@+id/fl_page_home"
android:layout_width="wrap_content"
android:layout_height="57dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:background="your drawable"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="your text" />
</FrameLayout>
<FrameLayout
android:id="@+id/fl_page_dashboard"
android:layout_width="wrap_content"
android:layout_height="57dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:background="your drawable"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="your text" />
</FrameLayout>
<FrameLayout
android:id="@+id/fl_page_notification"
android:layout_width="wrap_content"
android:layout_height="57dp"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center_horizontal"
android:background="your drawable"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="32dp"
android:text="your text" />
</FrameLayout>
</LinearLayout>
and height is flexable and you can new a new xml to write this as bottom Navigation and then include to your LinearLayout.
In Java class you can implement onclick listener. | unknown | |
d2733 | train | The answer is :
await Client.json.get("key" , {path : '$.[1:3]'})
which gets index 1 to 3. | unknown | |
d2734 | train | Tabulator is a modular system, you could easily either modify the existing pagination module, or create your own from scratch.
There is a guide to Building Your Own Module along with several Example Modules to show how things work in practice.
If you want a good starting point for the pagination module then why not start with the source code for the existing pagination module, which you can find Here | unknown | |
d2735 | train | I think when the problem states "this behavior is undefined" it's just saying that they aren't going to test that condition because you can't reasonably be expected to do anything. It's not actually a task for you to complete - it's just telling you not to worry about those scenarios.
A: Why not write an "ImpossibleStateException" and throw this if the said case is true?
It's part of Java's design that you can write own exception classes, so why not write one and throw it when an undefined state is happening.
I'm not sure how the said state is ever produced, I could imagine if you talk about a kind of board game, maybe somebody fiddles around with the ram or the vm and tries to cheat / hack the game.
Also, if somebody would make a deep test of EVERY possible state of the program, like every variable with every possible value the game allows, there would be around 98% cases that made no sense at all.
A: From Oracle doc IllegalStateException:
Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.
So I think in your sitiation it is not good solution. | unknown | |
d2736 | train | Here's an approach with np.argpartition -
idx_row = np.argpartition(-a,2,axis=1)[:,:2]
out_row = np.zeros(a.shape,dtype=int)
out_row[np.arange(idx_row.shape[0])[:,None],idx_row] = 1
idx_col = np.argpartition(-a,2,axis=0)[:2]
out_col = np.zeros(a.shape,dtype=int)
out_col[idx_col,np.arange(idx_col.shape[1])] = 1
Sample input, output -
In [40]: a
Out[40]:
array([[ 3, 7, 1, -5, 14, 2, 8],
[ 5, 8, 1, 4, -3, 3, 10],
[11, 3, 5, 1, 9, 2, 5],
[ 6, 4, 12, 6, 1, 15, 4],
[ 8, 2, 0, 1, -2, 3, 5]])
In [41]: out_row
Out[41]:
array([[0, 0, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0, 1]])
In [42]: out_col
Out[42]:
array([[0, 1, 0, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 1, 0, 0],
[0, 0, 1, 1, 0, 1, 0],
[1, 0, 0, 0, 0, 0, 0]])
Alternatively, if you are into compact codes, we can skip the initialization and use broadcasting to get the outputs from idx_row and idx_col directly, like so -
out_row = (idx_row[...,None] == np.arange(a.shape[1])).any(1).astype(int)
out_col = (idx_col[...,None] == np.arange(a.shape[0])).any(0).astype(int).T | unknown | |
d2737 | train | Use source_location.
Returns the Ruby source filename and line number containing this method or nil if this method was not defined in Ruby (i.e. native)
$ cat monkey.rb
class String
def reverse
""
end
end
p String.instance_method(:reverse).source_location
$ ruby monkey.rb
["monkey.rb", 2]
A: puts String.instance_method(:to_json).source_location | unknown | |
d2738 | train | The garbage collector will not remove instances1 from an array list. That is not the problem.
The problem is most likely that you are accessing and updating the array list object without proper synchronization. If you do not synchronize properly, one thread won't always see the changes made by another one.
Declaring the reference to the ArrayList object only guarantees that the threads will see the same list object reference. It makes no guarantees about what happens with the operations on the list object.
1 - Assuming that the array list is reachable when the GC runs, then all elements that have been properly added to the list will also be reachable. Nothing that is reachable will be deleted by the garbage collector. Besides, the GC won't ever reach into an object that your application can still see and change ordinary references to null. | unknown | |
d2739 | train | The constant Int32.MaxValue is stored at compile time, and in fact your code would be converted to Convert.ToDouble(0x7FFFFFFF) at compile time. The equivalent IL is:
ldc.i4 FF FF FF 7F
call System.Convert.ToDouble
This value is also saved so it can be retrieved at run-time through reflection.
However, Convert.ToDouble is a function that is only evaluated at run-time.
As minitech suggests, (double)Int32.MaxValue is evaluated at compile-time. The equivalent IL is:
ldc.r8 00 00 C0 FF FF FF DF 41 | unknown | |
d2740 | train | Do you try with a jquery accordion? | unknown | |
d2741 | train | you can set it in useEffect like that but my suggestion is to use the directly redux players variable.
useEffect(() => {
setPlayerData(players);
}, [players]) | unknown | |
d2742 | train | Just place what you want to render in a variable, then use render :json => variable
There are sensible defaults for lists, dicts, etc...
See this:
http://guides.rubyonrails.org/layouts_and_rendering.html
Item: "2.2.8 Rendering JSON" | unknown | |
d2743 | train | Run following query to get all tablenames with specific column name
SELECT t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%COMPANY_ID%'
just use in forward only cursor with tablenames to update the specific table. | unknown | |
d2744 | train | Your supersonic ad sdk is causing the bug. The ad view connects to play services and does not disconnect properly. | unknown | |
d2745 | train | for the moment the only solution that is working right now is this from this similar question but two months ago:
!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}
%cd /content
!mkdir drive
%cd drive
!mkdir MyDrive
%cd ..
%cd ..
!google-drive-ocamlfuse /content/drive/MyDrive
Let's hope the normal way drive.mount will be fixed soon !
A: Here is the solution you can try:
As of new (messed up) update you can not mount using drive._mount anymore (or at least for now). So what you can do is either copy your folder/directory from your other google drive to your current google drive (the account you are log in to colab with) OR you can simply log out from colab and log in with your google account that has the drive you want to mount to
Remember
use drive.mount and not drive._mount after following the above guideline | unknown | |
d2746 | train | You can use the following:
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytes);
A: Don't get hung up on the fact that you retrieved the byte array from a WCF service. Once you have the result stored in a byte array, you're looking at the exact same technique for writing to disk as if you read it out of a database or off the file system. If you change you research from WCF to flat-out reading/writing bytes I think you'll have better luck. Here's one from SO that had some good suggestions:
C# - How do I read and write a binary file?
Edit: I somehow managed to miss that this was ASP.NET... sorry about that, you have to write to response and set content type to binary then, as other answers have provided examples for. | unknown | |
d2747 | train | Use something like this.
<View style={{ flex: 1 }}>
{renderStickyListHeaderComponent()}
<SectionList
{...sectionListprops}
ref={sectionListRef}
sections={sectionData}
stickySectionHeadersEnabled={false}
/>
</View>
A: To make the top or any other header sticky for section list, provide a custom scroll component:
const CustomScrollComponent = (props) => <ScrollView {...props} stickyHeaderHiddenOnScroll={true} stickyHeaderIndices={[0]} />
then in your section list:
<SectionList
// other props
renderScrollComponent={CustomScrollComponent}
/>
A: you can use renderSectionHeader & stickySectionHeadersEnabled = true
render() {
return (
<SectionList
data={sections}
renderSectionHeader = {({section:{title}}) => (<YourHeader>)}
stickySectionHeadersEnabled/>
)
} | unknown | |
d2748 | train | jOOQ 3.15 requires Java 11 (class file version 55) and you are using Java 8 (class file version 52) in your build. You either need to upgrade to Java 11, downgrade to jOOQ 3.14, or purchase a license for jOOQ 3.15 as all of the commercial editions still support Java 8. | unknown | |
d2749 | train | This is what I would do:
<div id="start">0</div>
<div class="post_content"></div>
$(window).data('ajaxready', true).scroll(function(e) {
var postHeight = $('#post_content').height();
if ($(window).data('ajaxready') == false) return;
var start = parseInt($('#start').text());
var limit = 30; // return 30 posts each
if ($(window).scrollTop() >= postHeight - $(window).height() - 400) {
var height = $(window).scrollTop();
$(window).data('ajaxready', false);
if (start > 0) {
var new_start = start + limit;
var dataString = {articles : start, limit : limit};
$.ajax({
cache: false,
url: 'extendost.php',
type: 'POST',
data: dataString,
success: function(data) {
if ($.trim(data).indexOf('NO POST') > -1) {
/* stop infinite scroll when no more data */
$('#start').text(0);
} else {
$('#post_content').append(data);
$('#start').text(new_start);
}
$(window).data('ajaxready', true);
}
});
}
}
});
This way your #start value will change as it scroll and ready for the next scroll value
Then base on the $start (offset) and $limit, make your query like
$query = "SELECT * FROM articles LIMIT {$limit} OFFSET {$start}";
if (!$result = mysqli_query($con, $query) {
echo 'NO POST';
} else {
// fetch and echo your result;
} | unknown | |
d2750 | train | For me, I just needed to return raw strings on that endpoint so I implemented my own HttpBehavior and DispatchFormatter as such:
public class WebHttpBehaviorEx : WebHttpBehavior
{
protected override IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
return new DynamicFormatter();
}
}
public class DynamicFormatter : IDispatchMessageFormatter
{
public void DeserializeRequest(Message message, object[] parameters)
{
throw new NotImplementedException();
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
return WebOperationContext.Current.CreateTextResponse((result ?? string.Empty).ToString());
}
}
and changed
ep.Behaviors.Add(new WebHttpBehavior()); | unknown | |
d2751 | train | The simplest way to do it is this:
sympy.pprint(sympy.sqrt(8))
For me (using rxvt-unicode and ipython) it gives
___
2⋅╲╱ 2
A: In an ipython notebook you can enable Sympy's graphical math typesetting with the init_printing function:
import sympy
sympy.init_printing(use_latex='mathjax')
After that, sympy will intercept the output of each cell and format it using math fonts and symbols. Try:
sympy.sqrt(8)
See also:
*
*Printing section in the Sympy Tutorial. | unknown | |
d2752 | train | Please try with this one.
$dailymotion = file_get_contents("https://api.dailymotion.com/video/xreczc?fields=title,duration,thumbnail_url,id,tags");
$results = json_decode($dailymotion, true);
print_r($results);
A: You are trying to fetch a https link via curl which has known issues. See the following links to see if they help your issue.
Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
Regards,
A: This code seems to fix it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.dailymotion.com/video/".$id."?fields=id,title,thumbnail_url,tags,duration,embed_url");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$results = curl_exec($ch);
curl_close($ch);
$results = json_decode($results);
if (!$results || $results->error->code) {
return false;
} else {
return $results;
} | unknown | |
d2753 | train | Try changing it to :
<string name="title_label"><![CDATA[<b>Title</b>]]> %s</string>
A: Dude, you have 3 opening and 2 closing square brackets there in your XML :)
Happens to the best of us :) | unknown | |
d2754 | train | I use log4net its simple to implement
https://www.nuget.org/packages/log4net/
in your webconfig you add this config you can refer to https://logging.apache.org/log4net/release/manual/configuration.html
<log4net debug="true">
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\log.txt" /> <- this is where your log file will be
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
inside your controller you declare a variable to use for logging
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
now anywhere inside that controller you can call this
logger.Info("blablabla") or logger.Error("boom boom") you should check documentation for more. | unknown | |
d2755 | train | You can match the trailing slash optionally by adding a ? next to it in the pattern :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?page=$1 [NC] | unknown | |
d2756 | train | If you use
from socket import *
then you have to use without socket.
gethostbyname(...)
gethostname()
socket(AF_INET, SOCK_STREAM)
If you use
import socket
then you have to use with socket.
socket.gethostbyname(...)
socket.gethostname()
socket.socket(AF_INET, SOCK_STREAM)
BTW: import * is not preferred - see PEP 8 -- Style Guide for Python Code | unknown | |
d2757 | train | KeyEvent can represent multiple actions, specifically both ACTION_DOWN and ACTION_UP. Since you aren't checking the action in your dispatchKeyEvent callback you are calling your button click methods for both DOWN and UP events on the volume buttons. Try like this:
public boolean dispatchKeyEvent(KeyEvent event){
int keyCode = event.getKeyCode();
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
onButtonUp();
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
onButtonDown();
return true;
default:
return super.dispatchKeyEvent(event);
}
}
} | unknown | |
d2758 | train | You can use AntBuilder for this:
class FooController {
def index = {
def ant = new AntBuilder()
ant.echo(message:"hi")
}
}
A: You can create a groovy script say DynaScript_.groovy that contains your Gant code and place this script file in the {grailsHome}/scripts folder.
And then you can invoke the script file from your controller like this:
class FooController {
def index = {
def process = "cmd /c grails dyna-script".execute()
def out = new StringBuilder()
process.waitForProcessOutput(out, new StringBuilder())
println "$out"
}
}
It's important that your script name ends with an underscore. | unknown | |
d2759 | train | You need the ControlValueAccessor for material-input in your directives list.
Better to use materialInputDirectives instead of MaterialInputComponent directly as it has the other directives you might want to use to interact with the value. | unknown | |
d2760 | train | Create new state to detect whether handle search is completed or not.
const [isHandleSearchComplete, markHandleSearchAsComplete] = useState(false);
const handleSearch = () => {
getOptions().then((res) => {
// do something here
markHandleSearchAsComplete(true)
})
}
const handleSelect = () => {
// if handle search is complete then stop the process
if (isHandleSearchComplete) {
return
}
// otherwise, do something
} | unknown | |
d2761 | train | from bs4 import BeautifulSoup as soup
html='''<tr><th class="th10" align="left" valign="top" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid"><nobr>Organism</nobr></th>
<td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid"><div style="width:555px;overflow-x:auto;overflow-y:hidden"><a href="/kegg-bin/show_organism?tax=1397">ag</a> Addendum (Bacillus circulans)<br>
</div></td></tr>'''
html=soup(html)
print(html.text)
A simple way that prints
Organism
ag Addendum (Bacillus circulans)
Then you can
print(html.text.split('(')[1].split(')')[0])
Which prints Bacillus circulans
A: You could do this using bs4 and regular expressions.
BeautifulSoup Part
from bs4 import BeautifulSoup
h = """
<tr><th class="th10" align="left" valign="top" style="border-color:#000;
border-width: 1px 0px 0px 1px; border-style: solid"><nobr>Organism</nobr>
</th>
<td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px;
border-style: solid"><div style="width:555px;overflow-x:auto;overflow-
y:hidden"><a href="/kegg-bin/show_organism?
tax=1397">ag</a> Addendum (Bacillus circulans)<br>
</div></td></tr>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
Your content lies inside a <div> tag.
tag = soup.find('div')
t = tag.text #'ag\xa0\xa0Addendum (Bacillus circulans)\n'
Regular Expression Part
import re
m = re.match(('(.*)\((.*)\).*', t)
ans = m.group(2) #Bacillus circulans
A: The usual preliminaries.
>>> import bs4
>>> soup = bs4.BeautifulSoup('''\
... <tr><th class="th10" align="left" valign="top" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid"><nobr>Organism</nobr></th><td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid"><div style="width:555px;overflow-x:auto;overflow-y:hidden"><a href="/kegg-bin/show_organism?tax=1397">ag</a> Addendum (Bacillus circulans)<br></div></td></tr>''', 'lxml')
Then I prettify the soup to see what I'm up against.
>>> for line in soup.prettify().split('\n'):
... print(line)
...
<html>
<body>
<tr>
<th align="left" class="th10" style="border-color:#000; border-width: 1px 0px 0px 1px; border-style: solid" valign="top">
<nobr>
Organism
</nobr>
</th>
<td class="td10" style="border-color:#000; border-width: 1px 1px 0px 1px; border-style: solid">
<div style="width:555px;overflow-x:auto;overflow-y:hidden">
<a href="/kegg-bin/show_organism?tax=1397">
ag
</a>
Addendum (Bacillus circulans)
<br/>
</div>
</td>
</tr>
</body>
</html>
I can see that the string you want is one of three items that constitute the contents of a div element. My first step is to identify that element, and I use its style attribute.
>>> parentDiv = soup.find('div', attrs={"style":"width:555px;overflow-x:auto;overflow-y:hidden"})
I examine the three items in its contents, and I'm reminded that strings don't have a name; it's None.
>>> for item in parentDiv.contents:
... item, item.name
...
(<a href="/kegg-bin/show_organism?tax=1397">ag</a>, 'a')
('\xa0\xa0Addendum (Bacillus circulans)', None)
(<br/>, 'br')
Then to isolate that string I can use:
>>> BC_string = [_ for _ in parentDiv.contents if not _.name]
>>> BC_string
['\xa0\xa0Addendum (Bacillus circulans)']
Edit: Given information from comment, this is how to handle one page. Find the heading for 'Organism' (in a nobr elment), then look for the div that contains the desired text relative to that element. Filter out the string(s) from other elements that are contents of that div, then use a regex to obtain the parenthesised name of the organism. If the regex fails then offer the whole string.
>>> import bs4
>>> import requests
>>> soup_2 = bs4.BeautifulSoup(requests.get('http://www.kegg.jp/entry/ag:CAA27061').content, 'lxml')
>>> organism = soup_2.find_all('nobr', string='Organism')
>>> parentDiv = organism[0].fetchParents()[0].fetchNextSiblings()[0].find_all('div')[0]
>>> desiredContent = [_.strip() for _ in parentDiv.contents if not _.name and _.strip()]
>>> if desiredContent:
... m = bs4.re.match('[^\(]*\(([^\)]+)', desiredContent[0])
... if m:
... name = m.groups()[0]
... else:
... name = "Couldn't match content of " + desiredContent
...
>>> name
'Bacillus circulans' | unknown | |
d2762 | train | The logic of that comparison absolutely breaks my brain and is a pain to read in the first place. Here's an adapted version that should work a bit better.
This solution iterates through the recieved messages and increments a counter for each gamemode depending on a switch-case expression. (bear in mind this doesn't stop a user from simply spamming whichever gamemode they want...)
Credit for the getAllIndexes function (used to determine ties)
const filter = m => (m.author.id != client.user.id);
const channel = message.channel;
const collector = channel.createMessageCollector(filter, { time: 5000 });
collector.on('collect', m => console.log(`Collected ${m.content}`));
collector.on('end', async collected => {
let msgs = Array.from(collected.keys()).map(m=>m?.content.toLowerCase().trim());
let modes = [ "Battle Box", "Parkour Warrior", "Spleef", "SkyWars", "Capture the Flag" ] // Define the names of the GameModes
let scores = [ 0, 0, 0, 0, 0 ] // Set up the default scores
msgs.forEach(m => {
switch(m) {
case "bb": // Fallthrough case for aliases
case "battlebox":
case "battle box":
scores[0]++; // Increment BattleBox (0) Counter
break;
case "pw":
case "parkour":
case "parkour warrior":
scores[1]++; // Increment ParkourWarrior (1) counter
break;
case "spleef":
scores[2]++; // Increment Spleef (2) counter
break;
case "sw":
case "sky":
case "skywars":
scores[3]++; // Increment SkyWars (3) counter
break;
case "ctf":
case "capture the flag":
scores[4]++; // Increment CaptureTheFlag (4) counter
break;
});
// Now to find who won...
let winningCount = Math.max(scores);
let winningIndexes = getAllIndexes(scores, winningCount);
if(winningIndexes.length = 1) { // Single Winner
message.channel.send(`And the winner is... ${modes[winningIndexes[0]]}!`);
} else { // tie!
message.channel.send(`It's a tie! There were ${winningIndexes.length} winners. (${winningIndexes.map(i=>modes[i]).join(", ")})`);
}
j});
// Get All Indexes function...
function getAllIndexes(arr, val) {
var indexes = [], i;
for(i = 0; i < arr.length; i++)
if (arr[i] === val) indexes.push(i);
return indexes;
} | unknown | |
d2763 | train | You can try something like this :
if (isset($_POST['search'])) {
$sql = 'SELECT * FROM properties';
$where = array();
$params = array();
if (!empty($_POST['location'])) {
$where[] = "location = :location";
$params[':location'] = $_POST['location'];
}
if (!empty($_POST['purpose'])) {
$where[] = "purpose = :purpose";
$params[':purpose'] = $_POST['purpose'];
}
if(count($where) > 0)
$sql .= ' WHERE ' . implode(' AND ', $where);
$stmt = $db->prepare($sql);
foreach($params as $param => $value) {
$stmt->bindParam($param, $value);
}
$stmt->execute();
$data = $stmt->fetchAll();
print_r($data);
} | unknown | |
d2764 | train | Promise.all(urls.map(url =>
fetch(url)
.then(this.checkStatus)
.then(this.parseJSON)
))
.then(jsons => {
var newState = {};
var index = 0;
for(var key in this.state)
newState[key] = jsons[index++];
this.setState(newState);
}) | unknown | |
d2765 | train | Possible solution is the following:
html = """<div class="productDescription" style="overflow: hidden;
display: block;">
Black Tshirt
<br>
<br>
REF.: V23T87C88EC
<br>
<br>
COMPOSIÇÃO:
<br>
90% Poliamida
</div>"""
import re
pattern = re.compile(r'REF\.: (.+?)$')
found = pattern.findall(html)
Returns ['V23T87C88EC']
REGEX DEMO
A: You can do this with a regex (read more about regex: https://docs.python.org/3/howto/regex.html) :
html = '''
<div class="productDescription" style="overflow: hidden; display: block;">
Black Tshirt
<br>
<br>
REF.: V23T87C88EC
<br>
<br>
COMPOSIÇÃO:
<br>
90% Poliamida
</div>
'''
import re
myref = re.search (r"(?<=REF.: )\w+", html)[0]
print(myref)
# V23T87C88EC | unknown | |
d2766 | train | There is a json file in my war in the following location
WEB-INF->classes->META-INF->jsonFolder->file.json
So its name as a resource is META-INF/jsonFolder/file.json. Not what you have in your code. | unknown | |
d2767 | train | If I understand correctly, something like:
select
Users.UserID,
TargetedPackages.UserID as TargetedID,
TargetedPackages.TimeStamp as TargetedTimestamp,
TargeterPackages.UserID as TargeterID,
TargeterPackages.Timestamp as TargetedTimestamp
from
Users
INNER JOIN Users as Targeted
on Targeted.TargetId = Users.TargetID
INNER JOIN Users as Targeter
on Targeter.TargetId = Users.UserID
LEFT JOIN Packages as TargetedPackages
on Users.TargetID = TargetedPackages.UserID AND TargetedPackages.Timestamp = (SELECT Max(Timestamp) FROM Packages where Packages.UserID = Users.TargetID)
LEFT JOIN Packages as TargeterPackages
on Targeter.UserID = TargeterPackages.UserID AND TargeterPackages.Timestamp = (SELECT Max(Timestamp) FROM Packages where Packages.UserID = Targeter.UserID)
where Users.UserID = 2 | unknown | |
d2768 | train | This also looks like it may be a viable option
http://willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/ | unknown | |
d2769 | train | Almost 5 years ago I posted this answer. It contains two pieces of code to pull out an asset from a Framework's bundle. The key piece of code is this:
public func returnFile(_ resource:String, _ fileName:String, _ fileType:String) -> String {
let identifier = "com.companyname.appname" // replace with framework bundle identifier
let fileBundle = Bundle.init(identifier: identifier)
let filePath = (fileBundle?.path(forResource: resource, ofType: "bundle"))! + "/" + fileName + "." + fileType
do {
return try String(contentsOfFile: filePath)
}
catch let error as NSError {
return error.description
}
So what if your framework, which needs to know two things (app bundle and light/dark mode) tweaked this code? Move identifier out to be accessible to the app and not local to this function. Then create either a new variable (I think this is the best way) or a new function to work with the correct set of assets based on light or dark mode.
Now your apps can import your framework, and set things up in it's consumers appropriately. (I haven't tried this, but in theory I think it should work.) | unknown | |
d2770 | train | In Silverlight you have only limited access to the file system for security reason.
So everything what you want to save would end up in IsolatedStorage...
Check out this Quickstart Video and let me know if it helps
http://www.silverlight.net/learn/quickstarts/isolatedstorage/
A: In Silverlight, You have limited access to the client file system. If you are running Out Of Browser application with elevated permission, you can access User folders (My documents in windows).
But you can try some workarounds like using JavaScript u can try to download file. For reference Download a picture OnClick | unknown | |
d2771 | train | Yes. Typical providers include most of the the big telecoms, plus some extra names that are specific to data transit: AT&T, Cogent, Comcast, Level3, NTT, Verizon...
Note that pricing on bandwidth gets weird for large users. Most web hosts pay on a burstable billing plan (typically 95th percentile with a minimum commit), rather than flat-rate or per byte. Some really large companies that run a lot of their own infrastructure (e.g, Google) pay nothing at all for peering. | unknown | |
d2772 | train | Issue was Maven couldn't find ssh binary path on the environment
Setting GIT_SSH environment variable worked.
export GIT_SSH=${SSH_BINARY_PATH}
In my case
export GIT_SSH=/usr/bin/ssh | unknown | |
d2773 | train | Here is a working code.
Please read the comments and let me know if something not clear.
// listen to the click event
var all_items = $('.category-list>li').click(function(event) {
// stop the propagation - this will abort the function when you click on the child li
event.stopPropagation();
var elm = $(this);
// remove the class from all the items
all_items.not(elm).removeClass('current');
// add class if it's not the current item
elm.toggleClass('current', !elm.is('.current'));
});
.category-list {
}
.category-list li ul {
display: none;
}
.category-list li.current > ul {
display: block;
}
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<ul class="category-list">
<li>
<a href="#" title="">Category 1</a>
<ul>
<li><a href="#" title="">Sub-category 1</a></li>
<li><a href="#" title="">Sub-category 1</a></li>
<li><a href="#" title="">Sub-category 1</a></li>
</ul>
</li>
<li>
<a href="#" title="">Category 2</a>
<ul>
<li><a href="#" title="">Sub-category 2</a></li>
<li><a href="#" title="">Sub-category 2</a></li>
<li><a href="#" title="">Sub-category 2</a></li>
</ul>
</li>
</ul>
http://jsbin.com/tocewe/edit?html,css,js | unknown | |
d2774 | train | You would need a trigger to tell redis that mysql data has been updated.
*
*This can be a part of your code, whenever you save data to mysql, you invalidate the redis cache as well.
*You can use streams like http://debezium.io/ to capture changes in the database, and take neccessary actions like invalidating cache. | unknown | |
d2775 | train | If you check closer, there are 3 versions of Android Studio installed: version 1.2, version 1.5 and version 3.0.
Among the 3 versions, it seems that the 2 older version were the one's getting those error. And for the record it was mentioned in the documentation that you only needed the latest version of Android Studio. It means that you only need one version of Android Studio.
Before trying this, make sure that you’re on the latest version of
Android Studio and the Flutter plugins.
Also, here is a bug that was filed for this issue as reference. | unknown | |
d2776 | train | How/why are you generating html yourself? I think an eaiser solution might be to make an ASP.NET Core 2 MVC app. That will allow you to use ViewModels. I'd take a look into that.
Anyways, try returning Content... this returns a Http Status code of 200, and will allow you to return a string with other details of how the content is formatted.
[HttpGet]
[Produces("text/html")]
public IActionResult Display()
{
return Content("<html><h1>hello world!</h1></html>", "text/html", Encoding.UTF8);
} | unknown | |
d2777 | train | cmd.CommandText = "YourStoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@No_Entered",i); //@No_Entered is parameter name in SP
Stored Procedure
CREATE PROCEDURE dbo.YourStoredProcedureName
@No_Entered int
AS
INSERT INTO TABLENAME (No_Entered) VALUES (@No_Entered)
GO
A: You have to create the stored procedure yourself. It doesn't magically exist on its own.
https://msdn.microsoft.com/en-us/library/ms187926.aspx | unknown | |
d2778 | train | if (state1){
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.layout_1, parent,false);
}else if (state2){
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.layout_2, parent,false);
}
return view;
A: Well I found the Solution.
The problem is that I check if ConverView parameter is NOT null then the adapter doesn't inflate new view and it uses the last one. If I delete this condition and make the adapter to always inflate a new layout the problem gets solved.
Like this:
public View getView(int position, View convertedView, ViewGroup parent) {
View view;
int resource = 0;
if (state1){
resource = R.layout.layout_1;
}else{
resource = R.layout.layout_2;
}
//if (convertedView == null) { //I should Delete this condition
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.layout_2, parent,false);
//}
return view; | unknown | |
d2779 | train | This should do the trick:
file1 = sc.textFile("/FileStore/tables/f1.txt").map(lambda line: line.split(",")).map(lambda x: (x[0], list(x[1:])))
file2 = sc.textFile("/FileStore/tables/f2.txt").map(lambda line: line.split(",")).map(lambda x: (x[0], list(x[1:])))
join_file = file1.join(file2)
join_file.collect()
returns with Unicode u':
Out[3]:
[(u'2', ([u'7', u'4'], [u'1', u'j'])),
(u'1', ([u'9', u'5'], [u'g', u'h'])),
(u'3', ([u'8', u'3'], [u'k', u'i']))] | unknown | |
d2780 | train | 1) Make sure you do not have a function overwriting the delete function
2) if you have a relation, and it is improper created and you are trying to delete a user.id that is related to another record then the delete might fail. (but that should also fail in phpmyadmin)
3) I for example have a soft delete, I just replace the user.status with "deleted". I cannot do that if my model is not validating, so I have to make a ->save(false) to get around that (I actually do not do that but you get my point). | unknown | |
d2781 | train | If you can work with WCF then yes the ASMX services are obsolete because the WCF can fully replace them with more performance and flexibility (multiple binding), functionality. If you can write a WCF service then if you will be requested to create an ASMX service for some reason there will be no problem for you to do it.
And moving from ASMX to ASHX was not a smart move because they are not for replacing each other.
A: Oddly we moved from ASMX to WCF and then back to ASMX. WCF has quite a few downsides, most of all is cross-platform compatibility issues. If everyone consuming your service is on .NET this isn't an issue, but not all other frameworks have supported the full stack, and frequently they just can't do what WCF produces. We also found that dealing with security and testing was a pain in WCF. If your webservice is marked secure, it has to be secure in WCF, even in your testing environment, which means getting actual SSL certs for each developer. A tremendous pain to be sure.
A: ASMX and WCF are technologies to build web services in .NET. WCF was introduced in .NET 3.0. Its goal is to provide a standard abstraction over all communication technologies and is a recommended way of implementing web services in .NET.
What are the differences between WCF and ASMX web services?
ASHX is a way to write HTTPHandlers in .NET. For more information on what are HTTPHandler
http://forums.asp.net/t/1166701.aspx/1
ASMX services are supported in .NET. However migrating to WCF is recommended. Also, you should write all new services in WCF.
A: Yes, asmx is obsolute with WCF service. you can use asmx when you are working with < 4.0 aspx.
ashx will not be exact replace of asmx.
If you have coding format issue / standard / plenty of code then you can go with MVC Web API 2 (4.0 itself). but compare to WCF you must ensure what will be the recipient's response expectation
("WCF is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ. but Web api only for HTTP(s)"). | unknown | |
d2782 | train | A1: No. You can't build an image off your host.
You can create an new image according to your requirement like which Operating Sytem (Ubuntu, Fedora), Stack(LAMP, LEMP) and many other things.
Or you can pull an image which will be pre-configured with all the packages like Wordpress Stack image, Magento stack image, Bitnami image which you can pull from docker-hub.
A2: As I have mentioned earlier you can build an image of any operating system you want(Ubuntu, Fedora, Debian) but not off the host.
You just need to pull image from docker-hub. e.g docker pull ubuntu will pull mininmal image of Ubuntu-14.04. And if you need specific version of Ubuntu
like Ubuntu-12.04 version e.g docker pull ubuntu:12.04 will pull minimal image of Ubuntu-12.04
A3: Docker-compose is a tool for defining and running multi-container docker applications. docker-compose conatins a compose file
in which you can configure your application services.
And finally Amazon EC2 Container Registry is little bit different thing. The Idea is the same as docker but Amazon is providing
this as a EC2 Container Service with many other functionality which docker doesn't have right now.
Hope it hepls:-) | unknown | |
d2783 | train | Your uploadFile() method will connect() to the server and then sendall() the file content (in 1024 byte chunks).
Your server, on the other hand, will receive the first 1024 bytes (i.e. the first 1024 bytes of file content), and interpret it according to the protocol, looking at the first three bytes of the file content. The client, however, never sends protocol.HEAD_UPLOAD as the server expects.
(BTW, I would really recommend you PEP8 the code, and refrain from * imports. It makes the code much easier to read, and thus to help.) | unknown | |
d2784 | train | If you think about how to explain the process. There are several methods to solve this including:
*
*You would start with each of the Projects and find out if there does not exist anybody who Works on the project where the Employees name starts with S. You can do this using NOT EXISTS.
or
*Again, start with a Project and find, if any, who Works on the project and their corresponding Employees details using LEFT OUTER JOINs (but starting from the Project) and filtering for employee names starting with S in the JOIN condition. Then GROUP BY the primary key for the project and find those projects HAVING a COUNT of zero matched employees.
Since this appears to be a homework question, I'll leave the rest for you to complete. | unknown | |
d2785 | train | Hello and welcome to Stack Overflow!
Since you are declaring class javatesting1 to be in a package test1, Java expects to find that class in a folder named like the package in order to scan it (using the wildcard).
I have tested your code, importing using wildcard *, with a folder structure like this
folder
*
*javatesting2.java
*test1
*
*javatesting1.java
Try editing your folder structure.
Also please try do adhere to coding conventions: class names should be named using CamelCase, e.g. JavaTesting1 | unknown | |
d2786 | train | This is not a issue related to react-native but related to your response.
You're getting something like '<' in response which cannot be converted to JSON. Try with response.text() | unknown | |
d2787 | train | To combine the best of both worlds, you could create an external styles file, as you would for CSS, but with exported style objects. You could then import it into any file that needs it.
As example, main file:
import React, { Component } from 'react';
import { render } from 'react-dom';
import * as Styles from './svgstyles';
class App extends Component {
render() {
return (
<div>
<svg width="100" height="200" viewBox="0 0 100 200">
<rect x="0" y="0" width="10" height="10" style={Styles.style1} />
<rect x="15" y="0" width="10" height="10" style={Styles.style2} />
<rect x="30" y="0" width="10" height="10" style={Styles.style3} />
<rect x="45" y="0" width="10" height="10" style={Styles.style4} />
<rect x="0" y="15" width="10" height="10" style={Styles.style4} />
<rect x="15" y="15" width="10" height="10" style={Styles.style3} />
<rect x="30" y="15" width="10" height="10" style={Styles.style2} />
<rect x="45" y="15" width="10" height="10" style={Styles.style1} />
</svg>
</div>
);
}
}
render(<App />, document.getElementById('root'));
And an external styles file:
export const style1 = {
stroke: 'red',
strokeWidth: "1",
fill: "blue",
}
export const style2 = {
stroke: 'red',
strokeWidth: "1",
fill: "green",
}
export const style3 = {
stroke: 'red',
strokeWidth: "1",
fill: "yellow",
}
export const style4 = {
...style3,
fill: "pink",
}
Live example here
A: If you just want to DRY up the code, you could create one style-object and reuse it:
const Close = ({
fill, width, height, float,
}) => {
const style = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 }
return (
<svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }>
<title>x</title>
<g id="Layer_2" data-name="Layer 2">
<g id="Background">
<line style={ style } x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
<line style={ style } x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
</g>
</g>
</svg>
);
}
This would also result in a small performance improvement since fewer objects would be created in each render cycle.
A: Actually, if I was in your place, Surely I use fonts instead of SVGs, but for your exact question, I prefer to use constant variables inside of my arrow function, just like below:
import React from 'react';
const Close = ({ fill, width, height, float }) => {
const constStyle = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 };
return (
<svg
width={`${width}px`}
height={`${height}px`}
viewBox="0 0 14.48 14.48"
style={{ float: `${float}`, cursor: 'pointer' }}
>
<title>x</title>
<g id="Layer_2" data-name="Layer 2">
<g id="Background">
<line style={constStyle} x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
<line style={constStyle} x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
</g>
</g>
</svg>
);
};
export default Close;
Even, I make the line dimension variables as props, but I don't know what is your case exactly.
Hope this answer helps you. | unknown | |
d2788 | train | You can use the REST API Query - Get to get the log data in the table.
GET https://api.loganalytics.io/v1/workspaces/{workspaceId}/query?query={query}
Then follow this doc to send events to the event hub programmatically, the specific situation and language depend on you.
https://learn.microsoft.com/en-us/azure/event-hubs/event-hubs-dotnet-standard-getstarted-send#send-events | unknown | |
d2789 | train | If the previous line is
$('#dform).validate({
then I guess the problems comes from the fact that validate should be passed options
From the doc ( http://docs.jquery.com/Plugins/Validation/validate ), assuming your code is part of the submitHandler, something like :
$(".selector").validate({
submitHandler: function(form) {
var std_address_copy = $('#dform').find('input[name=del_standard_use_b_as_s]').val();
....
}
})
Hope this will help | unknown | |
d2790 | train | There's already a working, packaged mechanism to handle relocations. It's called dlsym(). While it doesn't directly give you a function pointer, all major C++ compilers support reinterpret_casting the result of dlsym to any ordinary function pointer. (Member functions are another issue altogether, but that's not relevant here) | unknown | |
d2791 | train | Ok, I got it.
I inspected the framework data and noticed this md-selected-value prop, contained in MdTable component. After declaring the prop in my component:
props: [
// ...
'mdSelectedValue'
],
I update its value through a second array, delegated to track what elements are being selected for deletion:
data: () => ({
selezionato = []
})
then I listen for any change in selection:
<md-table v-model="cercato" @md-selected="onSelezionato" md-sort="codice" md-sort-order="asc" md-card md-fixed-header :md-selected-value="selezionato">
In my delete function, after every deletion I reset the the new selezionato value, in order to disable the alternate header:
this.selezionato = []
That's it. | unknown | |
d2792 | train | On modern browsers, you can use querySelectorAll and iterate over the NodeList directly, .remove()ing every iframe:
document.querySelectorAll('iframe')
.forEach(iframe => iframe.remove());
Or, for ES5 compatibility:
Array.prototype.forEach.call(
document.querySelectorAll('iframe'),
function(iframe) {
// can't use .remove: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
iframe.parentElement.removeChild(iframe);
}
);
A: A loop is the right way. Here's a simple version that will work cross-browser:
function myFunction() {
var elements = document.getElementsByTagName("iframe");
while (elements.length) {
elements[0].parentNode.removeChild(elements[0]);
}
}
That continually removes the last entry in the HTMLCollection. The HTMLCollection is live, so removing an element that's in that collection from the DOM also removes it from the collection, so that will reduce the length until eventually length is zero. | unknown | |
d2793 | train | Just create a new file for each record:
int counter = 0;
while (rs.next()) {
String DocumentName = rs.getString(2);
doc1 = DocumentName;
try {
File file = new File("///" + counter + ".txt"); // path to output folder.
FileWriter fileWritter = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fileWritter);
out.write(doc1);
out.newLine();
out.close();
counter++;
} catch (IOException e1) {
System.out.println("Could not write in the file");
}
}
Just create a counter variable or something to differentiate each file. Append the counter to the file name so it will create a new file for each record... | unknown | |
d2794 | train | You need to use strcmp for string comparison.
Replace
if(name == "yes")
With
if(strcmp(name,"yes") == 0)
strcmp returns
*
*
0 if both strings are identical (equal)
*
Negative value if the ASCII value of first unmatched character is less than second.
*
Positive value if the
ASCII value of first unmatched character is greater than second.
A: == isn't defined for string (or any other array) comparisons - you need to use the standard library function strcmp to compare strings:
if ( strcmp( name, "yes" ) == 0 )
or
if ( !strcmp( name, "yes") )
strcmp is a little non-intuitive in that it returns 0 if the string contents are equal, so the sense of the test will feel wrong. It will return a negative value if the first string is lexicographically less than the second, and a positive value if the first string is lexicographically greater than the second.
You'll need to #include <string.h> in order to use strcmp.
For comparing arrays that aren't strings, use memcmp. | unknown | |
d2795 | train | This is the solution:
Replace
const admin = require('firebase-admin/app');
with
const admin = require('firebase-admin');
You would use /app if you’re going to use modular approach | unknown | |
d2796 | train | Accessors are only called if you refer to a name on the class.
@strength = 0
This doesn't call an accessor. Ever. Even if one is defined.
self.strength = 0
This will call an accessor. Now, attr_accessor defines strength and strength=. If you're planning to write strength= yourself, then you want attr_reader, which does not define strength= for you.
class Weapon
attr_reader :strength
def initialize()
...
self.strength = 0
end
...
def strength=(value)
...
end
end
A: It might be easier to modify the getter:
class Weapon
attr_accessor :grip, :strength
# ...
def strength
if grip == 'straight'
@strength + 5
else
@strength
end
end
end
w = Weapon.new
w.strength = 10
w.strength
#=> 10
Since the getter always re-calculates the value, you can modify both, strength and grip and it will instantly reflect the change:
w.grip = 'straight'
w.strength
#=> 15
w.strength = 12
w.strength
#=> 17
w.grip = 'curved'
w.strength
#=> 12
To avoid confusion, you could call the initial strength base_strength. | unknown | |
d2797 | train | Is this what you want?
voters <- data.frame(party = c("R", "D", "R", "D", "R", "R", "R", "R", "R", "R", "R", "R", "R", "D", "R"),
vote = c("Y", "N", "Y", "N", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "Y", "N", "Y"))
ggplot(voters, aes(x = party, fill = vote)) + geom_bar()
You can't tell from this plot (because everyone voted based on party lines) but using the same code, if there were both "Yea" and "Nay" votes coming from the same party, you would get a stacked bar plot showing multiple colors. | unknown | |
d2798 | train | This is happenning because you are joining the fields inside data iterable using \t , use | in the join as well for your requirement. Example -
def write_to_txt(header,data):
with open('test.txt','a+') as f:
f.write("|{}|\n".format('|'.join(str(field)
for field in header))) # write header
f.write("|{}|\n".format('|'.join(str(field)
for field in data))) | unknown | |
d2799 | train | You can specify the href attribute for a like button.
For example, this like button would like the Facebook page for Facebook:
<div class="fb-like" data-href="http://facebook.com/facebook" data-send="true" data-width="450" data-show-faces="true"></div>
A: You should probably use the URL from the status ID. You can find this by right-clicking on the "... Hours ago" link on every Facebook status (gray color).
This will now be the same post_object. | unknown | |
d2800 | train | Borland Turbo C++ pre-dates most C++ standards and modern C. I would not expect FMOD or any modern library to work with this compiler.
Visual C++ is free to use in the Express form, and is a vastly better compiler.
A: The code you have listed is FMOD 3 code, yet you are using FMOD 4 headers (and probably libs too). This will not work, I can see from your error pic you have other troubles too, perhaps include paths not being set correctly.
We provide a Borland lib that you will need to link with: 'fmodex_bc.lib' but again this is FMOD 4 code, I would highly recommend looking at the 'playstream' example that ships with the SDK, it demonstrates MP3 playback. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.