This question has been asked before. Please see this question.
Using the accepted answer and adapting it to your problem you get:
SELECT tt.*
FROM myTable tt
INNER JOIN
(SELECT ID, MAX(Date) AS MaxDateTime
FROM myTable
GROUP BY ID) groupedtt
ON tt.ID = groupedtt.ID
AND tt.Date = groupedtt.MaxDateTime
A) Run gradle dependencies
or ./gradlew dependencies
B) Look at your tree and figure out which of your dependencies is specifying a different support library version for a dependency you don't control.
I didn't realize that this warning also displays if the dependency is completely unused directly by your own code. In my case, Facebook specifies some support libs I wasn't using, you can see below most of those dependencies were overridden by my own specification of 25.2.0, denoted by the -> X.X.X (*) symbols. The card view and custom tabs libs weren't overridden by anyone, so I need to ask for 25.2.0 for those ones myself even though I don't use them.
+--- com.facebook.android:facebook-android-sdk:4.17.0
| +--- com.android.support:support-v4:25.0.0 -> 25.2.0 (*)
| +--- com.android.support:appcompat-v7:25.0.0 -> 25.2.0 (*)
| +--- com.android.support:cardview-v7:25.0.0
| | \--- com.android.support:support-annotations:25.0.0 -> 25.2.0
| +--- com.android.support:customtabs:25.0.0
| | +--- com.android.support:support-compat:25.0.0 -> 25.2.0 (*)
| | \--- com.android.support:support-annotations:25.0.0 -> 25.2.0
| \--- com.parse.bolts:bolts-android:1.4.0 (*)
If gradle has already warned you and given you examples...
Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0
... it's even easier if you throw in some grep highlighting for the lower version since gradle dependencies
can be quite verbose:
./gradlew dependencies | grep --color -E 'com.android.support:mediarouter-v7|$'
The simple answer:
doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice
ADD 1 is probably faster than INC here
MOV 2 and DIV is very expensive; just shift right
64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code
If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.
The problem is that you have not included bootstrap.min.css
. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
You don't need the date
validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA
validator, which uses dd/mm/yyyy format as you need.
Just like the date
validator, your code for dateGreaterThan
and dateLessThan
calls new Date
for input string and has the same issue parsing dates. You can use a function like this to parse the date:
function parseDMY(value) {
var date = value.split("/");
var d = parseInt(date[0], 10),
m = parseInt(date[1], 10),
y = parseInt(date[2], 10);
return new Date(y, m - 1, d);
}
Give this a try. It basically calculates the number of days that has passed on DateTime.Now
, then subtracts one from that and uses the new value to find the first of the current month. From there it uses that DateTime
and uses .AddMonths(-1)
to get the first of the previous month.
Getting the last day of last month does basically the same thing except it adds one to number of days in the month and subtracts that value from DateTime.Now.AddDays
, giving you the last day of the previous month.
int NumberofDays = DateTime.Now.Day;
int FirstDay = NumberofDays - 1;
int LastDay = NumberofDays + 1;
DateTime FirstofThisMonth = DateTime.Now.AddDays(-FirstDay);
DateTime LastDayOfLastMonth = DateTime.Now.AddDays(-LastDay);
DateTime CheckLastMonth = FirstofThisMonth.AddMonths(-1);
The shortest version I found is to use the --cat
option of parallel
like below. This version avoids using xargs, only relying on features of parallel
:
cat files.txt | \
parallel -n 500 --lb --pipe --cat rsync --files-from={} user@remote:/dir /dir -avPi
#### Arg explainer
# -n 500 :: split input into chunks of 500 entries
#
# --cat :: create a tmp file referenced by {} containing the 500
# entry content for each process
#
# user@remote:/dir :: the root relative to which entries in files.txt are considered
#
# /dir :: local root relative to which files are copied
Sample content from files.txt
:
/dir/file-1
/dir/subdir/file-2
....
Note that this doesn't use -j 50
for job count, that didn't work on my end here. Instead I've used -n 500
for record count per job, calculated as a reasonable number given the total number of records.
I found that this problem happened to me and to a colleague after changing the name of our solution/project.
The issue resulting from my colleague: I pulled changes into my branch and had the error. In my bin folder I found the old .dll files sitting with the newly named .dll files. Deleted the old ones and the problem went away.
Closest I can get:
$(function(){_x000D_
$('span').width($('span').width()/2);_x000D_
$('span:nth-child(2)').css('text-indent', -$('span').width());_x000D_
});
_x000D_
body{_x000D_
font-family: arial;_x000D_
}_x000D_
span{_x000D_
display: inline-block;_x000D_
overflow: hidden;_x000D_
}_x000D_
span:nth-child(2){_x000D_
color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span>X</span><span>X</span>
_x000D_
Demo: http://jsfiddle.net/9wxfY/2/
Heres a version that just uses one span: http://jsfiddle.net/9wxfY/4/
My first suggestion would be use your calendar table, if you don't have one, then create one. They are very useful. Your query is then as simple as:
DECLARE @MinDate DATE = '20140101',
@MaxDate DATE = '20140106';
SELECT Date
FROM dbo.Calendar
WHERE Date >= @MinDate
AND Date < @MaxDate;
If you don't want to, or can't create a calendar table you can still do this on the fly without a recursive CTE:
DECLARE @MinDate DATE = '20140101',
@MaxDate DATE = '20140106';
SELECT TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b;
For further reading on this see:
With regard to then using this sequence of dates in a cursor, I would really recommend you find another way. There is usually a set based alternative that will perform much better.
So with your data:
date | it_cd | qty
24-04-14 | i-1 | 10
26-04-14 | i-1 | 20
To get the quantity on 28-04-2014 (which I gather is your requirement), you don't actually need any of the above, you can simply use:
SELECT TOP 1 date, it_cd, qty
FROM T
WHERE it_cd = 'i-1'
AND Date <= '20140428'
ORDER BY Date DESC;
If you don't want it for a particular item:
SELECT date, it_cd, qty
FROM ( SELECT date,
it_cd,
qty,
RowNumber = ROW_NUMBER() OVER(PARTITION BY ic_id
ORDER BY date DESC)
FROM T
WHERE Date <= '20140428'
) T
WHERE RowNumber = 1;
Below are some of the way by which you can create a link button in MVC.
@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
@Html.Action("Action", "Controller", new { area = "AreaName" })
@Url.Action("Action", "Controller", new { area = "AreaName" })
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a>
Hope this will help you.
In case you are appending Dtpicker,use the following code
$('#enddate').appendDtpicker({
"dateOnly": true,
"dateFormat": "YYYY-MM-DD",
"closeOnSelected": true,
maxDate: new Date()
});
HttpClient is the newer of the APIs and it has the benefits of
If you are writing a web service which is making REST calls to other web services, you should want to be using an async programming model for all your REST calls, so that you don't hit thread starvation. You probably also want to use the newest C# compiler which has async/await support.
Note: It isn't more performant AFAIK. It's probably somewhat similarly performant if you create a fair test.
If you using stisla
and use firemodal :
$('#modal-create-promo').click(()=>{
setTimeout(()=>{
$('#fire-modal-1').removeAttr('tabindex');
});
});
$("#modal-create-promo").fireModal({
...
});
It's work for me
In Microsoft ASP.net MVC, the routing engine, which is used to parse incoming and outgoing URL Combinations, is designed with the idea of Convention over Configuration. What this means is that if you follow the Convention (rules) that the routing engine uses, you don't have to change the Configuration.
The routing engine for ASP.net MVC does not serve web pages (.cshtml). It provides a way for a URL to be handled by a Class in your code, which can render text/html to the output stream, or parse and serve the .cshtml files in a consistent manner using Convention.
The Convention which is used for routing is to match a Controller to a Class with a name similar to ControllerNameController
i.e. controller="MyAccount"
means find class named MyAccountController
. Next comes the action, which is mapped to a function within the Controller Class, which usually returns an ActionResult
. i.e. action="LoginRegister"
will look for a function public ActionResult LoginRegister(){}
in the controller's class. This function may return a View()
which would be by Convention named LoginRegister.cshtml
and would be stored in the /Views/MyAccount/
folder.
To summarize, you would have the following code:
/Controllers/MyAccountController.cs:
public class MyAccountController : Controller
{
public ActionResult LoginRegister()
{
return View();
}
}
/Views/MyAccount/LoginRegister.cshtml: Your view file.
You can use following addon to handle all subquery related function from laravel 5.5+
https://github.com/maksimru/eloquent-subquery-magic
User::selectRaw('user_id,comments_by_user.total_count')->leftJoinSubquery(
//subquery
Comment::selectRaw('user_id,count(*) total_count')
->groupBy('user_id'),
//alias
'comments_by_user',
//closure for "on" statement
function ($join) {
$join->on('users.id', '=', 'comments_by_user.user_id');
}
)->get();
A pure bash solution:
shopt -s nullglob
dirs=( /path/to/directory/*/ )
echo "There are ${#dirs[@]} (non-hidden) directories"
If you also want to count the hidden directories:
shopt -s nullglob dotglob
dirs=( /path/to/directory/*/ )
echo "There are ${#dirs[@]} directories (including hidden ones)"
Note that this will also count links to directories. If you don't want that, it's a bit more difficult with this method.
Using find
:
find /path/to/directory -type d \! -name . -prune -exec printf x \; | wc -c
The trick is to output an x
to stdout each time a directory is found, and then use wc
to count the number of characters. This will count the number of all directories (including hidden ones), excluding links.
The methods presented here are all safe wrt to funny characters that can appear in file names (spaces, newlines, glob characters, etc.).
I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!
Error 0x8007000d means URL rewriting module (referenced in web.config) is missing or proper version is not installed.
Just install URL rewriting module via web platform installer.
I recommend to check all dependencies from web.config and install them.
img = new Image();
img.src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
img.outerHTML;
"<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">"
For from / to date, here is how I implemented restricting the dates based on the date entered in the other datepicker. Works pretty good:
function activateDatePickers() {
$("#aDateFrom").datepicker({
onClose: function() {
$("#aDateTo").datepicker(
"change",
{ minDate: new Date($('#aDateFrom').val()) }
);
}
});
$("#aDateTo").datepicker({
onClose: function() {
$("#aDateFrom").datepicker(
"change",
{ maxDate: new Date($('#aDateTo').val()) }
);
}
});
}
I'm posting a more declarative way of sync Base64 converting. While async fetch().blob()
is very neat and I like this solution a lot, it doesn't work on Internet Explorer 11 (and probably Edge - I haven't tested this one), even with the polyfill - take a look at my comment to Endless' post for more details.
const blobPdfFromBase64String = base64String => {
const byteArray = Uint8Array.from(
atob(base64String)
.split('')
.map(char => char.charCodeAt(0))
);
return new Blob([byteArray], { type: 'application/pdf' });
};
If you want to print it you could do something like:
const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // Or however you want to check it
const printPDF = blob => {
try {
isIE11
? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
: printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
} catch (e) {
throw PDFError;
}
};
If you're able to do some preprocessing of the Base64 string on the server you could expose it under some URL and use the link in printJS
:)
Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?
using xl = Microsoft.Office.Interop.Excel;
xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;
Simple as that!
HTH, Z
The problem is that if you try to write a <table>
or a <tr>
or <td>
tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.
Instead of writing your table line by line, concatenate your table into a variable and insert it once created:
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";
myTable+="<tr><td style='width: 100px; '>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td></tr>";
for (var i=0; i<8; i++) {
myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
myArray[i] = myArray[i].toFixed(3);
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);
//-->
</script>
If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:
<div id="tablePrint"> </div>
And in JS instead of document.write(myTable)
use the following code:
document.getElementById('tablePrint').innerHTML = myTable;
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php also can use properties with dashes:
garex@ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
Here is the example of a web.config that solve the issue for me. Pay attention on the <binding name="TransportSecurity" messageEncoding="Text" textEncoding="utf-8">
minDate property for current date works on for both -> minDate:"yy-mm-dd" or minDate:0
Somewhere the code--either your code or a jQuery plugin--is calling $.browser
to get the current browser type.
However, early has year the $.browser
function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.
I don't see any references to $.browser
in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script>
tag.
As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser
.
Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.
Check this : Using Large Message Requests in Silverlight with WCF
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="TestLargeWCF.Web.MyServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="customBinding0">
<binaryMessageEncoding />
<!-- Start change -->
<httpTransport maxReceivedMessageSize="2097152"
maxBufferSize="2097152"
maxBufferPoolSize="2097152"/>
<!-- Stop change -->
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
<endpoint address=""
binding="customBinding"
bindingConfiguration="customBinding0"
contract="TestLargeWCF.Web.MyService"/>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
You can set the year range using this option in jQuery UI datepicker:
yearRange: "c-100:c+0", // last hundred years and current years
yearRange: "c-100:c+100", // last hundred years and future hundred years
yearRange: "c-10:c+10", // last ten years and future ten years
You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;
05/12/2015
The columns in the result set of a select
query with group by
clause must be:
group by
criteria , or ...So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:
I want to find the individual claim row bearing the most recent creation date within each group in my claims table
Given
create table dbo.some_claims_table
(
claim_id int not null ,
group_id int not null ,
date_created datetime not null ,
constraint some_table_PK primary key ( claim_id ) ,
constraint some_table_AK01 unique ( group_id , claim_id ) ,
constraint some_Table_AK02 unique ( group_id , date_created ) ,
)
The first thing to do is identify the most recent creation date for each group:
select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select
query:
select *
from dbo.claims_table t
join ( select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
) x on x.group_id = t.group_id
and x.date_created = t.date_created
If the table is not unique by date_created
within group_id
(AK02), you you can get duplicate rows for a given group.
The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:
JS file:
$(".from_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var startDate = new Date(selected.date.valueOf());
$('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
$('.to_date').datepicker('setStartDate', null);
});
$(".to_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var endDate = new Date(selected.date.valueOf());
$('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
$('.from_date').datepicker('setEndDate', null);
});
HTML:
<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">
you can also covert int to str first and assign index to it then again convert it to int like this:
int(str(x)[n]) //where x is an integer value
Is the name of your service class really IService (on the Service namespace)? What you probably had originally was a mismatch in the name of the service class in the name
attribute of the <service>
element.
here is another solution...
System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];
System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
m.Write (buffer, 0, buffer.Length);
}
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();
hope it helps!
The problem is that the default option of "yearRange" is 10 years.
So 2012 - 10 = 2002
.
So change the yearRange to c-20:c
or just 1999 (yearRange: '1999:c'
), and use that in combination with restrict dates (mindate, maxdate).
For more info: http://jqueryui.com/demos/datepicker/#option-yearRange
See example: http://jsfiddle.net/kGjdL/
And your code with the addition:
$(function () {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true,
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
minDate: new Date(1999, 10 - 1, 25),
maxDate: '+30Y',
yearRange: '1999:c',
inline: true
});
});
try this:
select salesid,count (salesid) from AXDelNotesNoTracking group by salesid having count (salesid) >1
you can simply use
startDate: 'today'
it working fine for me.
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
cp -r ./SourceFolder ./DestFolder
download
attributeJust to allow user to download the image or other file you may use the HTML5 download
attribute.
Static file download
<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg">
Dynamic file download
In cases requesting image dynamically it is possible to emulate such download.
If your image is already loaded and you have the base64
source then:
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
}
Otherwise if image file is downloaded as Blob
you can use FileReader
to convert it to Base64:
function saveBlobAsFile(blob, fileName) {
var reader = new FileReader();
reader.onloadend = function () {
var base64 = reader.result ;
var link = document.createElement("a");
document.body.appendChild(link); // for Firefox
link.setAttribute("href", base64);
link.setAttribute("download", fileName);
link.click();
};
reader.readAsDataURL(blob);
}
Firefox
The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).
IE is not supported: Caniuse link
$(".datepicker").datepicker({maxDate: '0'});
This will set the maxDate to +0 days from the current date (i.e. today). See:
Just keep the following in mind.
In IIS if you have a folder for example called Pages with multiple websites in it. Website will inherit settings from the web.config file from the parent directory. So even if the folder page (in this example Pages) isn't a website but contains a web.config file, all websites listed inside of it will inherit the setting.
You can't download the file directly via ajax.
You can put a link on the page with the URL to your file (returned from the ajax call) or another way is to use a hidden iframe
and set the URL of the source of that iframe
dynamically. This way you can download the file without refreshing the page.
Here is the code
$.ajax({
url : "yourURL.php",
type : "GET",
success : function(data) {
$("#iframeID").attr('src', 'downloadFileURL');
}
});
An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files.
AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.
In my instance, the error was generated because one of my complex types had a property with no set method.
The serializer threw an exception because of that fact. Added internal set methods and it all worked fine.
Best way to find out why this is happening (in my opinion) is to enable trace logging.
I achieved this by adding the following section to my web.config
:
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
<add type="System.Diagnostics.DefaultTraceListener" name="Default" />
</listeners>
</source>
<source propagateActivity="true" name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
<add type="System.Diagnostics.DefaultTraceListener" name="Default" />
</listeners>
</source>
</sources>
<trace autoflush="true" />
</system.diagnostics>
Once set, I ran my client, got exception and checked the 'Traces.svclog' file. From there, I only needed to find the exception.
This worked for me in IE 11:
<meta http-equiv="x-ua-compatible" content="IE=edge; charset=UTF-8">
Just found that lines below must be added to web.config
file, now everything works fine on production server too.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
You can try jQuery treegrid (http://maxazan.github.io/jquery-treegrid/) or jQuery treetable (http://ludo.cubicphuse.nl/jquery-treetable/)
Both are using HTML <table>
tag format and styled the as tree.
The jQuery treetable is using data-tt-id
and data-tt-parent-id
for determining the parent and child of the tree. Usage example:
<table id="tree">
<tr data-tt-id="1">
<td>Parent</td>
</tr>
<tr data-tt-id="2" data-tt-parent-id="1">
<td>Child</td>
</tr>
</table>
$("#tree").treetable({ expandable: true });
Meanwhile, jQuery treegrid is using only class for styling the tree. Usage example:
<table class="tree">
<tr class="treegrid-1">
<td>Root node</td><td>Additional info</td>
</tr>
<tr class="treegrid-2 treegrid-parent-1">
<td>Node 1-1</td><td>Additional info</td>
</tr>
<tr class="treegrid-3 treegrid-parent-1">
<td>Node 1-2</td><td>Additional info</td>
</tr>
<tr class="treegrid-4 treegrid-parent-3">
<td>Node 1-2-1</td><td>Additional info</td>
</tr>
</table>
<script type="text/javascript">
$('.tree').treegrid();
</script>
For me, the settings in web.config
/ app.config
were ignored. I ended up creating my binding manually, which solved the issue for me:
var httpBinding = new BasicHttpBinding()
{
MaxBufferPoolSize = Int32.MaxValue,
MaxBufferSize = Int32.MaxValue,
MaxReceivedMessageSize = Int32.MaxValue,
ReaderQuotas = new XmlDictionaryReaderQuotas()
{
MaxArrayLength = 200000000,
MaxDepth = 32,
MaxStringContentLength = 200000000
}
};
Try browsing to http://localhost/ScraperService.svc in the web browser on the server hosting the service, using the same Windows credentials that the client normally runs under.
I imagine that IIS is displaying an html error message of some description instead of returning xml as expected.
This also can occur when you have an http proxy server that performs internet filtering. My experience with ContentKeeper is that it intercepts any http/https traffic and blocks it as "Unmanaged Content" - all we get back is an html error message. To avoid this, you can add proxy server exception rules to Internet Explorer so that the proxy doesn't intercept traffic to your site:
Control Panel > Internet Options > Connections > LAN Settings > Advanced > Proxy Settings
This is a simple example of what I used for a recent test. You need to make sure that your security settings are the same on the server and client.
var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.None;
var myEndpointAddress = new EndpointAddress("http://servername:8732/TestService/");
client = new ClientTest(myBinding, myEndpointAddress);
client.someCall();
Checkout the -maxdepth
flag of find
find . -maxdepth 1 -type d -exec ls -ld "{}" \;
Here I used 1 as max level depth, -type d
means find only directories, which then ls -ld
lists contents of, in long format.
This should answer:
How To: Configure MachineKey in ASP.NET 2.0 - Web Farm Deployment Considerations
Web Farm Deployment Considerations
If you deploy your application in a Web farm, you must ensure that the configuration files on each server share the same value for validationKey and decryptionKey, which are used for hashing and decryption respectively. This is required because you cannot guarantee which server will handle successive requests.
With manually generated key values, the settings should be similar to the following example.
<machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7 AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B" decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F" validation="SHA1" decryption="AES" />
If you want to isolate your application from other applications on the same server, place the in the Web.config file for each application on each server in the farm. Ensure that you use separate key values for each application, but duplicate each application's keys across all servers in the farm.
In short, to set up the machine key refer the following link: Setting Up a Machine Key - Orchard Documentation.
Setting Up the Machine Key Using IIS Manager
If you have access to the IIS management console for the server where Orchard is installed, it is the easiest way to set-up a machine key.
Start the management console and then select the web site. Open the machine key configuration:
The machine key control panel has the following settings:
Uncheck "Automatically generate at runtime" for both the validation key and the decryption key.
Click "Generate Keys" under "Actions" on the right side of the panel.
Click "Apply".
and add the following line to the web.config
file in all the webservers
under system.web
tag if it does not exist.
<machineKey
validationKey="21F0SAMPLEKEY9C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7
AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
decryptionKey="ABAASAMPLEKEY56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
validation="SHA1"
decryption="AES"
/>
Please make sure that you have a permanent backup of the machine keys and web.config
file
Note Slipstream's response, that base64.b64encode
and base64.b64decode
need bytes-like object, not string.
>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform...
quickie example:
ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );
Put the UNIQUE declaration within the column definition section; working example:
CREATE TABLE a (
i INT,
j INT,
UNIQUE(i, j) ON CONFLICT REPLACE
);
This issue was even more strange for us. Everything worked if you had previously visited the sharepoint site from the browser, before you made the SOAP call. However, if you did the SOAP call first we'd throw the above error.
We were able to resolve this issue by installing the sharepoint certificate on the client and adding the domain to the local intranet sites.
This line looks questionable:
page_output.innerHTML = str_output;
You can use .innerHTML
within jQuery, or you can use it without, but you have to address the selector semantically one way or the other:
$('#page_output').innerHTML /* for jQuery */
document.getElementByID('page_output').innerHTML /* for standard JS */
or better yet
$('#page_output').html(str_output);
Another case to use a multi line function would be to circumvent sql server from pushing down the where clause.
For example, I have a table with a table names and some table names are formatted like C05_2019 and C12_2018 and and all tables formatted that way have the same schema. I wanted to merge all that data into one table and parse out 05 and 12 to a CompNo column and 2018,2019 into a year column. However, there are other tables like ACA_StupidTable which I cannot extract CompNo and CompYr and would get a conversion error if I tried. So, my query was in two part, an inner query that returned only tables formatted like 'C_______' then the outer query did a sub-string and int conversion. ie Cast(Substring(2, 2) as int) as CompNo. All looks good except that sql server decided to put my Cast function before the results were filtered and so I get a mind scrambling conversion error. A multi statement table function may prevent that from happening, since it is basically a "new" table.
Assuming your sample data is correct, your givenname, and other entries wrapped in brackets are arrays in JS... you'll want to use List for those data types. and List for say accountstatusexpmaxdate... I think you example has the dates incorrectly formatted though, so uncertain as to what else is incorrect in your example.
This is an old post, but wanted to make note of the issues.
I experienced the same issue, and found out that the applicationdeployed was of .NET version 3.5, but the Application pool was using .NET 2.0. That caused the problem you described above. Hope it helps someone.
My error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid. Detailed Error Information
Module IIS Web Core
Notification BeginRequest
Handler Not yet determined
Error Code 0x80070021
Config Error This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".
Config File \\?\C:\inetpub\MyService\web.config
Requested URL http://localhost:80/MyService.svc
Physical Path C:\inetpub\DeployService\DeployService.svc
Logon Method Not yet determined
Logon User Not yet determined
Config Source
101: </modules>
102: <handlers>
103: <remove name="WebServiceHandlerFactory-Integrated"/>
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid. Detailed Error Information
Module IIS Web Core
Notification BeginRequest
Handler Not yet determined
Error Code 0x80070021
Config Error This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".
Config File \\?\C:\inetpub\DeployService\web.config
Requested URL http://localhost:80/DeployService.svc
Physical Path C:\inetpub\DeployService\DeployService.svc
Logon Method Not yet determined
Logon User Not yet determined
Config Source
101: </modules>
102: <handlers>
103: <remove name="WebServiceHandlerFactory-Integrated"/>`
This may or not be related....I started off with the same error mentioned above, started googling, making changes, getting new errors, endless loop.
The change that got me by that error was messing with the Feature Delegation in IIS Manager under the Management section of the server. I'm sorry I can't remember which one I changed, but googling might help.
That got me past the 1st error into a whole new stream of others, some totally nonsensical. (I would get one error when running under a virtual directory, converting it to an application yielded another error, etec etc). What finally solved this series of errors was: IIS manager, Application Pools, DefaultAppPool, Enable 32-Bit applications=True
I had started this app on a 32 bit windows xp box, and I am now running it on a 64Bit Windows 7 box.
So hopefully this helps someone else.
Give zero to mindate and it'll disabale past dates.
$( "#datepicker" ).datepicker({ minDate: 0});
The best way is to change any setting you want in your code.
Check out the below example:
using(WCFServiceClient client = new WCFServiceClient ())
{
client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}
Try with this:
catch (System.Reflection.TargetInvocationException e1)
String excType
excType = e1.InnerException.GetType().ToString()
choose case excType
case "System.ServiceModel.FaultException"
System.ServiceModel.FaultException e2
e2 = e1.InnerException
System.ServiceModel.Channels.MessageFault fault
fault = e2.CreateMessageFault()
ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + fault.Reason.ToString()
if (fault.HasDetail) then
System.Xml.XmlReader reader
reader = fault.GetReaderAtDetailContents()
ls_message += " " + reader.Value
do while reader.Read()
ls_message += reader.Value
loop
end if
case "System.Text.DecoderFallbackException"
System.Text.DecoderFallbackException e3
e3 = e1.InnerException
ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e3.Message
case else
ls_message = "Class: uo_bcfeWS, Method: registraUnilateral ~r~n" + "Exception(1): " + e1.Message
end choose
MessageBox ( "Error", ls_message )
//logError(ls_message)
return false
I had this error too , and finally this codes worked for me in dot net core 3.1
first install svcutil in command prompt : dotnet tool install --global dotnet-svcutil
Then close command prompt and open it again.
Then create the Reference.cs in command prompt :
dotnet-svcutil http://YourService.com/SayHello.svc
(It needs an enter key and UserName and Password)
Add a folder named Connected Services to project root.
Copy Reference.cs file to Connected Services folder.
Add these 4 lines to Reference.cs after lines where creating BasicHttpBinding and setting MaxBufferSize :
result.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
result.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
result.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
result.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
Use this service in your Controller :
public async Task<string> Get()
{
try
{
var client = new EstelamClient();
client.ClientCredentials.UserName.UserName = "YourUserName";
client.ClientCredentials.UserName.Password = "YourPassword";
var res = await client.EmployeeCheckAsync("service parameters");
return res.ToString();
}
catch (Exception ex)
{
return ex.Message + " ************ stack : " + ex.StackTrace;
}
}
Do not forget install these packages in .cshtml :
<PackageReference Include="System.ServiceModel.Duplex" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Http" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.NetTcp" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Security" Version="4.6.*" />
In my case, it was not working even after trying all solutions and setting all limits to max. In last I found out that a Microsoft IIS filtering module Url Scan 3.1 was installed on IIS/website, which have it's own limit to reject incoming requests based on content size and return "404 Not found page".
It's limit can be updated in %windir%\System32\inetsrv\urlscan\UrlScan.ini
file by setting MaxAllowedContentLength
to the required value.
For eg. following will allow upto 300 mb requests
MaxAllowedContentLength=314572800
Hope it will help someone!
I don't often develop in asp.net, however when it comes to loggers I think a lot of best practices are universal. Here are some of my random thoughts on logging that I have learned over the years:
</xxx>
tag, your log is broken.-- Invoking Class: com.foocorp.foopackage.FooClass:9021 SELECT * FROM foo;
This is my logging statement - Repeated 100 times
Also see this question of mine.
What about -mmin
?
find /var/www/html/audio -daystart -maxdepth 1 -mmin +59 -type f -name "*.mp3" \
-exec rm -f {} \;
From man find:
-mmin n File's data was last modified n minutes ago.
Also, make sure to test this first!
... -exec echo rm -f '{}' \; ^^^^ Add the 'echo' so you just see the commands that are going to get run instead of actual trying them first.
In my case i am setting security mode to "TransportCredentialOnly" instead of "Transport" in binding. Changing it resolved the issue
<bindings>
<webHttpBinding>
<binding name="webHttpSecure">
<security mode="Transport">
<transport clientCredentialType="Windows" ></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
Adding my two cents, based on a performance issue I observed.
If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.
In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP
) are mentioned as important settings to check.
Note: Paul White mentioned max server memory
aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server
Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP
.
Why is cost threshold for parallelism ignored?
Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.
Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan
Try setting your ScriptManager to this.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
npm install
now supports thisnpm install --save ../path/to/mymodule
For this to work mymodule
must be configured as a module with its own package.json
. See Creating NodeJS modules.
As of npm 2.0, local dependencies are supported natively. See danilopopeye's answer to a similar question. I've copied his response here as this question ranks very high in web search results.
This feature was implemented in the version 2.0.0 of npm. For example:
{ "name": "baz", "dependencies": { "bar": "file:../foo/bar" } }
Any of the following paths are also valid:
../foo/bar ~/foo/bar ./foo/bar /foo/bar
Since npm install
copies mymodule
into node_modules
, changes in mymodule
's source will not automatically be seen by the dependent project.
There are two ways to update the dependent project with
Update the version of mymodule
and then use npm update
: As you can see above, the package.json
"dependencies" entry does not include a version specifier as you would see for normal dependencies. Instead, for local dependencies, npm update
just tries to make sure the latest version is installed, as determined by mymodule
's package.json
. See chriskelly's answer to this specific problem.
Reinstall using npm install
. This will install whatever is at mymodule
's source path, even if it is older, or has an alternate branch checked out, whatever.
It is specifically mentioned in the documentation as part of Entity SQL. Are you getting an error message?
// LIKE and ESCAPE
// If an AdventureWorksEntities.Product contained a Name
// with the value 'Down_Tube', the following query would find that
// value.
Select value P.Name FROM AdventureWorksEntities.Product
as P where P.Name LIKE 'DownA_%' ESCAPE 'A'
// LIKE
Select value P.Name FROM AdventureWorksEntities.Product
as P where P.Name like 'BB%'
If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content"
. Have overflow hidden on this new inner-div, but keep overflow visible on the green box.
The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.
<div id="1" background: #efe; padding: 5px; width: 125px">
<div id="content" style="overflow: hidden;">
</div>
<div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
<div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
</div>
</div>
URL url = new URL("https://test.domain:443");
String keyStore = "server.p12"
String keyStorePassword = "changeit";
String keyPassword = "changeit";
String KeyStoreType= "PKCS12";
String KeyManagerAlgorithm = "SunX509";
String SSLVersion = "SSLv3";
public HttpURLConnection getHttpsURLConnection(URL url, String keystore,
String keyStorePass,String keyPassword, String KeyStoreType
,String KeyManagerAlgorithm, String SSLVersion)
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, FileNotFoundException, IOException,
UnrecoverableKeyException, KeyManagementException {
System.setProperty("javax.net.debug","ssl,handshake,record");
SSLContext sslcontext = SSLContext.getInstance(SSLVersion);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerAlgorithm);
KeyStore ks = KeyStore.getInstance(KeyStoreType);
ks.load(new FileInputStream(keystore), keyStorePass.toCharArray());
kmf.init(ks, keyPassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
sslcontext.init(kmf.getKeyManagers(), tm, null);
SSLSocketFactory sslSocketFactory = sslcontext.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
HttpsURLConnection httpsURLConnection = ( HttpsURLConnection)uRL.openConnection();
return httpsURLConnection;
}
[[ $(lsof -t $0| wc -l) > 1 ]] && echo "At least one of $0 is running"
currsh=$0
currpid=$$
runpid=$(lsof -t $currsh| paste -s -d " ")
if [[ $runpid == $currpid ]]
then
sleep 11111111111111111
else
echo -e "\nPID($runpid)($currpid) ::: At least one of \"$currsh\" is running !!!\n"
false
exit 1
fi
"lsof -t" to list all pids of current running scripts named "$0".
Command "lsof" will do two advantages.
The @ symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
int @int = 15;
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = @"c:\myFolder\myfile.txt"
Both works. Instead of ==
you can write eq
I just make with JQuery.
I tested in Firefox and IE10.
In my problem the items have different heights.
<!DOCTYPE html>
<html>
<head>
<style>
.item {
border: 1px solid #FF0;
width: 100px;
position: relative;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<script>
function itemClicked(e) {
if (navigator.appName == 'Microsoft Internet Explorer')
e.removeNode();
else
e.remove();
reposition();
}
function reposition() {
var px = 0;
var py = 0;
var margeY = 0;
var limitContainer = $('#divContainer').innerHeight();
var voltaY=false;
$('#divContainer .item').each(function(key, value){
var c = $(value);
if ((py+c.outerHeight()) > limitContainer) {
px+=100;
margeY-=py;
py=0;
voltaY=true;
}
c.animate({
left:px+'px',
top:margeY+'px'
});
voltaY=false;
py+=c.outerHeight();
});
}
function addItem() {
$('#divContainer').append('<div class="item" style="height: '+Math.floor(Math.random()*3+1)*20+'px;" onclick="itemClicked(this);"></div>');
reposition();
}
</script>
<div id="divMarge" style="height: 100px;"></div>
<div id="divContainer" style="height: 200px; border: 1px solid #F00;">
<!--div class="item"></div-->
</div>
<div style="border: 1px solid #00F;">
<input type="button" value="Add Item" onclick="addItem();" />
</div>
</body>
</html>
Tried to use the solution proposed by Misko, but in my situation, some attributes, which needed to be merged into my template html, were themselves directives.
Unfortunately, not all of the directives referenced by the resulting template did work correctly. I did not have enough time to dive into angular code and find out the root cause, but found a workaround, which could potentially be helpful.
The solution was to move the code, which creates the template html, from compile to a template function. Example based on code from above:
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
template: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
return htmlText;
}
compile: function(element, attrs)
{
//do whatever else is necessary
}
}
})
create a view for each subquery is the way to go. Got it working like a charm.
If you want an alert to appear after a certain about time, you can use this code:
setTimeout(function() { alert("my message"); }, time);
If you want an alert to appear and disappear after a specified interval has passed, then you're out of luck. When an alert
has fired, the browser stops processing the javascript code until the user clicks "ok". This happens again when a confirm
or prompt
is shown.
If you want the appear/disappear behavior, then I would recommend using something like jQueryUI's dialog widget. Here's a quick example on how you might use it to achieve that behavior.
var dialog = $(foo).dialog('open');
setTimeout(function() { dialog.dialog('close'); }, time);
For Mac , what worked for me is creating a .my.cnf file in my ~ path. Hope this helps.
Arrays are pretty flexible in JS, you can do:
var myArray = new Array();
myArray.push("string 1");
myArray.push("string 2");
h6 {
font: 14px sans-serif;
margin-top: 20px;
text-align: center;
text-transform: uppercase;
font-weight: 900;
}
h6.background {
position: relative;
z-index: 1;
margin-top: 0%;
width:85%;
margin-left:6%;
}
h6.background span {
background: #fff;
padding: 0 15px;
}
h6.background:before {
border-top: 2px solid #dfdfdf;
content: "";
margin: 0 auto; /* this centers the line to the full width specified */
position: absolute; /* positioning must be absolute here, and relative positioning must be applied to the parent */
top: 50%;
left: 0;
right: 0;
bottom: 0;
width: 95%;
z-index: -1;
}
this will help you
This generates a random integer of size psize
public static Integer getRandom(Integer pSize) {
if(pSize<=0) {
return null;
}
Double min_d = Math.pow(10, pSize.doubleValue()-1D);
Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
int min = min_d.intValue();
int max = max_d.intValue();
return RAND.nextInt(max-min) + min;
}
if you want to change only the colour of the flag on hover
use this:
.fa-flag:hover {_x000D_
color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
The marketing release number is for the customers, called version number. It starts with 1.0 and goes up for major updates to 2.0, 3.0, for minor updates to 1.1, 1.2 and for bug fixes to 1.0.1, 1.0.2 . This number is oriented about releases and new features.
The build number is mostly the internal number of builds that have been made until then. But some use other numbers like the branch number of the repository. This number should be unique to distinguish the different nearly the same builds.
As you can see, the build number is not necessary and it is up to you which build number you want to use. So if you update your Xcode
to a major version, the build field is empty. The version field may not be empty!.
To get the build number as a NSString
variable:
NSString * appBuildString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
To get the version number as a NSString
variable:
NSString * appVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
If you want both in one NSString
:
NSString * versionBuildString = [NSString stringWithFormat:@"Version: %@ (%@)", appVersionString, appBuildString];
This is tested with Xcode Version 4.6.3 (4H1503). The build number is often written in parenthesis / braces. The build number is in hexadecimal or decimal.
In Xcode you can auto-increment the build number as a decimal number by placing the following in the Run script
build phase in the project settings
#!/bin/bash
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
For hexadecimal build number use this script
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=$((0x$buildNumber))
buildNumber=$(($buildNumber + 1))
buildNumber=$(printf "%X" $buildNumber)
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
Try this :
var results= persons.GroupBy(n => n.PersonId)
.Select(g => new {
PersonId=g.Key,
Cars=g.Select(p=>p.car).ToList())}).ToList();
But performance-wise the following practice is better and more optimized in memory usage (when our array contains much more items like millions):
var carDic=new Dictionary<int,List<string>>();
for(int i=0;i<persons.length;i++)
{
var person=persons[i];
if(carDic.ContainsKey(person.PersonId))
{
carDic[person.PersonId].Add(person.car);
}
else
{
carDic[person.PersonId]=new List<string>(){person.car};
}
}
//returns the list of cars for PersonId 1
var carList=carDic[1];
For now i think best emulator is https://app.crossbrowsertesting.com
It has real sizes and virtual keyboard (that is the most important thing) , zooming events...
Also https://appetize.io/demo has same things but it has time limit.
You could also try explicitly specifying DNS server settings, this worked for me.
In Eclipse:
Window>Preferences>Android>Launch
Default emulator options: -dns-server 8.8.8.8,8.8.4.4
Here is a base R answer using aggregate
and ave
:
df1 <- with(mtcars, aggregate(list(n = mpg), list(am = am, gear = gear), length))
df1$prop <- with(df1, n/ave(n, am, FUN = sum))
#Also with prop.table
#df1$prop <- with(df1, ave(n, am, FUN = prop.table))
df1
# am gear n prop
#1 0 3 15 0.7894737
#2 0 4 4 0.2105263
#3 1 4 8 0.6153846
#4 1 5 5 0.3846154
We can also use prop.table
but the output displays differently.
prop.table(table(mtcars$am, mtcars$gear), 1)
# 3 4 5
# 0 0.7894737 0.2105263 0.0000000
# 1 0.0000000 0.6153846 0.3846154
If you are getting this error, it could be because you don't have a route defined for your get.
For example:
const express = require('express');
const app = express();
app.get('/people', function (req, res) {
res.send('hello');
})
app.listen(3000);
http://http://localhost:3000/people --> this works
http://http://localhost:3000 --> this will output Cannot GET / message.
I know the question is "a bit" outdated but as I came accross it somebody else may also do so in future... ...still I doubt the poor fellow will list down here to read my comment :)
It seems to me that we are still too confined to C-style way of thinking. In the OOP paradigma we play around with objects, not types. Const object may be conceptually different from a non-const object, specifically in the sense of logical-const (in contrast to bitwise-const). Thus even if const correctness of function params is (perhaps) an over-carefulness in case of PODs it is not so in case of objects. If a function works with a const object it should say so. Consider the following code snippet
#include <iostream>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class SharedBuffer {
private:
int fakeData;
int const & Get_(int i) const
{
std::cout << "Accessing buffer element" << std::endl;
return fakeData;
}
public:
int & operator[](int i)
{
Unique();
return const_cast<int &>(Get_(i));
}
int const & operator[](int i) const
{
return Get_(i);
}
void Unique()
{
std::cout << "Making buffer unique (expensive operation)" << std::endl;
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void NonConstF(SharedBuffer x)
{
x[0] = 1;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void ConstF(const SharedBuffer x)
{
int q = x[0];
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main()
{
SharedBuffer x;
NonConstF(x);
std::cout << std::endl;
ConstF(x);
return 0;
}
ps.: you may argue that (const) reference would be more appropriate here and gives you the same behaviour. Well, right. Just giving a different picture from what I could see elsewhere...
You'd need to use JavaScript to accomplish this, I think.
jQuery:
$(function(){
$("#innerContainer").hover(
function(){
$("#innerContainer").css('border-color','#FFF');
$("#outerContainer").css('border-color','#FFF');
},
function(){
$("#innerContainer").css('border-color','#000');
$("#outerContainer").css('border-color','#000');
}
);
});
Adjust the values and element id's accordingly :)
2 / 4 = 0 with a remainder of 2
This happened to me and I was baffled as to why. Then I noticed that if i removed any nbsp; i had within the rows, then the rows didn't take up any space.
To add to Box9's answer:
Backbone.js is dependent on underscore.js, which itself implements John Resig's original microtemplates.
If you decide to use Backbone.js with Rails, be sure to check out the Jammit gem. It provides a very clean way to manage asset packaging for templates. http://documentcloud.github.com/jammit/#jst
By default Jammit also uses JResig's microtemplates, but it also allows you to replace the templating engine.
You need to tell Eclipse which JDK/JRE's you have installed and where they are located.
This is somewhat burried in the Eclipse preferences: In the Window-Menu select "Preferences". In the Preferences Tree, open the Node "Java" and select "Installed JRE's". Then click on the "Add"-Button in the Panel and select "Standard VM", "Next" and for "JRE Home" click on the "Directory"-Button and select the top level folder of the JDK you want to add.
Its easier than the description may make it look.
c# From http://www.faqs.org/faqs/graphics/algorithms-faq/ -> Subject 1.02: How do I find the distance from a point to a line?
Boolean Contains(PointF from, PointF to, PointF pt, double epsilon)
{
double segmentLengthSqr = (to.X - from.X) * (to.X - from.X) + (to.Y - from.Y) * (to.Y - from.Y);
double r = ((pt.X - from.X) * (to.X - from.X) + (pt.Y - from.Y) * (to.Y - from.Y)) / segmentLengthSqr;
if(r<0 || r>1) return false;
double sl = ((from.Y - pt.Y) * (to.X - from.X) - (from.X - pt.X) * (to.Y - from.Y)) / System.Math.Sqrt(segmentLengthSqr);
return -epsilon <= sl && sl <= epsilon;
}
I did something like this in my project. I would like to share it here. You can add another div as a child and give it a border with small width and place it left, centre or right with usual CSS
HTML code:
<div>
content
<div class ="ac-brdr"></div>
</div>
CSS as below:
.active {
color: magneta;
}
.active .ac-brdr {
width: 20px;
margin: 0 auto;
border-bottom: 1px solid magneta;
}
To clear the whole thing use the reset_session method in a controller.
reset_session
Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668
Resets the session by clearing out all the objects stored within and initializing a new session object.
Good luck!
I came across the same issue as well. Not sure why this is working but it indeed works: Try add ENGINE INNODB after your create query.
mysql> create table course
-> (course_id varchar(7),
-> title varchar (50),
-> dept_name varchar(20),
-> credits numeric(2,0),
-> primary key(course_id),
-> foreign key (dept_name) references department) ENGINE INNODB;
Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.
For A Debian box with Apache and sudo:
Configure sudo:
As root, run the following to edit a new/dedicated configuration file for sudo:
visudo -f /etc/sudoers.d/Webserver
(or whatever you want to call your file in /etc/sudoers.d/
)
Add the following to the file:
www-data ALL = (root) NOPASSWD: <executable_file_path>
where <executable_file_path>
is the command that you need to be able to run as root with the full path in its name(say /bin/chown
for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.
For example, say we always want to copy the same file in the /root/ directory, we would write the following:
www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
Modify the script(testscript):
Edit your script such that sudo
appears before the command that requires root privileges(say sudo /bin/chown ...
or sudo /bin/cp /root/test1 /root/test2
). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file.
So, for our example above, we would have the following in the script:
sudo /bin/cp /root/test1 /root/test2
If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.
Keep in mind:
When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).
Thankfully, it's not possible to change the duration of the vibration. The only way to trigger the vibration is to play the kSystemSoundID_Vibrate
as you have. If you really want to though, what you can do is to repeat the vibration indefinitely, resulting in a pulsing vibration effect instead of a long continuous one. To do this, you need to register a callback function that will get called when the vibration sound that you play is complete:
AudioServicesAddSystemSoundCompletion (
kSystemSoundID_Vibrate,
NULL,
NULL,
MyAudioServicesSystemSoundCompletionProc,
NULL
);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Then you define your callback function to replay the vibrate sound again:
#pragma mark AudioService callback function prototypes
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
);
#pragma mark AudioService callback function implementation
// Callback that gets called after we finish buzzing, so we
// can buzz a second time.
void MyAudioServicesSystemSoundCompletionProc (
SystemSoundID ssID,
void *clientData
) {
if (iShouldKeepBuzzing) { // Your logic here...
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
} else {
//Unregister, so we don't get called again...
AudioServicesRemoveSystemSoundCompletion(kSystemSoundID_Vibrate);
}
}
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
I get this error because a field was varbinary in sqlserver table instead of varchar.
another method:
> ["a","b","c","","","f","g"].keep_if{|some| some.present?}
=> ["a","b","c","f","g"]
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
For Windows/WSL/Cygwin etc users:
Make sure that your line endings are standard Unix line feeds, i.e. \n
(LF) only.
Using Windows line endings \r\n
(CRLF) line endings will break the command line break.
This is because having \
at the end of a line with Windows line ending translates to
\
\r
\n
.
As Mark correctly explains above:
The line-continuation will fail if you have whitespace after the backslash and before the newline.
This includes not just space () or tabs (
\t
) but also the carriage return (\r
).
onDestroy()
is meant for final cleanup - freeing up resources that you can on your own,closing open connections,readers,writers,etc. If you don't override it, the system does what it has to.
on the other hand, finish()
just lets the system know that the programmer wants the current Activity
to be finished. And hence, it calls up onDestroy()
after that.
Something to note:
it isn't necessary that only a call to finish()
triggers a call to onDestroy()
. No. As we know, the android system is free to kill activities if it feels that there are resources needed by the current Activity
that are needed to be freed.
You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.
It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.
for Atom Users, Packages ->whitspace -> remove trailing whitespaces
this worked for me
int val1 = [textBox1.text integerValue];
int val2 = [textBox2.text integerValue];
int resultValue = val1 * val2;
textBox3.text = [NSString stringWithFormat: @"%d", resultValue];
The answer from @user3379466 can be made to work by setting $data
as follows:
$data = "{'some_key' : 'some_value'}";
What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):
$data = "{\"collection\" : [$existing_variable]}";
So with $existing_variable
being, say, 90210, you get:
echo $data;
//{"collection" : [90210]}
Also worth noting is that you might want to also set the 'Accept' => 'application/json'
as well in case the endpoint you're hitting cares about that kind of thing.
Once a DataTable
has been filled, you can't change the type of a column.
Your best option in this scenario is to add an Int32
column to the DataTable
before filling it:
dataTable = new DataTable("Contact");
dataColumn = new DataColumn("Id");
dataColumn.DataType = typeof(Int32);
dataTable.Columns.Add(dataColumn);
Then you can clone the data from your original table to the new table:
DataTable dataTableClone = dataTable.Clone();
Here's a post with more details.
Main class is configurable in pom.xml
<properties>
<start-class>com.bt.collab.alu.api.webapp.Application</start-class>
</properties>
And in case you need access to your WatchKit extension delegate from a view controller on watchOS:
extDelegate = WKExtension.sharedExtension().delegate as WKExtensionDelegate?
The correct way to display the alert is to simply return a string. Don't call the alert()
method yourself.
<script type="text/javascript">
$(window).on('beforeunload', function() {
if (iWantTo) {
return 'you are an idiot!';
}
});
</script>
See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
RewriteRule /(.+)(\.html)$ /$1 [R=301,L]
Try this :) don't know if it works.
The question "Why do we need to install gulp globally and locally?" can be broken down into the following two questions:
Why do I need to install gulp locally if I've already installed it globally?
Why do I need to install gulp globally if I've already installed it locally?
Several others have provided excellent answers to theses questions in isolation, but I thought it would be beneficial to consolidate the information in a unified answer.
Why do I need to install gulp locally if I've already installed it globally?
The rationale for installing gulp locally is comprised of several reasons:
Why do I need to install gulp globally if I've already installed it locally?
To avoid installing locally you can use npm link [package]
, but the link command as well as the install --global
command doesn't seem to support the --save-dev
option which means there doesn't appear to be an easy way to install gulp globally and then easily add whatever version that is to your local package.json file.
Ultimately, I believe it makes more sense to have the option of using global modules to avoid having to duplicate the installation of common tools across all your projects, especially in the case of development tools such as grunt, gulp, jshint, etc. Unfortunately it seems you end up fighting the tools a bit when you go against the grain.
App.getRes().getString(R.string.some_id)
I have read all the answers, all answers can make your work done.
getString(R.string.some_string_id)
in both Activity
or Fragment
.Context.getString(R.string.some_string_id)
where you don't have direct access to getString()
method. Like Dialog
.When you don't have Context
access, like a method in your Util
class.
Assume below method without Context.
public void someMethod(){
...
// can't use getResource() or getString() without Context.
}
Now you will pass Context
as a parameter in this method and use getString().
public void someMethod(Context context){
...
context.getString(R.string.some_id);
}
What i do is
public void someMethod(){
...
App.getAppResources().getString(R.string.some_id)
}
What? It is very simple to use anywhere in your app!
So here is a solution by which you can access resources from anywhere like Util class
.
import android.app.Application;
import android.content.res.Resources;
public class App extends Application {
private static Resources resources;
@Override
public void onCreate() {
super.onCreate();
resources = getResources();
}
public static Resources getAppResources() {
return resources;
}
}
Add name field to your manifest.xml
<application
tag.
<application
android:name=".App"
...
>
...
</application>
Now you are good to go. Use App.getAppResources().getString(R.string.some_id)
anywhere in app.
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
If you are using VS Code editor .
Go to Explorer panel on left side -> find package.json & open it -> under dependencies find @angular/core.
This is your angular version as core is the main feature
I just edited my iPhone's 'hosts' file successfully (on Jailbroken iOS 4.0).
simophone.local
]root
alpine
/etc/hosts
fileThe phone does cache some webpages and DNS queries, so a reboot or clearing the cache may help. Hope that helps someone.
Simon.
Here is an example of processing xpath with vtd-xml... for heavy duty XML processing it is second to none. here is the a recent paper on this subject Processing XML with Java – A Performance Benchmark
import com.ximpleware.*;
public class changeAttrVal {
public static void main(String s[]) throws VTDException,java.io.UnsupportedEncodingException,java.io.IOException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", false))
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
XMLModifier xm = new XMLModifier(vn);
ap.selectXPath("/*/place[@id=\"p14\" and @initialMarking=\"2\"]/@initialMarking");
int i=0;
while((i=ap.evalXPath())!=-1){
xm.updateToken(i+1, "499");// change initial marking from 2 to 499
}
xm.output("new.xml");
}
}
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
function x() {}
is equivalent (or very similar) to
var x = function() {}
unless I'm mistaken.
So there is nothing funny going on.
Similar to @Dominykas's answer, this is a decorator that converts multiargument-accepting functions into tuple-accepting functions:
apply_tuple = lambda f: lambda args: f(*args)
Example 1:
def add(a, b):
return a + b
three = apply_tuple(add)((1, 2))
Example 2:
@apply_tuple
def add(a, b):
return a + b
three = add((1, 2))
With a foreach:
let itemYouWant = null;
array.forEach((item) => {
if (item.name === 'string 1') {
itemYouWant = item;
}
});
console.log(itemYouWant);
To know about all methods use this statement in console:
javap -cp jar-file.jar packagename.classname
or
javap class-file.class packagename.classname
or for example:
javap java.lang.StringBuffer
The shortest way to write a selector that accesses that specific div is to simply use
[role=main] {
/* CSS goes here */
}
The previous answers are not wrong, but they rely on you using either a div or using the specific id. With this selector, you'll be able to have all kinds of crazy markup and it would still work and you avoid problems with specificity.
[role=main] {_x000D_
background: rgba(48, 96, 144, 0.2);_x000D_
}_x000D_
div,_x000D_
span {_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="content" role="main">_x000D_
<span role="main">Hello</span>_x000D_
</div>
_x000D_
Don't use: import UserController from "api/xxxx" Should be: import UserController from "./api/xxxx"
I would make two changes:
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
onclick
handler instead of onchange
- you're changing the "checked state" of the radio input, not the value
, so there's not a change event happening.this
as a parameter, that will make it easy to check which value is currently selected.ETA: Along with your handleClick()
function, you can track the original / old value of the radio in a page-scoped variable. That is:
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
var currentValue = 0;_x000D_
function handleClick(myRadio) {_x000D_
alert('Old value: ' + currentValue);_x000D_
alert('New value: ' + myRadio.value);_x000D_
currentValue = myRadio.value;_x000D_
}
_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />_x000D_
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
_x000D_
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
The reason why it is throwing the error is the object is disposed and after that we are trying to access the table values through the object, but object is disposed.Better to convert that into ToList() so that we can have values
Maybe it isn't actually getting the data until you use it (it is lazy loading), so dataContext doesn't exist when you are trying to do the work. I bet if you did the ToList() in scope it would be ok.
try
{
IQueryable<User> users;
var ret = null;
using (var dataContext = new dataContext())
{
users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
if(users.Any())
{
ret = users.Select(x => x.ToInfo()).ToList();
}
}
Return ret;
}
catch (Exception ex)
{
...
}
Remove key and then add again the modified key, value pair as shown below :
JSONObject js = new JSONObject();
js.put("name", "rai");
js.remove("name");
js.put("name", "abc");
I haven't used your example; but conceptually its same.
CSS {vertical-align: top;} or html Attribute {valign="top"}
.table td,
.table th {
border: 1px solid #161b21;
text-align: left;
padding: 8px;
width: 250px;
height: 100px;
/* style for table */
}
.table-body-text {
vertical-align: top;
}
_x000D_
<table class="table">
<tr>
<th valign="top">Title 1</th>
<th valign="top">Title 2</th>
</tr>
<tr>
<td class="table-body-text">text</td>
<td class="table-body-text">text</td>
</tr>
</table>
_x000D_
For table vertical-align we have 2 options.
I asume you have connected to your database already.
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
$col = 0;
foreach($row_data as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
There is no difference in terms of functionality
The addwithvalue
method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add
method requires that you specify the Database type first. This helps to reduce such errors.
For more detail Please click here
The file platforms/platforms.json
lists all of the platform versions.
I know this has already been answered, but I stumbled across this question and went down the path of using format
, which works, but it returns them as strings when I wanted integers.
I just realized that moment comes with date
, month
and year
methods that return the actual integers for each method.
moment().date()
moment().month() // jan=0, dec=11
moment().year()
All carousel
<script type="text/javascript">
$(document).ready(function () {
$('.carousel').carousel({
interval: 15000
})
});
</script>
In case anyone else is looking for this... as of April 2013, you can still get the free Visual Studio edition of Crystal Reports from this web site: SAP Crystal Reports - Downloads (updated url).
It installs into Visual Studio 2010 or VS 2012, and you can edit and save RPT files with as much capability as the standard Crystal Reports editor.
use this code to wait till the element is attached:
boolean breakIt = true;
while (true) {
breakIt = true;
try {
// write your code here
} catch (Exception e) {
if (e.getMessage().contains("element is not attached")) {
breakIt = false;
}
}
if (breakIt) {
break;
}
}
append()
& prepend()
are for inserting content inside an element (making the content its child) while after()
& before()
insert content outside an element (making the content its sibling).
The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):
body{
$colorStart: rgba(0,0,0,0);
$colorEnd: rgba(0,0,0,0.8);
@include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}
Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.
You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -
If I may offer some suggestions (two years later but hopefully helpful to future readers):
h2
element.ooooooooooooo
text.if/then/else
construct if using XSLT 2.0.<h2>
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">m</xsl:when>
<xsl:otherwise>d</xsl:otherwise>
</xsl:choose>
ooooooooooooo
</h2>
<h2>
<xsl:value-of select="if ($CreatedDate > $IDAppendedDate) then 'm' else 'd'"/>
ooooooooooooo
</h2>
Just adding some addition aspects. Need for setting seed: In the academic world, if one claims that his algorithm achieves, say 98.05% performance in one simulation, others need to be able to reproduce it.
?set.seed
Going through the help file of this function, these are some interesting facts:
(1) set.seed() returns NULL, invisible
(2) "Initially, there is no seed; a new one is created from the current time and the process ID when one is required. Hence different sessions will give different simulation results, by default. However, the seed might be restored from a previous session if a previously saved workspace is restored.", this is why you would want to call set.seed() with same integer values the next time you want a same sequence of random sequence.
Goto IntelliJ -> Preferences -> Plugin
Search for maven, you will see 1. Maven Integration 2. Maven Integration Extension.
Select the Maven Integration option and restart your Intellij
You may be interested in having a look at this page it list regular expressions for validating email address that cover more general cases.
C# 8 allows you to solve this problem elegantly and compactly using an switch expression:
public string GetTypeName(object obj)
{
return obj switch
{
int i => "Int32",
string s => "String",
{ } => "Unknown",
_ => throw new ArgumentNullException(nameof(obj))
};
}
As a result, you get:
Console.WriteLine(GetTypeName(obj: 1)); // Int32
Console.WriteLine(GetTypeName(obj: "string")); // String
Console.WriteLine(GetTypeName(obj: 1.2)); // Unknown
Console.WriteLine(GetTypeName(obj: null)); // System.ArgumentNullException
You can read more about the new feature here.
Django has method_decorator
which is a decorator that turns any decorator into a method decorator, you can see how it's implemented in django.utils.decorators
:
https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#decorating-the-class
Check the config file, the config path is /etc/php5/fpm/pool.d/www.conf
, there you'll find the path by config and if you want you can change it.
EDIT:
well you're correct, you need to replace listen = 127.0.0.1:9000
to listen = /var/run/php5-fpm/php5-fpm.sock
, then you need to run sudo service php5-fpm restart
, and make sure it says that it restarted correctly, if not then make sure that /var/run/
has a folder called php5-fpm
, or make it listen to /var/run/php5-fpm.sock
cause i don't think the folder inside /var/run
is created automatically, i remember i had to edit the start up script to create that folder, otherwise even if you mkdir /var/run/php5-fpm
after restart that folder will disappear and the service starting will fail.
this is pretty basic stuff, all you need to do is to create a base view model and make sure ALL! and i mean ALL! of your views that will ever use that layout will receive views that use that base model!
public class SomeViewModel : ViewModelBase
{
public bool ImNotEmpty = true;
}
public class EmptyViewModel : ViewModelBase
{
}
public abstract class ViewModelBase
{
}
in the _Layout.cshtml:
@model Models.ViewModelBase
<!DOCTYPE html>
<html>
and so on...
in the the Index (for example) method in the home controller:
public ActionResult Index()
{
var model = new SomeViewModel()
{
};
return View(model);
}
the Index.cshtml:
@model Models.SomeViewModel
@{
ViewBag.Title = "Title";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
i disagree that passing a model to the _layout is an error, some user info can be passed and the data can be populate in the controllers inheritance chain so only one implementation is needed.
obviously for more advanced purpose you should consider creating custom static contaxt using injection and include that model namespace in the _Layout.cshtml.
but for basic users this will do the trick
The float value is stored in IEEE 754 format so we can't convert it directly like integer, char to binary.
But we can convert float to binary through a pointer.
#include <stdio.h>
int main()
{
float a = 7.5;
int i;
int * p;
p = &a;
for (i = sizeof(int) * 8 - 1; i >= 0; i--)
{
printf("%d", (*p) >> i & 1);
}
return 0;
}
Output
0 10000001 11100000000000000000000
Spaces added for clarification, they are not included as part of the program.
Use textView.text
for getter and setter, ex:
val textView = findViewById<TextView>(R.id.textView)
// Set text
textView.text = "Hello World!"
// Get text
val textViewString = textView.text.toString()
Check out the sortBy
method for Eloquent: http://laravel.com/docs/eloquent
Here are the rules for how these functions work:
stringValue.CompareTo(otherStringValue)
null
comes before a stringCultureInfo.CurrentCulture.CompareInfo.Compare
, which means it will use a culture-dependent comparison. This might mean that ß
will compare equal to SS
in Germany, or similarstringValue.Equals(otherStringValue)
null
is not considered equal to anythingStringComparison
option, it will use what looks like a direct ordinal equality check, i.e. ß
is not the same as SS
, in any language or culturestringValue == otherStringValue
stringValue.Equals()
.==
operator calls the static Equals(string a, string b)
method (which in turn goes to an internal EqualsHelper
to do the comparison..Equals()
on a null
string gets null
reference exception, while on ==
does not.Object.ReferenceEquals(stringValue, otherStringValue)
Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.
Note that with the options above that use method calls, there are overloads with more options to specify how to compare.
My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo
or .Equals
, depending on the choice.
I like the following approach as it works for all situations:
$(':focus').blur();
There's a method that does this for you:
def show
@city = @user.city.present?
end
The present?
method tests for not-nil
plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.
Since this pattern is so common there's even a shortcut in ActiveRecord:
def show
@city = @user.city?
end
This is roughly equivalent.
As a note, testing vs nil
is almost always redundant. There are only two logically false values in Ruby: nil
and false
. Unless it's possible for a variable to be literal false
, this would be sufficient:
if (variable)
# ...
end
This is preferable to the usual if (!variable.nil?)
or if (variable != nil)
stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.
One reason you'd want to compare vs. nil
is if you have a tri-state variable that can be true
, false
or nil
and you need to distinguish between the last two states.
When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”
For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging
In another way,
If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”
There won't be any "merge commit" in fast-forwarding merge.
ZoomLib Link: https://drive.google.com/uc?export=download&id=0B34PUThnUsjVaHpkaGk0Z1hSRU0
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy_layout_for_zooming);// Activity layout
mZoomLinearLayout = (LinearLayout) findViewById(R.id.mZoomLinearLayout);// LinearLayout inside Activity layout
View v = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_for_zoom, null, false);// View wants to zoom
v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
ZoomView zoomView = new ZoomView(this);// intialize lib
zoomView.addView(v);
mZoomLinearLayout.addView(zoomView);
}
This problem is because of the fact that eclipse is not able to find Java ,
Check the java directory cd /Library/Java/JavaVirtualMachines///Contents/Home/jre/bin
If thats not present down JDK from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Once JDK is installed change eclipse.ini file
On Mac: Right click on Eclipse icon and click "Show package Content"
Navigate to eclipse>Contents>Eclipse>eclipse.ini
Open the file and replace the java path after "-vm" with this
/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
In my case error is because i have put ">>" twice
mongodump --db=$DB_NAME --collection=$col --out=$BACKUP_LOCATION/$DB_NAME-$BACKUP_DATE >> >> $LOG_PATH
i just correct it as
mongodump --db=$DB_NAME --collection=$col --out=$BACKUP_LOCATION/$DB_NAME-$BACKUP_DATE >> $LOG_PATH
If the underlying goal is "How can I start a container when Docker starts?"
We can use Docker's restart policy
To add a restart policy to an existing container:
Docker: Add a restart policy to a container that was already created
Example:
docker update --restart=always <container>
Try the following:
List<Map<String, ArrayList<String>>> mapList =
new ArrayList<Map<String, ArrayList<String>>>();
mapList.add(map);
If your list must be of type List<HashMap<String, ArrayList<String>>>
, then declare your map
variable as a HashMap
and not a Map
.
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
In addition, ModelState.Values.ErrorMessage
may be empty, but ModelState.Values.Exception.Message
may indicate an error.
This is what i did for rendering html files. And it solved the errors. Install consolidate and mustache by executing the below command in your project folder.
$ sudo npm install consolidate mustache --save
And make the following changes to your app.js file
var engine = require('consolidate');
app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');
And now html pages will be rendered properly.
I believe you are looking for -maxdepth 1
.
Why do you need to attach it to the HTML? Just bind the function with hover
$("div.system_box").hover(function(){ mousin },
function() { mouseout });
If you do insist to have JS references inside the html, which is usualy a bad idea you can use:
onmouseover="yourJavaScriptCode()"
<div class="system_box" data-target="sms_box">
...
$("div.system_box").click(function(){ slideonlyone($(this).attr("data-target")); });
__construct
was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor).
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.
An example could go like this:
class Database {
protected $userName;
protected $password;
protected $dbName;
public function __construct ( $UserName, $Password, $DbName ) {
$this->userName = $UserName;
$this->password = $Password;
$this->dbName = $DbName;
}
}
// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );
Everything else is explained in the PHP manual: click here
Try using the property ForeColor. Like this :
TextBox1.ForeColor = Color.Red;
I think you can sort both lists and convert to List if some of them was a HashSet colleciton.
java.utils.Collections package lets you do it.
List<Category> categoriesList = new ArrayList<>();
Set<Category> setList = new HashSet<>();
Collections.sort(categoriesList);
List<Category> fileCategories = new ArrayList<>(setList);
Collections.sort(fileCategories);
if(categoriesList.size() == fileCategories.size() && categoriesList.containsAll(fileCategories)) {
//Do something
}
There is no need to use substr
method to get a single char of a string!
taking the example of Jamon Holmgren we can change substr method and simply specify the array position:
var id = "ctl03_Tabs1";
var lastChar = id[id.length - 1]; // => "1"
You can use -j
.
-j
--junk-paths
Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current directory).
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
OK guys, this is a small solution, but it works fine.
suppose the following code:
<div id='the_div_holder' style='height: 400px; overflow-y: scroll'>
<div class='post'>1st post</div>
<div class='post'>2nd post</div>
<div class='post'>3rd post</div>
</div>
you want when a new post is added to 'the_div_holder' then it scrolls its inner content (the div's .post) to the last one like a chat. So, do the following whenever a new .post is added to the main div holder:
var scroll = function(div) {
var totalHeight = 0;
div.find('.post').each(function(){
totalHeight += $(this).outerHeight();
});
div.scrollTop(totalHeight);
}
// call it:
scroll($('#the_div_holder'));
Lets go over 4 methods
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> from collections import deque
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>>
I think the problem is the realpath of the file. For example your script is working on './', your file is inside the directory './xml'. So better check if the file exists or not, before you get filemtime or unlink it:
function deleteOldFiles(){
if ($handle = opendir('./xml')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/^.*\.(xml|xsl)$/i", $file)){
$fpath = 'xml/'.$file;
if (file_exists($fpath)) {
$filelastmodified = filemtime($fpath);
if ( (time() - $filelastmodified ) > 24*3600){
unlink($fpath);
}
}
}
}
closedir($handle);
}
}
There is a contains
method for lists, so you should be able to do:
Arrays.asList(yourArray).contains(yourObject);
Warning: this might not do what you (or I) expect, see Tom's comment below.
this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.
for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.
PS: but like I said, this might be totally unrelated to your query :)
Really fast, really easy:
srand(time(NULL)); // Seed the time
int finalNum = rand()%(max-min+1)+min; // Generate the number, assign to variable.
And that is it. However, this is biased towards the lower end, but if you are using C++ TR1/C++11 you can do it using the random
header to avoid that bias like so:
#include <random>
std::mt19937 rng(seed);
std::uniform_int_distribution<int> gen(min, max); // uniform, unbiased
int r = gen(rng);
But you can also remove the bias in normal C++ like this:
int rangeRandomAlg2 (int min, int max){
int n = max - min + 1;
int remainder = RAND_MAX % n;
int x;
do{
x = rand();
}while (x >= RAND_MAX - remainder);
return min + x % n;
}
and that was gotten from this post.
public static class XMLHelper
{
/// <summary>
/// Usage: var xmlString = XMLHelper.Serialize<MyObject>(value);
/// </summary>
/// <typeparam name="T">Ki?u d? li?u</typeparam>
/// <param name="value">giá tr?</param>
/// <param name="omitXmlDeclaration">b? qua declare</param>
/// <param name="removeEncodingDeclaration">xóa encode declare</param>
/// <returns>xml string</returns>
public static string Serialize<T>(T value, bool omitXmlDeclaration = false, bool omitEncodingDeclaration = true)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = omitXmlDeclaration, //true: remove <?xml version="1.0" encoding="utf-8"?>
Encoding = Encoding.UTF8,
NewLineChars = "", // remove \r\n
};
var xmlserializer = new XmlSerializer(typeof(T));
using (var memoryStream = new MemoryStream())
{
using (var xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
{
xmlserializer.Serialize(xmlWriter, value);
//return stringWriter.ToString();
}
memoryStream.Position = 0;
using (var sr = new StreamReader(memoryStream))
{
var pureResult = sr.ReadToEnd();
var resultAfterOmitEncoding = ReplaceFirst(pureResult, " encoding=\"utf-8\"", "");
if (omitEncodingDeclaration)
return resultAfterOmitEncoding;
return pureResult;
}
}
}
catch (Exception ex)
{
throw new Exception("XMLSerialize error: ", ex);
}
}
private static string ReplaceFirst(string text, string search, string replace)
{
int pos = text.IndexOf(search);
if (pos < 0)
{
return text;
}
return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
}
}
psxls gave a great answer but I think my Notepad++ version is slightly different so the $ (dollar sign) capturing did not work.
I have Notepad++ v.5.9.3 and here's how you can accomplish your task:
Search for the pattern: value=\"([0-9]*)\" And replace with: \1 (whatever you want to do around that capturing group)
Ex. Surround with square brackets
[\1] --> will produce value="[4]"
Delete entire node "Element" (inside "Connections" tree) from XML file, used by version 18 or higher.
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml
Insert the image inside a with position: relative;
and overflow: hidden;
HTML
<div><img src="#"></div>
CSS
div {
position: relative;
overflow: hidden;
}
img {
filter: blur(5px);
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
}
This also works on variable sizes elements, like dynamic div's.
I just learned of another option for solving this problem. If you load the jquery-turbolinks
gem it will bind the Rails Turbolinks events to the document.ready
events so you can write your jQuery in the usual way. You just add jquery.turbolinks
right after jquery
in the js manifest file (by default: application.js
).
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
You can do it without jQuery!
Example:
document.querySelector('button').setAttribute('disabled', '');
_x000D_
<button>My disabled button!</button>
_x000D_
To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.
I found a very simple solution.
Now, all pages URLs in WordPress should work perfectly.
You can return the URL to the previous setting and the WordPress will re-generate the URL correctly. I choose Post name in my case and it works fine.
You can use also "void*" (void pointer) to send an address to the function.
typedef struct pstring_t {
char * chars;
int(*length)(void*);
} PString;
int length(void* self) {
return strlen(((PString*)self)->chars);
}
PString initializeString() {
PString str;
str.length = &length;
return str;
}
int main()
{
PString p = initializeString();
p.chars = "Hello";
printf("Length: %i\n", p.length(&p));
return 0;
}
Output:
Length: 5
This should work:
grep(pattern = 'A1|A9|A6', x = myfile$Letter)
Or even more simply:
library(data.table)
myfile$Letter %like% 'A1|A9|A6'
In contrast to SGB's answer, I prefer doing the regexp defining the actual format of my data and negating that. This allows me to define values like $DDD,DDD,DDD.DD In the OPs simple scenario, it would look like
SELECT *
FROM table_with_column_to_search
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^[0-9]+$');
which finds all non-positive integers. If you wau accept negatiuve integers also, it's an easy change, just add an optional leading minus.
SELECT *
FROM table_with_column_to_search
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+$');
accepting floating points...
SELECT *
FROM table_with_column_to_search
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+(\.[0-9]+)?$');
Same goes further with any format. Basically, you will generally already have the formats to validate input data, so when you will desire to find data that does not match that format ... it's simpler to negate that format than come up with another one; which in case of SGB's approach would be a bit tricky to do if you want more than just positive integers.
I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string)
and remove(key: string)
method. I suspect that this could be simplified once generics are available in the 0.9 release.
First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.
interface IDictionary {
add(key: string, value: any): void;
remove(key: string): void;
containsKey(key: string): bool;
keys(): string[];
values(): any[];
}
class Dictionary {
_keys: string[] = new string[];
_values: any[] = new any[];
constructor(init: { key: string; value: any; }[]) {
for (var x = 0; x < init.length; x++) {
this[init[x].key] = init[x].value;
this._keys.push(init[x].key);
this._values.push(init[x].value);
}
}
add(key: string, value: any) {
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): any[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary {
return this;
}
}
Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values()
and toLookup()
to return the correct types.
interface IPerson {
firstName: string;
lastName: string;
}
interface IPersonDictionary extends IDictionary {
[index: string]: IPerson;
values(): IPerson[];
}
class PersonDictionary extends Dictionary {
constructor(init: { key: string; value: IPerson; }[]) {
super(init);
}
values(): IPerson[]{
return this._values;
}
toLookup(): IPersonDictionary {
return this;
}
}
And here is a simple initialization and usage example:
var persons = new PersonDictionary([
{ key: "p1", value: { firstName: "F1", lastName: "L2" } },
{ key: "p2", value: { firstName: "F2", lastName: "L2" } },
{ key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();
alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2
persons.remove("p2");
if (!persons.containsKey("p2")) {
alert("Key no longer exists");
// alert: Key no longer exists
}
alert(persons.keys().join(", "));
// alert: p1, p3
If all the web.config
solutions do not work for you and you have implemented PageRouting (IIS 7+), then the code snippet below will solve your problems.
Dont mean to Highjack this question but had the same problem as everyone else and implemented 100% of the suggestions here, with minor modifications for .Net 4.0/4.5, and none of them worked for me.
In my situation i had implemented Page Routing which was ghosting my problem. Basically it would work for about 20, or so, debug runs and then BAM would error out with the Sys is undefined
error.
After reviewing a couple other posts, that got to talking about the Clean-URL logic, i remembered that i had done PageRouting setup's.
Here is the resource i used to build my patterns: Page Routing
My one-liner code fixed my VS2012 Debugging problem:
rts.Ignore("{resource}.axd/{*pathInfo}") 'Ignores any Resource cache references, used heavily in AJAX interactions.
What worked for me was setting up the .prettierrc.json
config file. Put it to the root of your project with a sample config like this:
{
"singleQuote": true,
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
"arrowParens": "always"
}
After triggering the Format Document command, all works just as expected.
Side note: What comes as a bonus with this solution is that each team member gets the same formatting outputs thanks to the present config file.
<li style="background-color: #ffffff;"><a href="/<%=logo_marka_url%>"><img border="0" style="border-radius:5px;background: url(images/picture.jpg') 50% 50% no-repeat;width:150px;height:80px;" src="images/clearpixel.gif"/></a></li>
Other Sample Box Center Image and Background Color
1.First clearpixel fix image area 2.style center image area box 3.li background or div color style
Try this?
encodeURIComponent('space word').replace(/%20/g,'+')
That happened to me exactly the same with this:
<%@ page language="java" contentType="application/json" pageEncoding="UTF-8"%>
But this works for me:
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8"%>
Try adding
;charset=UTF-8
to your contentType.
A little mathematical logic theory here:
"NOT a AND NOT b" is the same as "NOT (a OR b)", so:
"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".
So if you want exact opposite result, df1 and df2 should be as below:
df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]
On RHEL/CentOS/OEL 6
Check that the firewall is allowing connection to Zabbix Server port which is 10051, as a user with root priv:
and add the following lines
-A INPUT -m state --state NEW -m tcp -p tcp --dport 10051 -j ACCEPT
restart iptables
# service iptables restart
If you have disabled IPV6, you need to also edit the hosts file and remove IPV6 line for "localhost"
# vi /etc/hosts
remove or comment out "#" the ipv6 line for localhost
::1 localhost6.localdomain6 localhost6
restart the zabbix-server and check if the error message is gone.
The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:
https://dl-ssl.google.com/android/eclipse/
Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine) I don't know how future-proof these links are. They all worked on February 27th, 2017.
Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.
The first element of the sites
array is an array, as you can see indenting the JSON:
{"units":[{"id":42,
...
"sites":
[
[
{
"id":316,
"article":42,
"clip":133904
}
],
{"length":5}
]
...
}
Therefore you need to treat its value accordingly; probably you could do something like:
JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));
The ftp
command isn't designed for scripts, so controlling it is awkward, and getting its exit status is even more awkward.
Curl is made to be scriptable, and also has the merit that you can easily switch to other protocols later by just modifying the URL. If you put your FTP credentials in your .netrc, you can simply do:
# Download file
curl --netrc --remote-name ftp://ftp.example.com/file.bin
# Upload file
curl --netrc --upload-file file.bin ftp://ftp.example.com/
If you must, you can specify username and password directly on the command line using --user username:password
instead of --netrc
.
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
[dateformate setDateFormat:@"yyyy"]; // Date formater
NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
NSLog(@"date :%@",date);
As several folks have noted, requests doesn't support FTP but Python has other libraries that do. If you want to keep using the requests library, there is a requests-ftp package that adds FTP capability to requests. I've used this library a little and it does work. The docs are full of warnings about code quality though. As of 0.2.0 the docs say "This library was cowboyed together in about 4 hours of total work, has no tests, and relies on a few ugly hacks".
import requests, requests_ftp
requests_ftp.monkeypatch_session()
response = requests.get('ftp://example.com/foo.txt')
I found the following summary very useful: http://www.techrepublic.com/article/configure-vi-for-java-application-development/5054618. The description of :make was for ant not maven, but otherwise a nice summary.
Without annotations, inferred property name (to match from JSON) would be "set", and not -- as seems to be the intent -- "isSet". This is because as per Java Beans specification, methods of form "isXxx" and "setXxx" are taken to mean that there is logical property "xxx" to manage.
This is how you will add local dependencies:
npm install file:src/assets/js/FILE_NAME
Add it to package.json from NPM:
npm install --save file:src/assets/js/FILE_NAME
Directly add to package.json like this:
....
"angular2-autosize": "1.0.1",
"angular2-text-mask": "8.0.2",
"animate.css": "3.5.2",
"LIBRARY_NAME": "file:src/assets/js/FILE_NAME"
....
For me the with NPP V7.6.6 (x64) this worked:
Download the plugin, and unzip to some local folder (e.g. Downloads). Make sure you download the correct plugin for your Notepad++ (64 or 32 bit - e.g. see ? -> About Notepad++ to find if you are 64-bit)
Check each DLL to ensure it is unblocked (right-click, Properties, and check/select Unblock.
Run Notepad++. If you have UAC enabled, use "Run as Administrator" to run Notepad++ (Hold Shift key down, right-click Notepad++ icon, and select "Run as Administrator").
Go to menu Settings -> Import -> Import plugins...
Use dialog displayed to locate you local copy of the plugin DLL.
Once plugin DLL has been selected, Notepad++ should tell you you need to restart. If it doesn't, then Notepad++ has had some problem - though it doesn't tell you what...!
Restart Notepad++.
The above causes a copy of the plugin DLL to be copied under a subfolder of the same name in C:\Program Files\Notepad++\plugins.
Putting plugins directly into one of the following folders (or sub-folders for each plugin), as suggested in other answers, did not work for me:
a) %PROGRAMDATA%\Notepad++\plugins. b) %ALLDATA%\Notepad++\plugins.
I am reproducing the same issue and it's really annoying. I've found these useful:
HttpClient - dealing with aggregate exceptions
Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException
Some code in case the links go nowhere:
var c = new HttpClient();
c.Timeout = TimeSpan.FromMilliseconds(10);
var cts = new CancellationTokenSource();
try
{
var x = await c.GetAsync("http://linqpad.net", cts.Token);
}
catch(WebException ex)
{
// handle web exception
}
catch(TaskCanceledException ex)
{
if(ex.CancellationToken == cts.Token)
{
// a real cancellation, triggered by the caller
}
else
{
// a web request timeout (possibly other things!?)
}
}
First off, BigDecimal.multiply()
returns a BigDecimal
and you're trying to store that in an int
.
Second, it takes another BigDecimal
as the argument, not an int
.
If you just use the BigDecimal
for all variables involved in these calculations, it should work fine.
I hope you were joking about writing your own parser. :-)
For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
If you're using PHP you just do your query and then you can unset an specific element:
$sql = "SELECT * FROM ........ your query";
$result = $conection->query($sql); // execute your query
$row_cnt = $result->num_rows;
if ($row_cnt > 0) {
while ($row = $result->fetch_object()) {
unset($row->your_column_name); // Exclude column from your fetch
$data[] = $row;
}
echo json_encode($data); // or whatever
As described by the others, writing to /dev/null eliminates the output of a program. Usually cron sends an email for every output from the process started with a cronjob. So by writing the output to /dev/null you prevent being spammed if you have specified your adress in cron.
Copying by plain assignment is best, since it's shorter, easier to read, and has a higher level of abstraction. Instead of saying (to the human reader of the code) "copy these bits from here to there", and requiring the reader to think about the size argument to the copy, you're just doing a plain assignment ("copy this value from here to here"). There can be no hesitation about whether or not the size is correct.
Also, if the structure is heavily padded, assignment might make the compiler emit something more efficient, since it doesn't have to copy the padding (and it knows where it is), but mempcy()
doesn't so it will always copy the exact number of bytes you tell it to copy.
If your string is an actual array, i.e.:
struct {
char string[32];
size_t len;
} a, b;
strcpy(a.string, "hello");
a.len = strlen(a.string);
Then you can still use plain assignment:
b = a;
To get a complete copy. For variable-length data modelled like this though, this is not the most efficient way to do the copy since the entire array will always be copied.
Beware though, that copying structs that contain pointers to heap-allocated memory can be a bit dangerous, since by doing so you're aliasing the pointer, and typically making it ambiguous who owns the pointer after the copying operation.
For these situations a "deep copy" is really the only choice, and that needs to go in a function.
sklearn
estimators implement methods to make it easy for you to save relevant trained properties of an estimator. Some estimators implement __getstate__
methods themselves, but others, like the GMM
just use the base implementation which simply saves the objects inner dictionary:
def __getstate__(self):
try:
state = super(BaseEstimator, self).__getstate__()
except AttributeError:
state = self.__dict__.copy()
if type(self).__module__.startswith('sklearn.'):
return dict(state.items(), _sklearn_version=__version__)
else:
return state
The recommended method to save your model to disc is to use the pickle
module:
from sklearn import datasets
from sklearn.svm import SVC
iris = datasets.load_iris()
X = iris.data[:100, :2]
y = iris.target[:100]
model = SVC()
model.fit(X,y)
import pickle
with open('mymodel','wb') as f:
pickle.dump(model,f)
However, you should save additional data so you can retrain your model in the future, or suffer dire consequences (such as being locked into an old version of sklearn).
From the documentation:
In order to rebuild a similar model with future versions of scikit-learn, additional metadata should be saved along the pickled model:
The training data, e.g. a reference to a immutable snapshot
The python source code used to generate the model
The versions of scikit-learn and its dependencies
The cross validation score obtained on the training data
This is especially true for Ensemble estimators that rely on the tree.pyx
module written in Cython(such as IsolationForest
), since it creates a coupling to the implementation, which is not guaranteed to be stable between versions of sklearn. It has seen backwards incompatible changes in the past.
If your models become very large and loading becomes a nuisance, you can also use the more efficient joblib
. From the documentation:
In the specific case of the scikit, it may be more interesting to use joblib’s replacement of
pickle
(joblib.dump
&joblib.load
), which is more efficient on objects that carry large numpy arrays internally as is often the case for fitted scikit-learn estimators, but can only pickle to the disk and not to a string:
The following constructor, JLabel(String, int)
, allow you to specify the horizontal alignment of the label.
JLabel label = new JLabel("The Label", SwingConstants.CENTER);
By default, Windows makes the root of each drive available (provided you've got Administrator privileges) as (e.g.) \\server\c$
. These are known as Administrative Shares.
This works for me:
convert original.png -fuzz 10% -transparent white transparent.png
where the smaller the fuzz %, the closer to true white or conversely, the larger the %, the more variation from white is allowed to become transparent
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Synchronized Vs Atomic Vs Volatile:
Please correct me if anything i missed.
I wouldn't recommend any of these methods. Instead, put it within its own namespace.
class Post < ActiveRecord::Base
def clean_input
self.input = Helpers.sanitize(self.input, :tags => %w(b i u))
end
module Helpers
extend ActionView::Helpers::SanitizeHelper
end
end
private InetAddress getLocalAddress()throws IOException {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
//return inetAddress.getHostAddress().toString();
return inetAddress;
}
}
}
} catch (SocketException ex) {
Log.e("SALMAN", ex.toString());
}
return null;
}
I am doing some basic array in JGrasp and found that with an accessor method for a char[][] array to use ('.') to place a single dot.
You can download a JSON parser from a link on the JSON.org website which works great, you can also stringify you JSON to view the contents.
Also, if you're using EVAL and it's a JSON array then you'll need to use the following synrax:
eval('([' + jsonData + '])');
JavaDoc:
The maximum queue length for incoming connection indications (a request to connect) is set to 50. If a connection indication arrives when the queue is full, the connection is refused.
You should increase "backlog" parameter of your ServerSocket, for example
int backlogSize = 50 ;
new ServerSocket(port, backlogSize);
Mostly stylistic these days. When C was young, there was no such thing as a const variable. So if you used a variable instead of a #define
, you had no guarantee that somebody somewhere wouldn't change the value of it, causing havoc throughout your program.
In the old days, FORTRAN passed even constants to subroutines by reference, and it was possible (and headache inducing) to change the value of a constant like '2' to be something different. One time, this happened in a program I was working on, and the only hint we had that something was wrong was we'd get an ABEND (abnormal end) when the program hit the STOP 999
that was supposed to end it normally.
I would do something like,
Main
var getPage = get_page
func get_page (...
func downloader() {
dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
content := getPage(BASE_URL)
links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
matches := links_regexp.FindAllStringSubmatch(content, -1)
for _, match := range matches{
go serie_dl(match[1], match[2])
}
}
Test
func TestDownloader (t *testing.T) {
origGetPage := getPage
getPage = mock_get_page
defer func() {getPage = origGatePage}()
// The rest to be written
}
// define mock_get_page and rest of the codes
func mock_get_page (....
And I would avoid _
in golang. Better use camelCase
I guess you will get ORA-01741: illegal zero-length identifier if you use the following
SELECT "" AS Contact FROM Customers;
And if you use the following 2 statements, you will be getting the same null value populated in the column.
SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;
Unless I'm badly mistaken libmagic
or -lmagic
is not the same library as ImageMagick. You state that you want ImageMagick.
ImageMagick comes with a utility to supply all appropriate options to the compiler.
Ex:
g++ program.cpp `Magick++-config --cppflags --cxxflags --ldflags --libs` -o "prog"
Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.
My setup was as follows:
I put the following formula in cell A1 of Sheet3:
=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)
Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.
Notes:
In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.
A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.
After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)
and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.
Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.
Cells A2, A3, etc. will get these formulas:
=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)
Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.
Put this in a custom style and it solves all the problems. Using the hacky translucent fix will make your task bar and nav bar translucent and make the splashscreen or main screen look like spaghetti.
<item name="android:windowDisablePreview">true</item>
select Status, * from WorkItems t1
where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
UNION
select 'DELETED', * from WorkItems t1
where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)
Perhaps that'd do the trick. I can't test it from here though, and I'm not sure what version of SQL you're working against.
Ctrl+3 in SQL Server 2012. Might work in 2008 too
Google disallows automated access in their TOS, so if you accept their terms you would break them.
That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)
There are two options to scrape Google results:
1) Use their API
UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.
You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.
If you want a higher amount of API requests you need to pay.
60 requests per hour cost 2000 USD per year, more queries require a custom deal.
2) Scrape the normal result pages
3) Alternatively use a scraping service (updated)
Struggled with the same problem for a couple hours this morning. Building my project from command line seems to have done the trick for me.
Exact steps -
To check if it worked, look in your projects exploded-bundles folder, inspect a library and find the classes.jar. If it is expandable, then everything is going to be ok.
edit - I found after doing a clean within Android studio, it broke again. So if you have to clean, you will need to do this process again.
You may also need to enable the World Wide Web Service inbound firewall rule.
On Windows 7: Start -> Control Panel -> Windows Firewall -> Advanced Settings -> Inbound Rules
Find World Wide Web Services (HTTP Traffic-In)
in the list and select to enable the rule. Change is pretty much immediate.
Solr currently checks for a "pure negative" query and inserts *:*
(which matches all documents) so that it works correctly.
-foo
is transformed by solr into (*:* -foo)
The big caveat is that Solr only checks to see if the top level query is a pure negative query!
So this means that a query like bar OR (-foo)
is not changed since the pure negative query is in a sub-clause of the top level query. You need to transform this query yourself into bar OR (*:* -foo)
You may check the solr query explanation to verify the query transformation:
?q=-title:foo&debug=query
is transformed to
(+(-title:foo +MatchAllDocsQuery(*:*))
rm -rf *
Would remove everything (folders & files) in the current directory.
But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.
git log origin/master..HEAD
You can also view the diff using the same syntax
git diff origin/master..HEAD
https://www.postgresql.org/docs/8.4/functions-formatting.html
SELECT to_char(date_field, 'DD/MM/YYYY')
FROM table
For tab separated values the code below can be used
sort -t$'\t' -k2 -n
-r can be used for getting data in descending order.
-n for numerical sort
-k, --key=POS1[,POS2] where k is column in file
For descending order below is the code
sort -t$'\t' -k2 -rn
Judging from your output it looks like you have defined START_DATE as a timestamp. If it were a regular date Oracle would be able to handle the implicit conversion. But as it isn't you need to explicitly cast those strings to be dates.
SQL> alter session set nls_date_format = 'dd-mon-yyyy hh24:mi:ss'
2 /
Session altered.
SQL>
SQL> select * from t23
2 where start_date between '15-JAN-10' and '17-JAN-10'
3 /
no rows selected
SQL> select * from t23
2 where start_date between to_date('15-JAN-10') and to_date('17-JAN-10')
3 /
WIDGET START_DATE
------------------------------ ----------------------
Small Widget 15-JAN-10 04.25.32.000
SQL>
But we still only get one row. This is because START_DATE has a time element. If we don't specify the time component Oracle defaults it to midnight. That is fine for the from side of the BETWEEN
but not for the until side:
SQL> select * from t23
2 where start_date between to_date('15-JAN-10')
3 and to_date('17-JAN-10 23:59:59')
4 /
WIDGET START_DATE
------------------------------ ----------------------
Small Widget 15-JAN-10 04.25.32.000
Product 1 17-JAN-10 04.31.32.000
SQL>
edit
If you cannot pass in the time component there are a couple of choices. One is to change the WHERE clause to remove the time element from the criteria:
where trunc(start_date) between to_date('15-JAN-10')
and to_date('17-JAN-10')
This might have an impact on performance, because it disqualifies any b-tree index on START_DATE. You would need to build a function-based index instead.
Alternatively you could add the time element to the date in your code:
where start_date between to_date('15-JAN-10')
and to_date('17-JAN-10') + (86399/86400)
Because of these problems many people prefer to avoid the use of between
by checking for date boundaries like this:
where start_date >= to_date('15-JAN-10')
and start_date < to_date('18-JAN-10')
I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.
$('#selectField').change(function(){
if($('#selectField').val() == 'N'){
$('#secondaryInput').hide();
} else {
$('#secondaryInput').show();
}
});
Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".
$('#selectField').val(valueFromDatabase).change();
So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.
You can use default_scope to implement a default sort order http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html
At the very core, the file extension you use makes no difference as to how perl
interprets those files.
However, putting modules in .pm
files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD
and you put it in a directory Example/Plot/FourD.pm
in a path in your @INC
, then use
and require
will do the right thing when given the package name as in use Example::Plot::FourD
.
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with
1;
unless you're sure it'll return true otherwise. But it's better just to put the1;
, in case you add more statements.If
EXPR
is a bareword, therequire
assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.
All use
does is to figure out the filename from the package name provided, require
it in a BEGIN
block and invoke import
on the package. There is nothing preventing you from not using use
but taking those steps manually.
For example, below I put the Example::Plot::FourD
package in a file called t.pl
, loaded it in a script in file s.pl
.
C:\Temp> cat t.pl
package Example::Plot::FourD;
use strict; use warnings;
sub new { bless {} => shift }
sub something { print "something\n" }
"Example::Plot::FourD"
C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;
BEGIN {
require 't.pl';
}
my $p = Example::Plot::FourD->new;
$p->something;
C:\Temp> s
something
This example shows that module files do not have to end in 1
, any true value will do.
You can easily use this function to get the result:
function objetToArray($adminBar){
$reflector = new ReflectionObject($adminBar);
$nodes = $reflector->getProperties();
$out = [];
foreach ($nodes as $node) {
$nod = $reflector->getProperty($node->getName());
$nod->setAccessible(true);
$out[$node->getName()] = $nod->getValue($adminBar);
}
return $out;
}
Use PHP 5 or later.
C# Xamarin version
const string FIRST_RUN = "hasRunBefore";
var userDefaults = NSUserDefaults.StandardUserDefaults;
if (!userDefaults.BoolForKey(FIRST_RUN))
{
//TODO: remove keychain items
userDefaults.SetBool(true, FIRST_RUN);
userDefaults.Synchronize();
}
... and to clear records from the keychain (TODO comment above)
var securityRecords = new[] { SecKind.GenericPassword,
SecKind.Certificate,
SecKind.Identity,
SecKind.InternetPassword,
SecKind.Key
};
foreach (var recordKind in securityRecords)
{
SecRecord query = new SecRecord(recordKind);
SecKeyChain.Remove(query);
}
when to use const
or readonly
const
readonly
App.config
, but once it initializes it can't be changedTo convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
From the main menu bar, select command link File > Import.... The Import wizard opens.
Select General > Existing Project into Workspace and click Next.
Choose either Select root directory or Select archive file and click the associated Browse to locate the directory or file containing the projects.
Under Projects select the project or projects which you would like to import.
Click Finish to start the import.
In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:
import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'
df['string_col'].str.replace(regular_expression, '', regex=True)
With the EncodingHelper plugin you can view the encoding of the file on the status bar. Also you can convert the encoding of the file and extended another functionalities.
In my case, the Webservice was generating the assembly with a different name than the project/service name. It was set like that by my predecessor developer working on the solution and I didn't know.
It was set to -
<serviceBehaviors>
<behavior name="CustomServiceBehavior">
<serviceAuthorization serviceAuthorizationManagerType="BookingService.KeyAuthorizationManager, BookingService" />
</behavior>
</serviceBehaviors>
So, the fix was the put the right assembly name in serviceAuthorizationManagerType. The assembly name can be obtained from following path of the service project: Right click on the WCF svc project--> Select "Properties" --> From the list of tabs select "Application". Check the value against "Assembly name:" field in the list. This is the assemblyName to use for serviceAuthorizationManagerType which may not be the servicename necessarily.
<serviceBehaviors>
<behavior name="MyCustomServiceBehavior">
<serviceAuthorization serviceAuthorizationManagerType="BookingService.KeyAuthorizationManager, AssemblyNameFromSvcProperties" />
</behavior>
</serviceBehaviors>
remember to follow the instruction for serviceAuthorizationManagerType as mentioned on https://docs.microsoft.com/en-us/dotnet/framework/wcf/extending/how-to-create-a-custom-authorization-manager-for-a-service
It says -
Warning
Note that when you specify the serviceAuthorizationManagerType, the string must contain the fully qualified type name. a comma, and the name of the assembly in which the type is defined. If you leave out the assembly name, WCF will attempt to load the type from System.ServiceModel.dll.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
When transmitting data or storing them in a file, the data are required to be byte strings, but complex objects are seldom in this format. Serialization can convert these complex objects into byte strings for such use. After the byte strings are transmitted, the receiver will have to recover the original object from the byte string. This is known as deserialization.
Say, you have an object:
{foo: [1, 4, 7, 10], bar: "baz"}
serializing into JSON will convert it into a string:
'{"foo":[1,4,7,10],"bar":"baz"}'
which can be stored or sent through wire to anywhere. The receiver can then deserialize this string to get back the original object. {foo: [1, 4, 7, 10], bar: "baz"}
.
Based on a link to Apache HTTP Components on this SO thread, I came across the Fluent facade API for HTTP Components. An example there shows how to set up a queue of asynchronous HTTP requests (and get notified of their completion/failure/cancellation). In my case, I didn't need a queue, just one async request at a time.
Here's where I ended up (also using URIBuilder from HTTP Components, example here).
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;
//...
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("myhost.com").setPath("/folder")
.setParameter("query0", "val0")
.setParameter("query1", "val1")
...;
URI requestURL = null;
try {
requestURL = builder.build();
} catch (URISyntaxException use) {}
ExecutorService threadpool = Executors.newFixedThreadPool(2);
Async async = Async.newInstance().use(threadpool);
final Request request = Request.Get(requestURL);
Future<Content> future = async.execute(request, new FutureCallback<Content>() {
public void failed (final Exception e) {
System.out.println(e.getMessage() +": "+ request);
}
public void completed (final Content content) {
System.out.println("Request completed: "+ request);
System.out.println("Response:\n"+ content.asString());
}
public void cancelled () {}
});
To increase uploading file's size limit we have two ways
1. IIS6 or lower
By default, in ASP.Net the maximum size of a file to be uploaded to the server is around 4MB. This value can be increased by modifying the maxRequestLength attribute in web.config.
Remember : maxRequestLenght is in KB
Example: if you want to restrict uploads to 15MB, set maxRequestLength to “15360” (15 x 1024).
<system.web>
<!-- maxRequestLength for asp.net, in KB -->
<httpRuntime maxRequestLength="15360" ></httpRuntime>
</system.web>
2. IIS7 or higher
A slight different way used here to upload files.IIS7 has introduced request filtering module.Which executed before ASP.Net.Means the way pipeline works is that the IIS value(maxAllowedContentLength) checked first then ASP.NET value(maxRequestLength) is checked.The maxAllowedContentLength attribute defaults to 28.61 MB.This value can be increased by modifying both attribute in same web.config.
Remember : maxAllowedContentLength is in bytes
Example : if you want to restrict uploads to 15MB, set maxRequestLength to “15360” and maxAllowedContentLength to "15728640" (15 x 1024 x 1024).
<system.web>
<!-- maxRequestLength for asp.net, in KB -->
<httpRuntime maxRequestLength="15360" ></httpRuntime>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!-- maxAllowedContentLength, for IIS, in bytes -->
<requestLimits maxAllowedContentLength="15728640" ></requestLimits>
</requestFiltering>
</security>
</system.webServer>
MSDN Reference link : https://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx
simply use a 'script' tag with a dot after.
script.
var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}
https://github.com/pugjs/pug/blob/master/examples/dynamicscript.pug
I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q)
, but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use
.
I did a docker system prune
and it cleaned up what was needed to remove the last volume:
[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated
Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER VOLUME NAME
local uuid
[0]$ docker volume rm uuid
uuid
[0]$
The client and daemon API must both be at least 1.25 to use this command. Use the
docker version
command on the client to check your client and daemon API versions.
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission). This has been confirmed by Facebook as 'by design'.
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.
To bad CSS doesn't support cross-browser multiline clamping, only webkit seems to be pushing it.
You could try and use a simple Javascript ellipsis library like Ellipsity on github the source code is very clean and small so if you do need to make any additional changes it should be quite easy.
Using Laravel 4.2 without Carbon
Here's how I grab the recent ten days and count each row with same day created_at timestamp.
$q = Spins::orderBy('created_at', 'desc')
->groupBy(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
->take(10)
->get(array(
DB::raw('Date(created_at) as date'),
DB::raw('COUNT(*) as "views"')
));
foreach ($q as $day) {
echo $day->date. " Views: " . $day->views.'<br>';
}
Hope this helps
Answers above are all cool, but they all missed one thing. group executes tasks(blocks) in the thread where it entered when you use dispatch_group_enter
/dispatch_group_leave
.
- (IBAction)buttonAction:(id)sender {
dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(demoQueue, ^{
dispatch_group_t demoGroup = dispatch_group_create();
for(int i = 0; i < 10; i++) {
dispatch_group_enter(demoGroup);
[self testMethod:i
block:^{
dispatch_group_leave(demoGroup);
}];
}
dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
NSLog(@"All group tasks are done!");
});
});
}
- (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
NSLog(@"Group task started...%ld", index);
NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
[NSThread sleepForTimeInterval:1.f];
if(completeBlock) {
completeBlock();
}
}
this runs in the created concurrent queue demoQueue
. If i dont create any queue, it runs in main thread.
- (IBAction)buttonAction:(id)sender {
dispatch_group_t demoGroup = dispatch_group_create();
for(int i = 0; i < 10; i++) {
dispatch_group_enter(demoGroup);
[self testMethod:i
block:^{
dispatch_group_leave(demoGroup);
}];
}
dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
NSLog(@"All group tasks are done!");
});
}
- (void)testMethod:(NSInteger)index block:(void(^)(void))completeBlock {
NSLog(@"Group task started...%ld", index);
NSLog(@"Current thread is %@ thread", [NSThread isMainThread] ? @"main" : @"not main");
[NSThread sleepForTimeInterval:1.f];
if(completeBlock) {
completeBlock();
}
}
and there's a third way to make tasks executed in another thread:
- (IBAction)buttonAction:(id)sender {
dispatch_queue_t demoQueue = dispatch_queue_create("com.demo.group", DISPATCH_QUEUE_CONCURRENT);
// dispatch_async(demoQueue, ^{
__weak ViewController* weakSelf = self;
dispatch_group_t demoGroup = dispatch_group_create();
for(int i = 0; i < 10; i++) {
dispatch_group_enter(demoGroup);
dispatch_async(demoQueue, ^{
[weakSelf testMethod:i
block:^{
dispatch_group_leave(demoGroup);
}];
});
}
dispatch_group_notify(demoGroup, dispatch_get_main_queue(), ^{
NSLog(@"All group tasks are done!");
});
// });
}
Of course, as mentioned you can use dispatch_group_async
to get what you want.