This might be helpful for whoever else faces this problem. I finally figured out a solution. Turns out, even if we use the inline for "content-disposition" and specify a file name, the browsers still do not use the file name. Instead browsers try and interpret the file name based on the Path/URL.
You can read further on this URL: Securly download file inside browser with correct filename
This gave me an idea, I just created my URL route that would convert the URL and end it with the name of the file I wanted to give the file. So for e.g. my original controller call just consisted of passing the Order Id of the Order being printed. I was expecting the file name to be of the format Order{0}.pdf where {0} is the Order Id. Similarly for quotes, I wanted Quote{0}.pdf.
In my controller, I just went ahead and added an additional parameter to accept the file name. I passed the filename as a parameter in the URL.Action method.
I then created a new route that would map that URL to the format: http://localhost/ShoppingCart/PrintQuote/1054/Quote1054.pdf
routes.MapRoute("", "{controller}/{action}/{orderId}/{fileName}",
new { controller = "ShoppingCart", action = "PrintQuote" }
, new string[] { "x.x.x.Controllers" }
);
This pretty much solved my issue. Hoping this helps someone!
Cheerz, Anup
I'm using the following method based on @Watki02's answer:
That way you can keep your visual studio instance as your own user whilst debugging from the other.
If you are 100% sure that you have just one stash or you want to delete all stashes (make a git stash list
to be 107% sure), you can do a:
git stash clear
..and forget about them (it deletes all stashes).
Note: Added this answer for those who ended up here looking for a way to clear them all (like me).
git stash apply n
works as of git version 2.11
Original answer, possibly helping to debug issues with the older syntax involving shell escapes:
As pointed out previously, the curly braces may require escaping or quoting depending on your OS, shell, etc.
See "stash@{1} is ambiguous?" for some detailed hints of what may be going wrong, and how to work around it in various shells and platforms.
git stash list
git stash apply stash@{n}
I wrote a blog post about this.
To summarise, some of the options are:
I finally found that none were suitable for me, and developed my own little "framework". (It is not open-source yet).
faster and shorter :
// nl is the nodelist
var a=[], l=nl.length>>>0;
for( ; l--; a[l]=nl[l] );
Maybe it helps someone too:)
I'm not allowed to post images, so here goes extra link to my blog. Sorry.
IIS webpage by using IP address
In IIS Management : Choose Site, then Bindings.
Add
Here is the changeLocation example from this article http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase
//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
$scope = $scope || angular.element(document).scope();
if(forceReload || $scope.$$phase) {
window.location = url;
}
else {
//only use this if you want to replace the history stack
//$location.path(url).replace();
//this this if you want to change the URL and add it to the history stack
$location.path(url);
$scope.$apply();
}
};
Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html
tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge
Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure
war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes
ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files
You can set this bookmarklet in your "Bookmarks Bar" in order to have Firebug lite always available in Chrome/Chromium browser (put this as the URL):
javascript:var firebug=document.createElement('script');firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');document.body.appendChild(firebug);(function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug);
In combination of answers of @Cassian and @Hllitec and from https://stackoverflow.com/a/42706309/1001717 here my solution, where I put (only!) the checksum value into a variable for further processing:
for /f "delims=" %i in ('certutil -v -hashfile myPackage.nupkg SHA256 ^| find /i /v "sha256" ^| find /i /v "certutil"') do set myVar=%i
To test the output you can add a piped echo command with the var:
for /f "delims=" %i in ('certutil -v -hashfile myPackage.nupkg SHA256 ^| find /i /v "sha256" ^| find /i /v "certutil"') do set myVar=%i | echo %myVar%
A bit off-topic, but FYI: I used this before uploading my NuGet package to Artifactory. BTW. as alternative you can use JFrog CLI, where checksum is calculated automatically.
I think you should store the size somewhere.
The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.
Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.
P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.
You can add new column with the query
ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)
But it will be added at the end, not in between the existing columns.
To help others who do not have a full disk to troubleshoot this problem, first inspect your error log (for me the path is given in my /etc/mysql/my.cnf
file):
tail /var/log/mysql/error.log
My problem turned out to be a new IP address allocated after some network router reconfiguration, so I needed to change the bind-address
variable.
You can get through every object in the list and get which value you want. Just pass an object as first parameter in the function call and object property which you want as second parameter. Change object with your object.
const treeData = [{_x000D_
"jssType": "fieldset",_x000D_
"jssSelectLabel": "Fieldset (with legend)",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "fieldset-715",_x000D_
"jssLabel": "Legend",_x000D_
"jssIcon": "typcn typcn-folder",_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "list-ol",_x000D_
"jssSelectLabel": "List - ol",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-ol-147",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ol",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "list-li",_x000D_
"jssSelectLabel": "List Item - li",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-li-752",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ul",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "text",_x000D_
"jssSelectLabel": "Text (short text)",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "text-422",_x000D_
"jssLabel": "Your Name (required)",_x000D_
"jsRequired": true,_x000D_
"jsTagOptions": [{_x000D_
"jsOption": "",_x000D_
"optionLabel": "Default value",_x000D_
"optionType": "input"_x000D_
},_x000D_
{_x000D_
"jsOption": "placeholder",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Use this text as the placeholder of the field",_x000D_
"optionType": "checkbox"_x000D_
},_x000D_
{_x000D_
"jsOption": "akismet_author_email",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Akismet - this field requires author's email address",_x000D_
"optionType": "checkbox"_x000D_
}_x000D_
],_x000D_
"jsValues": "",_x000D_
"jsPlaceholder": false,_x000D_
"jsAkismetAuthor": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-sort-alphabetically",_x000D_
"noChildren": true_x000D_
}]_x000D_
},_x000D_
{_x000D_
"jssType": "list-li",_x000D_
"jssSelectLabel": "List Item - li",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-li-538",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ul",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "email",_x000D_
"jssSelectLabel": "Email",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "email-842",_x000D_
"jssLabel": "Email Address (required)",_x000D_
"jsRequired": true,_x000D_
"jsTagOptions": [{_x000D_
"jsOption": "",_x000D_
"optionLabel": "Default value",_x000D_
"optionType": "input"_x000D_
},_x000D_
{_x000D_
"jsOption": "placeholder",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Use this text as the placeholder of the field",_x000D_
"optionType": "checkbox"_x000D_
},_x000D_
{_x000D_
"jsOption": "akismet_author_email",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Akismet - this field requires author's email address",_x000D_
"optionType": "checkbox"_x000D_
}_x000D_
],_x000D_
"jsValues": "",_x000D_
"jsPlaceholder": false,_x000D_
"jsAkismetAuthorEmail": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-mail",_x000D_
"noChildren": true_x000D_
}]_x000D_
},_x000D_
{_x000D_
"jssType": "list-li",_x000D_
"jssSelectLabel": "List Item - li",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "list-li-855",_x000D_
"jssLabel": "",_x000D_
"jssIcon": "dashicons dashicons-editor-ul",_x000D_
"noChildren": false,_x000D_
"expanded": true,_x000D_
"children": [{_x000D_
"jssType": "textarea",_x000D_
"jssSelectLabel": "Textarea (long text)",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "textarea-217",_x000D_
"jssLabel": "Your Message",_x000D_
"jsRequired": false,_x000D_
"jsTagOptions": [{_x000D_
"jsOption": "",_x000D_
"optionLabel": "Default value",_x000D_
"optionType": "input"_x000D_
},_x000D_
{_x000D_
"jsOption": "placeholder",_x000D_
"isChecked": false,_x000D_
"optionLabel": "Use this text as the placeholder of the field",_x000D_
"optionType": "checkbox"_x000D_
}_x000D_
],_x000D_
"jsValues": "",_x000D_
"jsPlaceholder": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-document-text",_x000D_
"noChildren": true_x000D_
}]_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
"jssType": "paragraph",_x000D_
"jssSelectLabel": "Paragraph - p",_x000D_
"jssSelectGroup": "jssItem",_x000D_
"jsName": "paragraph-993",_x000D_
"jssContent": "* Required",_x000D_
"jssIcon": "dashicons dashicons-editor-paragraph",_x000D_
"noChildren": true_x000D_
}_x000D_
]_x000D_
_x000D_
},_x000D_
{_x000D_
"jssType": "submit",_x000D_
"jssSelectLabel": "Submit",_x000D_
"jssSelectGroup": "jsTag",_x000D_
"jsName": "submit-704",_x000D_
"jssLabel": "Send",_x000D_
"jsValues": "",_x000D_
"jsRequired": false,_x000D_
"jsIdAttribute": "",_x000D_
"jsClassAttribute": "",_x000D_
"jssIcon": "typcn typcn-mail",_x000D_
"noChildren": true_x000D_
},_x000D_
_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function findObjectByLabel(obj, label) {_x000D_
for(var elements in obj){_x000D_
if (elements === label){_x000D_
console.log(obj[elements]);_x000D_
}_x000D_
if(typeof obj[elements] === 'object'){_x000D_
findObjectByLabel(obj[elements], 'jssType');_x000D_
}_x000D_
_x000D_
}_x000D_
};_x000D_
_x000D_
findObjectByLabel(treeData, 'jssType');
_x000D_
[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)
For me, the problem was that I wasn't including bootstrap.min.css (I was only including bootstrap-responsive.min.css).
like some say boost::replace_all
here a dummy example:
#include <boost/algorithm/string/replace.hpp>
std::string path("file.gz");
boost::replace_all(path, ".gz", ".zip");
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));
This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]()
.
very basic:
<?php
$username = 'user';
$password = 'password';
$server = 'localhost';
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>
result:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please
as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php
The following does not return a response:
You must return anything like return afunction()
or return 'a string'
.
This can solve the issue
When loading all names of files in the operating directory you can use
Dir.glob("*)
This will return all files within the context that the application is running in (Note for Rails this is the top level directory of the application)
You can do additional matching and recursive searching found here https://ruby-doc.org/core-2.7.1/Dir.html#method-c-glob
select isnull(nullif(CAR_OWNER_TEL, ''), 'NULLLLL') PHONE from TABLE
will replace CAR_OWNER_TEL if empty by NULLLLL (MS SQL)
import org.springframework.core.io.ClassPathResource;
...
File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();
It is worth noting that this will limit your deployment options, ClassPathResource.getFile()
only works if the container has exploded (unzipped) your war file.
if (input == undefined) { ... }
works just fine. It is of course not a null
comparison, but I usually find that if I need to distinguish between undefined
and null
, I actually rather need to distinguish between undefined
and just any false value, so
else if (input) { ... }
does it.
If a program redefines undefined
it is really braindead anyway.
The only reason I can think of was for IE4 compatibility, it did not understand the undefined
keyword (which is not actually a keyword, unfortunately), but of course values could be undefined
, so you had to have this:
var undefined;
and the comparison above would work just fine.
In your second example, you probably need double parentheses to make lint happy?
Since most modern CPUs support virtualization natively, the reason you received such message can be because virtualization is turned off on your machine. For example, that was the case on my HP laptop - the factory setting for hardware virtualization was "Disabled". So, go to your machine's BIOS and enable virtualization.
Try:
DateTime first;
DateTime second;
int milliSeconds = (int)((TimeSpan)(second - first)).TotalMilliseconds;
Actually, it's not possible with axios as of now. The status codes which falls in the range of 2xx
only, can be caught in .then()
.
A conventional approach is to catch errors in the catch()
block like below:
axios.get('/api/xyz/abcd')
.catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
Another approach can be intercepting requests or responses before they are handled by then or catch.
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
This will work as well:
$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
This setting works well under angular 8:
Package.json:
...
"dependencies": {
"@angular/animations": "^8.2.14",
"@angular/cdk": "8.2.3",
"@angular/common": "^8.2.14",
"@angular/compiler": "^8.2.14",
"@angular/core": "^8.2.14",
...
"devDependencies": {
"@angular-devkit/build-angular": "~0.803.29",
"@angular/cli": "~8.3.29",
"@angular/compiler-cli": "^8.2.14"
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
Change the key of the component.
<Component key="1" />
<Component key="2" />
Component will be unmounted and a new instance of Component will be mounted since the key has changed.
edit: Documented on You Probably Don't Need Derived State:
When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.
<%
String session_val = (String)session.getAttribute("sessionval");
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
The proper way to get LF endings in Windows is to first set core.autocrlf
to false
:
git config --global core.autocrlf false
You need to do this if you are using msysgit, because it sets it to true
in its system settings.
Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto
in your .gitattributes
for all files:
* text=auto
And set core.eol
to lf
:
git config --global core.eol lf
Now you can also switch single repos to crlf (in the working directory!) by running
git config core.eol crlf
After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:
git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f
If you now want git to also normalize the files in your working directory, run these commands:
git ls-files -z | xargs -0 rm
git checkout .
Another, more concise, option:
z = dict(x, **y)
Note: this has become a popular answer, but it is important to point out that if y
has any non-string keys, the fact that this works at all is an abuse of a CPython implementation detail, and it does not work in Python 3, or in PyPy, IronPython, or Jython. Also, Guido is not a fan. So I can't recommend this technique for forward-compatible or cross-implementation portable code, which really means it should be avoided entirely.
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
pure javascript no jQuery
function sah() {_x000D_
$("#div2").attr("disabled", "disabled").off('click');_x000D_
var x1=$("#div2").hasClass("disabledDiv");_x000D_
_x000D_
(x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
function sah1(el) {_x000D_
try {_x000D_
el.disabled = el.disabled ? false : true;_x000D_
} catch (E) {}_x000D_
if (el.childNodes && el.childNodes.length > 0) {_x000D_
for (var x = 0; x < el.childNodes.length; x++) {_x000D_
sah1(el.childNodes[x]);_x000D_
}_x000D_
}_x000D_
}
_x000D_
#div2{_x000D_
padding:5px 10px;_x000D_
background-color:#777;_x000D_
width:150px;_x000D_
margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
pointer-events: none;_x000D_
opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
<div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
<input type="text" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="button" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="radio" name="sex" value="Male" />Male_x000D_
<Br />_x000D_
<input type="radio" name="sex" value="Female" />Female_x000D_
<Br />_x000D_
</div>_x000D_
<Br />_x000D_
<Br />_x000D_
<input type="button" value="Click" onclick="sah()" />
_x000D_
Try this
public void onClick(View view){
txtView.setText("hello");
//printmyname();
Toast.makeText(NameonbuttonclickActivity.this, "hello", Toast.LENGTH_LONG).show();
}
Also in toast use "Hello"
The way I typically handle this is with a second piece of software. For Windows I use Notepad++, for OS X I use Sublime Text 2.
The reason you are getting this error is that you have a vector
.
If you want to use the $
operator, you simply need to convert it to a data.frame
. But since you only have one row in this particular case, you would also need to transpose it; otherwise bob
and ed
will become your row names instead of your column names which is what I think you want.
x <- c(1, 2)
x
names(x) <- c("bob", "ed")
x <- as.data.frame(t(x))
x$ed
[1] 2
I posted some code in answer to a related question on StackOverflow:
Sorting a multidimensionnal array in VBA
The code samples in that thread include:
Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop.
Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort.
Public Sub QuickSortArray(ByRef SortArray As Variant, _ Optional lngMin As Long = -1, _ Optional lngMax As Long = -1, _ Optional lngColumn As Long = 0) On Error Resume Next
'Sort a 2-Dimensional array
' Sample Usage: sort arrData by the contents of column 3 ' ' QuickSortArray arrData, , , 3
' 'Posted by Jim Rech 10/20/98 Excel.Programming
'Modifications, Nigel Heffernan:
' ' Escape failed comparison with empty variant ' ' Defensive coding: check inputs
Dim i As Long Dim j As Long Dim varMid As Variant Dim arrRowTemp As Variant Dim lngColTemp As Long
If IsEmpty(SortArray) Then Exit Sub End If
If InStr(TypeName(SortArray), "()") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name Exit Sub End If
If lngMin = -1 Then lngMin = LBound(SortArray, 1) End If
If lngMax = -1 Then lngMax = UBound(SortArray, 1) End If
If lngMin >= lngMax Then ' no sorting required Exit Sub End If
i = lngMin j = lngMax
varMid = Empty varMid = SortArray((lngMin + lngMax) \ 2, lngColumn)
' We send 'Empty' and invalid data items to the end of the list: If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid might pick up a valid default member or property i = lngMax j = lngMin ElseIf IsEmpty(varMid) Then i = lngMax j = lngMin ElseIf IsNull(varMid) Then i = lngMax j = lngMin ElseIf varMid = "" Then i = lngMax j = lngMin ElseIf varType(varMid) = vbError Then i = lngMax j = lngMin ElseIf varType(varMid) > 17 Then i = lngMax j = lngMin End If
While i <= j
While SortArray(i, lngColumn) < varMid And i < lngMax i = i + 1 Wend
While varMid < SortArray(j, lngColumn) And j > lngMin j = j - 1 Wend
If i <= j Then
' Swap the rows ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2)) For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2) arrRowTemp(lngColTemp) = SortArray(i, lngColTemp) SortArray(i, lngColTemp) = SortArray(j, lngColTemp) SortArray(j, lngColTemp) = arrRowTemp(lngColTemp) Next lngColTemp Erase arrRowTemp
i = i + 1 j = j - 1
End If
Wend
If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn) If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)
End Sub
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.
The main advantage of numpy matrices is that they provide a convenient notation
for matrix multiplication: if a and b are matrices, then a*b
is their matrix
product.
import numpy as np
a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
# [2 1]]
print(b)
# [[1 2]
# [3 4]]
print(a*b)
# [[13 20]
# [ 5 8]]
On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @
operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.
import numpy as np
a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
# [ 5 8]]
Both matrix objects and ndarrays have .T
to return the transpose, but matrix
objects also have .H
for the conjugate transpose, and .I
for the inverse.
In contrast, numpy arrays consistently abide by the rule that operations are
applied element-wise (except for the new @
operator). Thus, if a
and b
are numpy arrays, then a*b
is the array
formed by multiplying the components element-wise:
c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
# [6 4]]
To obtain the result of matrix multiplication, you use np.dot
(or @
in Python >= 3.5, as shown above):
print(np.dot(c,d))
# [[13 20]
# [ 5 8]]
The **
operator also behaves differently:
print(a**2)
# [[22 15]
# [10 7]]
print(c**2)
# [[16 9]
# [ 4 1]]
Since a
is a matrix, a**2
returns the matrix product a*a
.
Since c
is an ndarray, c**2
returns an ndarray with each component squared
element-wise.
There are other technical differences between matrix objects and ndarrays
(having to do with np.ravel
, item selection and sequence behavior).
The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.
Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect.
In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.
If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.
PS. Of course, you really don't have to choose one at the expense of the other,
since np.asmatrix
and np.asarray
allow you to convert one to the other (as
long as the array is 2-dimensional).
There is a synopsis of the differences between NumPy arrays
vs NumPy matrix
es here.
bash has a builtin
pushd SOME_PATH
run_stuff
...
...
popd
Credit to @mehras for the code. I just created a snippet to demonstrate it because I thought that would be appreciated and I wanted an excuse to try that feature.
$(document).ready(function() {_x000D_
$('#container').addClass('hidden');_x000D_
$('#header').click(function() {_x000D_
if ($('#container').hasClass('hidden')) {_x000D_
$('#container').removeClass('hidden');_x000D_
} else {_x000D_
$('#container').addClass('hidden');_x000D_
}_x000D_
});_x000D_
$('#header input[type=checkbox]').click(function(event) {_x000D_
if (event.stopPropagation) { // standard_x000D_
event.stopPropagation();_x000D_
} else { // IE6-8_x000D_
event.cancelBubble = true;_x000D_
}_x000D_
});_x000D_
});
_x000D_
div {_x000D_
text-align: center;_x000D_
padding: 2em;_x000D_
font-size: 1.2em_x000D_
}_x000D_
_x000D_
.hidden {_x000D_
display: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="header"><input type="checkbox" />Checkbox won't bubble the event, but this text will.</div>_x000D_
<div id="container">click() bubbled up!</div>
_x000D_
You define the class gameObject
in both your .cpp
file and your .h
file.
That is creating a redefinition error.
You should define the class, ONCE, in ONE place.
(convention says the definition is in the .h
, and all the implementation is in the .cpp
)
Please help us understand better, what part of the error message did you have trouble with?
The first part of the error says the class has been redefined in gameObject.cpp
The second part of the error says the previous definition is in gameObject.h
.
How much clearer could the message be?
The PHP function array_key_exists()
determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset()
can tell you that (and that the value is not null
). array_key_exists()
cannot return information about the value of a key/index.
If you are using JavaScript, the solution provided by cletus, (?<=\[)(.*?)(?=\])
won't work because JavaScript doesn't support the lookbehind operator.
Edit: actually, now (ES2018) it's possible to use the lookbehind operator. Just add / to define the regex string, like this:
var regex = /(?<=\[)(.*?)(?=\])/;
Old answer:
Solution:
var regex = /\[(.*?)\]/;
var strToMatch = "This is a test string [more or less]";
var matched = regex.exec(strToMatch);
It will return:
["[more or less]", "more or less"]
So, what you need is the second value. Use:
var matched = regex.exec(strToMatch)[1];
To return:
"more or less"
To add to the others, var_export might be handy too:
$email_text = var_export($_POST, true);
You can give it a property display block; so it will behave like a div and have its own line
CSS:
.feature_desc {
display: block;
....
}
<div id="uploadButton">UPLOAD</div>
<form action="[FILE_HANDLER_URL]" style="display:none">
<input id="myInput" type="file" />
</form>
<script>
const uploadButton = document.getElementById('uploadButton');
const myInput = document.getElementById('myInput');
uploadButton.addEventListener('click', () => {
myInput.click();
});
</script>
I think that this construct: if exists (select...
is specific for MS SQL. In MySQL EXISTS
predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
You can rewrite the above lines of code like this:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
You can call QCoreApplication::exit(0) to exit with code 0
There's no need to use extra large tables or ALL_OBJECTS table:
SELECT TRUNC (SYSDATE - ROWNUM) dt
FROM DUAL CONNECT BY ROWNUM < 366
will do the trick.
Angular 6.0.0
https://github.com/angular/angular/blob/master/CHANGELOG.md#610-2018-07-25
introduced a KeyValuePipe
See also https://angular.io/api/common/KeyValuePipe
@Component({ selector: 'keyvalue-pipe', template: `<span> <p>Object</p> <div *ngFor="let item of object | keyvalue"> {{item.key}}:{{item.value}} </div> <p>Map</p> <div *ngFor="let item of map | keyvalue"> {{item.key}}:{{item.value}} </div> </span>` }) export class KeyValuePipeComponent { object: {[key: number]: string} = {2: 'foo', 1: 'bar'}; map = new Map([[2, 'foo'], [1, 'bar']]); }
original
You can use a pipe
@Pipe({ name: 'keys', pure: false })
export class KeysPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value)//.map(key => value[key]);
}
}
<div *ngFor="let key of objs | keys">
This is how I do it, with a README.md file in each directory:
/data/*
!/data/README.md
!/data/input/
/data/input/*
!/data/input/README.md
!/data/output/
/data/output/*
!/data/output/README.md
I have similar requirement where I need a MySQL client but not server (running in a virtual machine and don't want any additional overhead) and for me the easiest thing was to install MySQL community server taking typical installation options but NOT configure the server, so it never starts, never runs. Added C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin to system path environment variable and I'm able to use the MySQL command line client mssql.exe and mysqladmin.exe programs.
We can check error & 404 statusCode, and use try {} catch (err) {}
.
You can try this :
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
if (req.status == 404) {_x000D_
console.log("404");_x000D_
return false;_x000D_
}_x000D_
_x000D_
if (!(req.readyState == 4 && req.status == 200))_x000D_
return false;_x000D_
_x000D_
const json = (function(raw) {_x000D_
try {_x000D_
return JSON.parse(raw);_x000D_
} catch (err) {_x000D_
return false;_x000D_
}_x000D_
})(req.responseText);_x000D_
_x000D_
if (!json)_x000D_
return false;_x000D_
_x000D_
document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
Read more :
I've written a simple jQuery plugin - alterClass, that does wildcard class removal. Will optionally add classes too.
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
We can do this by css3 too. Try this:
.halfsize {
-moz-transform:scale(0.5);
-webkit-transform:scale(0.5);
transform:scale(0.5);
}
<img class="halfsize" src="image4.jpg">
Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:
sell_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_edit"
android:icon="@drawable/ic_edit_white_shadow_24dp"
app:showAsAction="always"
android:title="Edit" />
<item
android:id="@+id/action_delete"
android:icon="@drawable/ic_delete_white_shadow_24dp"
app:showAsAction="always"
android:title="Delete" />
Now Override the two method in your activity & make a field variable mMenu as:
private Menu mMenu; // field variable
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.sell_menu, menu);
this.mMenu = menu;
menu.findItem(R.id.action_delete).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
// do action
return true;
} else if (item.getItemId() == R.id.action_edit) {
// do action
return true;
}
return super.onOptionsItemSelected(item);
}
Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:
public void showDeleteImageOption(boolean status) {
if (menu != null) {
menu.findItem(R.id.action_delete).setVisible(status);
}
}
public void showEditImageOption(boolean status) {
if (menu != null) {
menu.findItem(R.id.action_edit).setVisible(status);
}
}
That's Solve from my side,I think this explanation will help you.
for me, the best approach is remove border of the textbox, and place it inside a Panel, which can be customized as you like.
1.) Never use MESH COLLIDER. Use combination of box and capsule collider.
2.) Check constraints in RigidBody. If you tick Freeze Position X than it will pass through the object on the X axis. (Same for y axis).
A is the key, max(date) is the value, we might simplify the query as below:
SELECT distinct A, max(date) over (partition by A)
FROM TABLENAME
I would suggest not using pixels for sWidth, instead use percentages. Like below:
"aoColumnDefs": [
{ "sWidth": "20%", "aTargets": [ 0 ] }, <- start from zero
{ "sWidth": "5%", "aTargets": [ 1 ] },
{ "sWidth": "10%", "aTargets": [ 2 ] },
{ "sWidth": "5%", "aTargets": [ 3 ] },
{ "sWidth": "40%", "aTargets": [ 4 ] },
{ "sWidth": "5%", "aTargets": [ 5 ] },
{ "sWidth": "15%", "aTargets": [ 6 ] }
],
aoColumns : [
{ "sWidth": "20%"},
{ "sWidth": "5%"},
{ "sWidth": "10%"},
{ "sWidth": "5%"},
{ "sWidth": "40%"},
{ "sWidth": "5%"},
{ "sWidth": "15%"}
]
});
Hope it helps.
Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);
Check if the session is empty or not in C# MVC Version Lower than 5.
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//cast it and use it
//business logic
}
Check if the session is empty or not in C# MVC Version Above 5.
if(Session["emp_num"] != null)
{
//cast it and use it
//business logic
}
Final(?) edit
Answer, wrapped up in a function, with annotated interactive session:
>>> import re
>>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):
... return not bool(search(strg))
...
>>> special_match("")
True
>>> special_match("az09.")
True
>>> special_match("az09.\n")
False
# The above test case is to catch out any attempt to use re.match()
# with a `$` instead of `\Z` -- see point (6) below.
>>> special_match("az09.#")
False
>>> special_match("az09.X")
False
>>>
Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.
==== Earlier text ====
The [previously] accepted answer could use a few improvements:
(1) Presentation gives the appearance of being the result of an interactive Python session:
reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True
but match() doesn't return True
(2) For use with match(), the ^
at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the ^
(3) Should foster the use of raw string automatically unthinkingly for any re pattern
(4) The backslash in front of the dot/period is redundant
(5) Slower than the OP's code!
prompt>rem OP's version -- NOTE: OP used raw string!
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9\.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.43 usec per loop
prompt>rem OP's version w/o backslash
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.44 usec per loop
prompt>rem cleaned-up version of accepted answer
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[a-z0-9.]+\Z')" "bool(reg.match(t))"
100000 loops, best of 3: 2.07 usec per loop
prompt>rem accepted answer
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile('^[a-z0-9\.]+$')" "bool(reg.match(t))"
100000 loops, best of 3: 2.08 usec per loop
(6) Can produce the wrong answer!!
>>> import re
>>> bool(re.compile('^[a-z0-9\.]+$').match('1234\n'))
True # uh-oh
>>> bool(re.compile('^[a-z0-9\.]+\Z').match('1234\n'))
False
I couldn't always use pointer-events: none
in my scenario, because I wanted both the overlay and the underlying element(s) to be clickable / selectable.
The DOM structure looked like this:
<div id="outerElement">
<div id="canvas-wrapper">
<canvas id="overlay"></canvas>
</div>
<!-- Omitted: element(s) behind canvas that should still be selectable -->
</div>
(The outerElement
, canvas-wrapper
and canvas
elements have the same size.)
To make the elements behind the canvas act normally (e.g. selectable, editable), I used the following code:
canvasWrapper.style.pointerEvents = 'none';
outerElement.addEventListener('mousedown', event => {
const clickedOnElementInCanvas = yourCheck // TODO: check if the event *would* click a canvas element.
if (!clickedOnElementInCanvas) {
// if necessary, add logic to deselect your canvas elements ...
wrapper.style.pointerEvents = 'none';
return true;
}
// Check if we emitted the event ourselves (avoid endless loop)
if (event.isTrusted) {
// Manually forward element to the canvas
const mouseEvent = new MouseEvent(event.type, event);
canvas.dispatchEvent(mouseEvent);
mouseEvent.stopPropagation();
}
return true;
});
Some canvas objects also came with input fields, so I had to allow keyboard events, too.
To do this, I had to update the pointerEvents
property based on whether a canvas input field was currently focused or not:
onCanvasModified(canvas, () => {
const inputFieldInCanvasActive = // TODO: Check if an input field of the canvas is active.
wrapper.style.pointerEvents = inputFieldInCanvasActive ? 'auto' : 'none';
});
If you only have to support modern browsers, you can get away with:
You only need to convert the number to a class
, e.g. class='stars-score-50'
.
First a demo of "rendered" markup:
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: gold;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
Within block level elements:_x000D_
_x000D_
<div><span class="stars-container stars-0">?????</span></div>_x000D_
<div><span class="stars-container stars-10">?????</span></div>_x000D_
<div><span class="stars-container stars-20">?????</span></div>_x000D_
<div><span class="stars-container stars-30">?????</span></div>_x000D_
<div><span class="stars-container stars-40">?????</span></div>_x000D_
<div><span class="stars-container stars-50">?????</span></div>_x000D_
<div><span class="stars-container stars-60">?????</span></div>_x000D_
<div><span class="stars-container stars-70">?????</span></div>_x000D_
<div><span class="stars-container stars-80">?????</span></div>_x000D_
<div><span class="stars-container stars-90">?????</span></div>_x000D_
<div><span class="stars-container stars-100">?????</span></div>_x000D_
_x000D_
<p>Or use it in a sentence: <span class="stars-container stars-70">?????</span> (cool, huh?).</p>
_x000D_
Then a demo that uses a wee bit of code:
$(function() {_x000D_
function addScore(score, $domElement) {_x000D_
$("<span class='stars-container'>")_x000D_
.addClass("stars-" + score.toString())_x000D_
.text("?????")_x000D_
.appendTo($domElement);_x000D_
}_x000D_
_x000D_
addScore(70, $("#fixture"));_x000D_
});
_x000D_
body { font-size: 18px; }_x000D_
_x000D_
.stars-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
.stars-container:before {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: lightgray;_x000D_
}_x000D_
_x000D_
.stars-container:after {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
content: '?????';_x000D_
color: gold;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.stars-0:after { width: 0%; }_x000D_
.stars-10:after { width: 10%; }_x000D_
.stars-20:after { width: 20%; }_x000D_
.stars-30:after { width: 30%; }_x000D_
.stars-40:after { width: 40%; }_x000D_
.stars-50:after { width: 50%; }_x000D_
.stars-60:after { width: 60%; }_x000D_
.stars-70:after { width: 70%; }_x000D_
.stars-80:after { width: 80%; }_x000D_
.stars-90:after { width: 90%; }_x000D_
.stars-100:after { width: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
Generated: <div id="fixture"></div>
_x000D_
The biggest downsides of this solution are:
width
on a pseudo-element).To fix this the solution above can be easily tweaked. The :before
and :after
bits need to become actual elements in the DOM (so we need some JS for that).
The latter is left as an excercise for the reader.
Structs can have functions just like classes. The only difference is that they are public by default:
struct A {
void f() {}
};
Additionally, structs can also have constructors and destructors.
struct A {
A() : x(5) {}
~A() {}
private: int x;
};
Add the below dependency to your pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
In addition to @CB Bailey's answer:
I tried to remove multiple folders (in subfolders) named et-cache
(caching folder from Wordpress divi theme) from the index and from being tracked.
I added
et-cache/
to the .gitignore
file. But
git rm -r --cached et-cache
resulted in an error:
fatal: pathspec 'et-cache' did not match any files
So the solution was to use powershell:
Get-ChildItem et-cache -Recurse |% {git rm -r --cached $_.FullName}
This searches for all subfolders named et-cache. Each of the folders path (fullname) is then used to remove it from tracking in git.
You can change the user with
Subversion 1.6 and earlier:
svn switch --relocate protocol://currentUser@server/path protocol://newUser@server/path
Subversion 1.7 and later:
svn relocate protocol://currentUser@server/path protocol://newUser@server/path
To find out what protocol://currentUser@server/path
is, run
svn info
in your working copy.
It is much more accurate to use IndexOf:
If dt.Columns.IndexOf("ColumnName") = -1 Then
'Column not exist
End If
If the Contains is used it would not differentiate between ColumName and ColumnName2.
Make sure you make it as a separate component I have used tabler-react
import * as React from "react";
import { Page, Button } from "tabler-react";
class PaginateComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
limit: 5, // optional
page: 1
};
}
paginateValue = (page) => {
this.setState({ page: page });
console.log(page) // access this value from parent component
}
paginatePrevValue = (page) => {
this.setState({ page: page });
console.log(page) // access this value from parent component
}
paginateNxtValue = (page) => {
this.setState({ page: page });
console.log(page) // access this value from parent component
}
render() {
return (
<div>
<div>
<Button.List>
<Button
disabled={this.state.page === 0}
onClick={() => this.paginatePrevValue(this.state.page - 1)}
outline
color="primary"
>
Previous
</Button>
{this.state.array.map((value, index) => {
return (
<Button
onClick={() => this.paginateValue(value)}
color={
this.state.page === value
? "primary"
: "secondary"
}
>
{value}
</Button>
);
})}
<Button
onClick={() => this.paginateNxtValue(this.state.page + 1)}
outline
color="secondary"
>
Next
</Button>
</Button.List>
</div>
</div>
)
}
}
export default PaginateComponent;
As described in the answer of Ricardo ,
netsh Winsock reset
has worked for me ,
P.S. if you have Internet download manager or such programs which changes you IP Setting is installed then after running this command when you reboot your computer IDM will ask to change setting , Set NO in this case and then run your application it will work correctly.
Hope it
To get the actual height of the Actionbar, you have to resolve the attribute actionBarSize
at runtime.
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);
The way I am doing it my code is to make an extension of UIFont: (This is Swift 4.1)
extension UIFont {
public func textWidth(s: String) -> CGFloat
{
return s.size(withAttributes: [NSAttributedString.Key.font: self]).width
}
} // extension UIFont
To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.
To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.
var rotated = false;
document.getElementById('button').onclick = function() {
var div = document.getElementById('div'),
deg = rotated ? 0 : 66;
div.style.webkitTransform = 'rotate('+deg+'deg)';
div.style.mozTransform = 'rotate('+deg+'deg)';
div.style.msTransform = 'rotate('+deg+'deg)';
div.style.oTransform = 'rotate('+deg+'deg)';
div.style.transform = 'rotate('+deg+'deg)';
rotated = !rotated;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
To add some animation to the rotation all we have to do is add CSS transitions
div {
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
var div = document.getElementById('div'),_x000D_
deg = rotated ? 0 : 66;_x000D_
_x000D_
div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.mozTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.msTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.oTransform = 'rotate('+deg+'deg)'; _x000D_
div.style.transform = 'rotate('+deg+'deg)'; _x000D_
_x000D_
rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript
document.getElementById('button').onclick = function() {
document.getElementById('div').classList.toggle('rotated');
}
document.getElementById('button').onclick = function() {_x000D_
document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
position:relative; _x000D_
height: 200px; _x000D_
width: 200px; _x000D_
margin: 30px;_x000D_
background: red;_x000D_
-webkit-transition: all 0.5s ease-in-out;_x000D_
-moz-transition: all 0.5s ease-in-out;_x000D_
-o-transition: all 0.5s ease-in-out;_x000D_
transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
-webkit-transform : rotate(66deg); _x000D_
-moz-transform : rotate(66deg); _x000D_
-ms-transform : rotate(66deg); _x000D_
-o-transform : rotate(66deg); _x000D_
transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
I can see people giving lots of comments on this question. But I think, simple use of LIKE
could be easier to get the data from the table.
SELECT * FROM table WHERE COLUMN LIKE '2013-05-11%'
Use LIKE
and post data wild character search. Hopefully this will solve your problem.
I came around the same problem as the OP, and trying some solutions from the top answers above didn't prove to work for my scenarios. See why at the end.
Instead, I found this helpful script, to avoid confusion let's call it html2text_roundcube
, available under GPL:
It's actually an updated version of an already mentioned script - http://www.chuggnutt.com/html2text.php
- updated by RoundCube mail.
Usage:
$h2t = new \Html2Text\Html2Text('Hello, "<b>world</b>"');
echo $h2t->getText(); // prints Hello, "WORLD"
Why html2text_roundcube
proved better than the others:
Script http://www.chuggnutt.com/html2text.php
didn't work out of the box for cases with special HTML codes/names (eg ä
), or unpaired quotes (eg <p>25" Monitor</p>
).
Script https://github.com/soundasleep/html2text
had no option to hide or group the links at the end of the text, making a usual HTML page look bloated with links when in text-plain format; customizing the code for special treatment of how the transformation is done is not as straight forward as simply editing an array in html2text_roundcube
.
To assign value of a text box whose id is "textbox" in JQuery please do the following
$("#textbox").get(0).value = "blah"
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print(df)
yields
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
but this only works if you want every float to be formatted with a dollar sign.
Otherwise, if you want dollar formatting for some floats only, then I think you'll have to pre-modify the dataframe (converting those floats to strings):
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df['foo'] = df['cost']
df['cost'] = df['cost'].map('${:,.2f}'.format)
print(df)
yields
cost foo
foo $123.46 123.4567
bar $234.57 234.5678
baz $345.68 345.6789
quux $456.79 456.7890
Try this:
>> a = "Smith"
>> a[0]
=> "S"
OR
>> "Smith".chr
#=> "S"
In my case I was using more than two variables, and this worked for me better:
cor(x = as.matrix(tbl), method = "pearson", use = "pairwise.complete.obs")
However:
If use has the value "pairwise.complete.obs" then the correlation or covariance between each pair of variables is computed using all complete pairs of observations on those variables. This can result in covariance or correlation matrices which are not positive semi-definite, as well as NA entries if there are no complete pairs for that pair of variables.
The Kotlin
way by using builtin Extension function on File
Write: yourFile.writeText(textFromEditText)
Read: yourFile.readText()
I had the same question, and I tested 3 main solution :
(df != null) && (df.count > 0)
df.head(1).isEmpty()
as @hulin003 suggestdf.rdd.isEmpty()
as @Justin Pihony suggestand of course the 3 works, however in term of perfermance, here is what I found, when executing the these methods on the same DF in my machine, in terme of execution time :
therefore I think that the best solution is df.rdd.isEmpty()
as @Justin Pihony suggest
function converter()
{
var number = $(.number).text();
var number = 'Rp. '+number;
s(.number).val(number);
}
In my case the solution was quite simple. I added this header and the browsers opened the file in every test. header('Content-Disposition: attachment; filename="filename.pdf"');
The accepted answer has some gotchas. For example:
>>> a = [{}] * 3
>>> a
[{}, {}, {}]
>>> a[0]['hello'] = 5
>>> a
[{'hello': 5}, {'hello': 5}, {'hello': 5}]
>>>
So each dictionary refers to the same object. Same holds true if you initialize with arrays or objects.
You could do this instead:
>>> b = [{} for i in range(0, 3)]
>>> b
[{}, {}, {}]
>>> b[0]['hello'] = 6
>>> b
[{'hello': 6}, {}, {}]
>>>
use \\:
instead of \:
.. the \
has special meaning in java strings.
Here is something that might help someone looking for this answer: The following uses jquery it searches the whole document and only replaces the text. for example if we had
<a href="/i-am/123/a/overpopulation">overpopulation</a>
and we wanted to add a span with the class overpop around the word overpopulation
<a href="/i-am/123/a/overpopulation"><span class="overpop">overpopulation</span></a>
we would run the following
$("*:containsIN('overpopulation')").filter(
function() {
return $(this).find("*:contains('" + str + "')").length == 0
}
).html(function(_, html) {
if (html != 'undefined') {
return html.replace(/(overpopulation)/gi, '<span class="overpop">$1</span>');
}
});
the search is case insensitive searches the whole document and only replaces the text portions in this case we are searching for the string 'overpopulation'
$.extend($.expr[":"], {
"containsIN": function(elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
The functions in stdlib.h
and stdio.h
have implementations in libc.so
(or libc.a
for static linking), which is linked into your executable by default (as if -lc
were specified). GCC can be instructed to avoid this automatic link with the -nostdlib
or -nodefaultlibs
options.
The math functions in math.h
have implementations in libm.so
(or libm.a
for static linking), and libm
is not linked in by default. There are historical reasons for this libm
/libc
split, none of them very convincing.
Interestingly, the C++ runtime libstdc++
requires libm
, so if you compile a C++ program with GCC (g++
), you will automatically get libm
linked in.
I stumbled in the same problem while working on a web api Asp Net Core project. I followed the suggestion to change the reference in my code to:
ConfigurationManager.ConnectionStrings["NameOfTheConnectionString"].ConnectionString
but adding the reference to System.Configuration.dll caused the error "Reference not valid or not supported".
To fix the problem I had to download the package System.Configuration.ConfigurationManager using NuGet (Tools -> Nuget Package-> Manage Nuget packages for the solution)
Most of the answers don't cover cases where there is more than 24h. This one does. I suggest extending Date object:
class SuperDate extends Date {_x000D_
get raceTime() {_x000D_
return Math.floor(this/36e5).toString().padStart(2,'0')_x000D_
+ this.toISOString().slice(13, -1)_x000D_
}_x000D_
}_x000D_
_x000D_
console.log('marathon', new SuperDate(11235200).raceTime)_x000D_
console.log('ironman', new SuperDate(40521100).raceTime)_x000D_
console.log('spartathlon', new SuperDate(116239000).raceTime)_x000D_
console.log('epoch', new SuperDate(new Date()).raceTime)
_x000D_
This approach works great with Firestore Timestamp objects which are similar to what you need:
class SuperDate extends Date {_x000D_
fromFirestore (timestamp) {_x000D_
return new SuperDate(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000)_x000D_
}_x000D_
get raceTime() {_x000D_
return Math.floor(this/36e5).toString().padStart(2,'0')_x000D_
+ this.toISOString().slice(13, -1)_x000D_
}_x000D_
}_x000D_
_x000D_
const timestamp = {seconds: 11235, nanoseconds: 200000000}_x000D_
_x000D_
console.log('timestamp', new SuperDate().fromFirestore(timestamp))_x000D_
console.log('marathon', new SuperDate().fromFirestore(timestamp).raceTime)
_x000D_
According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f
will be true only if f is NaN.
Note that, as some comments below have pointed out, not all compilers respect this when optimizing code.
For any compiler which claims to use IEEE floating point, this trick should work. But I can't guarantee that it will work in practice. Check with your compiler, if in doubt.
Isn't it just: System.out.println(Array.length);
? Because this is what it seems like you are looking for.
Every time you used the mysql console, the version is shown.
mysql -u user
Successful console login shows the following which includes the mysql server version.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1432
Server version: 5.5.9-log Source distribution
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
You can also check the mysql server version directly by executing the following command:
mysql --version
You may also check the version information from the mysql console itself using the version variables:
mysql> SHOW VARIABLES LIKE "%version%";
Output will be something like this:
+-------------------------+---------------------+
| Variable_name | Value |
+-------------------------+---------------------+
| innodb_version | 1.1.5 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.9-log |
| version_comment | Source distribution |
| version_compile_machine | i386 |
| version_compile_os | osx10.4 |
+-------------------------+---------------------+
7 rows in set (0.01 sec)
You may also use this:
mysql> select @@version;
The STATUS command display version information as well.
mysql> STATUS
You can also check the version by executing this command:
mysql -v
It's worth mentioning that if you have encountered something like this:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket
'/tmp/mysql.sock' (2)
you can fix it by:
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock
Reading the documentation, there is a way to pop the back stack based on either the transaction name or the id provided by commit. Using the name may be easier since it shouldn't require keeping track of a number that may change and reinforces the "unique back stack entry" logic.
Since you want only one back stack entry per Fragment
, make the back state name the Fragment's class name (via getClass().getName()
). Then when replacing a Fragment
, use the popBackStackImmediate()
method. If it returns true, it means there is an instance of the Fragment in the back stack. If not, actually execute the Fragment replacement logic.
private void replaceFragment (Fragment fragment){
String backStateName = fragment.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(backStateName);
ft.commit();
}
}
EDIT
The problem is - when i launch A and then B, then press back button, B is removed and A is resumed. and pressing again back button should exit the app. But it is showing a blank window and need another press to close it.
This is because the FragmentTransaction
is being added to the back stack to ensure that we can pop the fragments on top later. A quick fix for this is overriding onBackPressed()
and finishing the Activity if the back stack contains only 1 Fragment
@Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() == 1){
finish();
}
else {
super.onBackPressed();
}
}
Regarding the duplicate back stack entries, your conditional statement that replaces the fragment if it hasn't been popped is clearly different than what my original code snippet's. What you are doing is adding to the back stack regardless of whether or not the back stack was popped.
Something like this should be closer to what you want:
private void replaceFragment (Fragment fragment){
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content_frame, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
The conditional was changed a bit since selecting the same fragment while it was visible also caused duplicate entries.
Implementation:
I highly suggest not taking the the updated replaceFragment()
method apart like you did in your code. All the logic is contained in this method and moving parts around may cause problems.
This means you should copy the updated replaceFragment()
method into your class then change
backStateName = fragmentName.getClass().getName();
fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
ft.replace(R.id.content_frame, fragmentName);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
so it is simply
replaceFragment (fragmentName);
EDIT #2
To update the drawer when the back stack changes, make a method that accepts in a Fragment and compares the class names. If anything matches, change the title and selection. Also add an OnBackStackChangedListener
and have it call your update method if there is a valid Fragment.
For example, in the Activity's onCreate()
, add
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);
if (f != null){
updateTitleAndDrawer (f);
}
}
});
And the other method:
private void updateTitleAndDrawer (Fragment fragment){
String fragClassName = fragment.getClass().getName();
if (fragClassName.equals(A.class.getName())){
setTitle ("A");
//set selected item position, etc
}
else if (fragClassName.equals(B.class.getName())){
setTitle ("B");
//set selected item position, etc
}
else if (fragClassName.equals(C.class.getName())){
setTitle ("C");
//set selected item position, etc
}
}
Now, whenever the back stack changes, the title and checked position will reflect the visible Fragment
.
Use URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var data = new URLSearchParams();
data.append('userName', '[email protected]');
data.append('password', 'Password');
data.append('grant_type', 'password');
to_date
format worked for me. Please consider the date formats:
MON-
, MM
, .
, -
.
t.start_date >= to_date('14.11.2016 04:01:39', 'DD.MM.YYYY HH24:MI:SS')
t.start_date <=to_date('14.11.2016 04:10:07', 'DD.MM.YYYY HH24:MI:SS')
This function uses the current millisecond time to subtract the current week, and then subtracts one more week if the current date is on a monday (javascript counts from sunday).
function getMonday(fromDate) {
// length of one day i milliseconds
var dayLength = 24 * 60 * 60 * 1000;
// Get the current date (without time)
var currentDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
// Get the current date's millisecond for this week
var currentWeekDayMillisecond = ((currentDate.getDay()) * dayLength);
// subtract the current date with the current date's millisecond for this week
var monday = new Date(currentDate.getTime() - currentWeekDayMillisecond + dayLength);
if (monday > currentDate) {
// It is sunday, so we need to go back further
monday = new Date(monday.getTime() - (dayLength * 7));
}
return monday;
}
I have tested it when week spans over from one month to another (and also years), and it seems to work properly.
You can do it :
chmod +x PATH_TO_YOUR_SCRIPT/start_my_app
then use this command
update-rc.d start_my_app defaults 100
Please see this page on Cyberciti.
In could able to resolve this issue with giving username and password in below url.
Please replace username and password with your Github credentials:
git remote set-url origin https://<username>:<password>@github.com/<username>/FirstRepository.git
It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga
faulthandler.enable()
// bad code goes here
or
$ python3 -q -X faulthandler
>>> /// bad cod goes here
Ok @Adam and @Kimvais were right, paramiko cannot parse .ppk files.
So the way to go (thanks to @JimB too) is to convert .ppk file to openssh private key format; this can be achieved using Puttygen as described here.
Then it's very simple getting connected with it:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()
I had similar problem while installing SQL Server 2005 on Windows 7 Professional and got error SQL server failed to start
. I logged in as a Administrator (my user id is administrator) in windows.
SOLUTION
Go to services, from control panel -> Administrative Tools
Click on properties of "SQL Server (MSSQLSERVER)"
Go to Log On Tab, Select "This Account"
Enter your windows login detail (administrator and password)
Start the service manually, it should work fine..
Hope this too helps..
go to the modal-dialog
div and add
style="width:70%"
depending on the size you want
For a long time, CMake had the add_definitions
command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options).
An example using the new add_compile_definitions:
add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
add_compile_definitions(WITH_OPENCV2)
Or:
add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)
The good part about this is that it circumvents the shabby trickery CMake has in place for add_definitions
. CMake is such a shabby system, but they are finally finding some sanity.
Find more explanation on which commands to use for compiler flags here: https://cmake.org/cmake/help/latest/command/add_definitions.html
Likewise, you can do this per-target as explained in Jim Hunziker's answer.
If access modifier of base class member function is protected OR public, you can do call member function of base class from derived class. Call to the base class non-virtual and virtual member function from derived member function can be made. Please refer the program.
#include<iostream>
using namespace std;
class Parent
{
protected:
virtual void fun(int i)
{
cout<<"Parent::fun functionality write here"<<endl;
}
void fun1(int i)
{
cout<<"Parent::fun1 functionality write here"<<endl;
}
void fun2()
{
cout<<"Parent::fun3 functionality write here"<<endl;
}
};
class Child:public Parent
{
public:
virtual void fun(int i)
{
cout<<"Child::fun partial functionality write here"<<endl;
Parent::fun(++i);
Parent::fun2();
}
void fun1(int i)
{
cout<<"Child::fun1 partial functionality write here"<<endl;
Parent::fun1(++i);
}
};
int main()
{
Child d1;
d1.fun(1);
d1.fun1(2);
return 0;
}
Output:
$ g++ base_function_call_from_derived.cpp
$ ./a.out
Child::fun partial functionality write here
Parent::fun functionality write here
Parent::fun3 functionality write here
Child::fun1 partial functionality write here
Parent::fun1 functionality write here
The and operator in a selector is just an empty string, and the or operator is the comma.
There is however no grouping or priority, so you have to repeat one of the conditions:
a=$('[myc=blue][myid="1"],[myc=blue][myid="3"]');
you may also do
git pull -r origin master
fix merge conflicts if any
git rebase --continue
-r is for rebase. This will make you branch structure from
v master
o-o-o-o-o
\o-o-o
^ other branch
to
v master
o-o-o-o-o-o-o-o
^ other branch
This will lead to a cleaner history. Note: In case you have already pushed your other-branch to origin( or any other remote), you may have to force push your branch after rebase.
git push -f origin other-branch
The beauty of String(format:) is that you can save a formatting string and then reuse it later in dozen of places. It also can be localized in this single place. Where as in case of the interpolation approach you must write it again and again.
Just copy the array. There are many ways to do that:
function sort(arr) {
return arr.concat().sort();
}
// Or:
return Array.prototype.slice.call(arr).sort(); // For array-like objects
What does $rootScope.$broadcast
do?
$rootScope.$broadcast
is sending an event through the application scope.
Any children scope of that app can catch it using a simple: $scope.$on()
.
It is especially useful to send events when you want to reach a scope that is not a direct parent (A branch of a parent for example)
!!! One thing to not do however is to use $rootScope.$on
from a controller. $rootScope
is the application, when your controller is destroyed that event listener will still exist, and when your controller will be created again, it will just pile up more event listeners. (So one broadcast will be caught multiple times). Use $scope.$on()
instead, and the listeners will also get destroyed.
What is the difference between $rootScope.$broadcast
& $rootScope.$broadcast.apply
?
Sometimes you have to use apply()
, especially when working with directives and other JS libraries. However since I don't know that code base, I wouldn't be able to tell if that's the case here.
You can use .closest()
to get up to the current <tr>
parent, like this:
$('input[type=button]' ).click(function() {
var bid = this.id; // button ID
var trid = $(this).closest('tr').attr('id'); // table row ID
});
using bootstrap you can have a responsive and mobile first embeded file.
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="address of your file" allowfullscreen></iframe>
</div>
Aspect ratios can be customized with modifier classes.
<!-- 21:9 aspect ratio -->
<div class="embed-responsive embed-responsive-21by9">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
<!-- 1:1 aspect ratio -->
<div class="embed-responsive embed-responsive-1by1">
<iframe class="embed-responsive-item" src="..."></iframe>
</div>
We must define the behavior configuration to REST endpoint
<endpointBehaviors>
<behavior name="restfulBehavior">
<webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
</behavior>
</endpointBehaviors>
and also to a service
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
After the behaviors, next step is the bindings. For example basicHttpBinding to SOAP endpoint and webHttpBinding to REST.
<bindings>
<basicHttpBinding>
<binding name="soapService" />
</basicHttpBinding>
<webHttpBinding>
<binding name="jsonp" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
Finally we must define the 2 endpoint in the service definition. Attention for the address="" of endpoint, where to REST service is not necessary nothing.
<services>
<service name="ComposerWcf.ComposerService">
<endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
<endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
<endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
</service>
</services>
In Interface of the service we define the operation with its attributes.
namespace ComposerWcf.Interface
{
[ServiceContract]
public interface IComposerService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/autenticationInfo/{app_id}/{access_token}", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);
}
}
Joining all parties, this will be our WCF system.serviceModel definition.
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="restfulBehavior">
<webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="soapService" />
</basicHttpBinding>
<webHttpBinding>
<binding name="jsonp" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="ComposerWcf.ComposerService">
<endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
<endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
<endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
To test the both endpoint, we can use WCFClient to SOAP and PostMan to REST.
You can rename classes or any file by hitting F2 on the filename in Eclipse. It will ask you if you want to update references. It's really as easy as that :)
Use this in your conda prompt:
python -m pip install xgboost
Use the entity code  
instead.
is a HTML "character entity reference". There is no named entity for non-breaking space in XML, so you use the code  
.
Wikipedia includes a list of XML and HTML entities, and you can see that there are only 5 "predefined entities" in XML, but HTML has over 200. I'll also point over to Creating a space ( ) in XSL which has excellent answers.
SingleOrDefault
method throws an Exception
if there is more than one element in the sequence.
Apparently, your query in GetCustomer
is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.
Text boxes in worksheets are sometimes not updated when their text or formatting is changed, and even the DoEvent command does not help.
As there is no command in Excel to refresh a worksheet in the way a user form can be refreshed, it is necessary to use a trick to force Excel to update the screen.
The following commands seem to do the trick:
- ActiveSheet.Calculate
- ActiveWindow.SmallScroll
- Application.WindowState = Application.WindowState
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "yourcustomaddress/bundles/andreistatistics/css/like.css"
});
css_link.appendTo('head');
WHERE id <> 2
should work fine...Is that what you are after?
This is a tool to open Java class file binaries, view their internal structure, modify portions of it if required and save the class file back. It also generates readable reports similar to the javap utility. Easy to use Java Swing GUI. The user interface tries to display as much detail as possible and tries to present a structure as close as the actual Java class file structure. At the same time ease of use and class file consistency while doing modifications is also stressed. For example, when a method is deleted, the associated constant pool entry will also be deleted if it is no longer referenced. In built verifier checks changes before saving the file. This tool has been used by people learning Java class file internals. This tool has also been used to do quick modifications in class files when the source code is not available." this is a quote from the website.
You might want to use \n
instead of /n
.
Use:
String str = "whatever";
str = str.replaceAll("[,.]", "");
replaceAll takes a regular expression. This:
[,.]
...looks for each comma and/or period.
The existing answers all seem to run this script in a DOS console window.
This may be acceptable, but for example means that colour codes (changing text colour) don't work but instead get printed out as they are:
there is no item "[032mGroovy[0m"
I found this solution some time ago, so I'm not sure whether mintty.exe
is a standard Cygwin utility or whether you have to run the setup
program to get it, but I run like this:
D:\apps\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico bash.exe .\myShellScript.sh
... this causes the script to run in a Cygwin BASH console instead of a Windows DOS console.
Small refinement to the previous answers: To make longer lines more readable if they spill over to additional screen lines:
ul, li {list-style-type: none;}
li {padding-left: 2em; text-indent: -2em;}
There should be a binary called "pip2.7" installed at some location included within your $PATH variable.
You can find that out by typing
which pip2.7
This should print something like '/usr/local/bin/pip2.7' to your stdout. If it does not print anything like this, it is not installed. In that case, install it by running
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2.7 get-pip.py
Now, you should be all set, and
which pip2.7
should return the correct output.
Are you mixing C and C++? One issue that can occur is that the declarations in the .h
file for a .c
file need to be surrounded by:
#if defined(__cplusplus)
extern "C" { // Make sure we have C-declarations in C++ programs
#endif
and:
#if defined(__cplusplus)
}
#endif
Note: if unable / unwilling to modify the .h
file(s) in question, you can surround their inclusion with extern "C"
:
extern "C" {
#include <abc.h>
} //extern
Empty
refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty
then it would return true.
IsEmpty
refers to no value being initialized.
In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty
. If you want to see if something is currently in its default value then use Empty
.
I think style no. 111 (Japan) should work:
SELECT CONVERT(DATETIME, '2012-08-17', 111)
And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD
) which works for any language and date format setting in SQL Server:
SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)
Check out the COPY command of Postgres:
the code provided didn't work for me. I found another way to Map :
MapElements :
package com.cellfish.mediadb.rest.lucene;
import javax.xml.bind.annotation.XmlElement;
class MapElements
{
@XmlElement public String key;
@XmlElement public Integer value;
private MapElements() {} //Required by JAXB
public MapElements(String key, Integer value)
{
this.key = key;
this.value = value;
}
}
MapAdapter :
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.adapters.XmlAdapter;
class MapAdapter extends XmlAdapter<MapElements[], Map<String, Integer>> {
public MapElements[] marshal(Map<String, Integer> arg0) throws Exception {
MapElements[] mapElements = new MapElements[arg0.size()];
int i = 0;
for (Map.Entry<String, Integer> entry : arg0.entrySet())
mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());
return mapElements;
}
public Map<String, Integer> unmarshal(MapElements[] arg0) throws Exception {
Map<String, Integer> r = new HashMap<String, Integer>();
for (MapElements mapelement : arg0)
r.put(mapelement.key, mapelement.value);
return r;
}
}
The rootElement :
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
public class Root {
private Map<String, Integer> mapProperty;
public Root() {
mapProperty = new HashMap<String, Integer>();
}
@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, Integer> getMapProperty() {
return mapProperty;
}
public void setMapProperty(Map<String, Integer> map) {
this.mapProperty = map;
}
}
I found the code in this website : http://www.developpez.net/forums/d972324/java/general-java/xml/hashmap-jaxb/
$(function(){
$("#id").keypress(function() {
var maxlen = 100;
if ($(this).val().length > maxlen) {
return false;
}
})
});
I like the solution from
http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/
public class Dada<T> {
private Class<T> typeOfT;
@SuppressWarnings("unchecked")
public Dada() {
this.typeOfT = (Class<T>)
((ParameterizedType)getClass()
.getGenericSuperclass())
.getActualTypeArguments()[0];
}
...
<input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">
export class InformationSectionComponent {
formname = this.formbuilder.group({
firstname: ['']
});
}
Enable whole form
this.formname.enable();
Enable particular field alone
this.formname.controls.firstname.enable();
same for disable, replace enable() with disable().
This Works fine. Comment for queries.
Try to assign the image that way instead:
imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));
Microsoft Network Monitor (http://www.microsoft.com/downloads/details.aspx?FamilyID=983b941d-06cb-4658-b7f6-3088333d062f)
I had the following scenario that was causing the same error:
Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.
It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":
using (var wc = new WebClient())
{
var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
tskResult.Wait();
}
If you need only display the trimmed value then I'd suggest against manipulating the original string and using a filter instead.
app.filter('trim', function () {
return function(value) {
if(!angular.isString(value)) {
return value;
}
return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
};
});
And then
<span>{{ foo | trim }}</span>
You need to join the two tables:
select p.id, p.first, p.middle, p.last, p.age,
a.id as address_id, a.street, a.city, a.state, a.zip
from Person p inner join Address a on p.id = a.person_id
where a.zip = '97229';
This will select all of the columns from both tables. You could of course limit that by choosing different columns in the select
clause.
this will subtract ten days of the current date (before Java 8):
int x = -10;
Calendar cal = GregorianCalendar.getInstance();
cal.add( Calendar.DAY_OF_YEAR, x);
Date tenDaysAgo = cal.getTime();
If you're using Java 8 you can make use of the new Date & Time API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html):
LocalDate tenDaysAgo = LocalDate.now().minusDays(10);
For converting the new to the old types and vice versa see: Converting between java.time.LocalDateTime and java.util.Date
select2
has the placeholder
parameter. Use that one
$("#state").select2({
placeholder: "Choose a Country"
});
getting logged in username: System.Web.HttpContext.Current.User.Identity.Name
ht editor can disassemble binaries in many formats. It is similar to Hiew, but open source.
To disassemble, open a binary, then press F6 and then select elf/image.
One way is to use window.print() function. Which does not require any library
Pros
1.No external library require.
2.We can print only selected parts of body also.
3.No css conflicts and js issues.
4.Core html/js functionality
---Simply add below code
CSS to
@media print {
body * {
visibility: hidden; // part to hide at the time of print
-webkit-print-color-adjust: exact !important; // not necessary use
if colors not visible
}
#printBtn {
visibility: hidden !important; // To hide
}
#page-wrapper * {
visibility: visible; // Print only required part
text-align: left;
-webkit-print-color-adjust: exact !important;
}
}
JS code - Call bewlow function on btn click
$scope.printWindow = function () {
window.print()
}
Note: Use !important in every css object
Example -
.legend {
background: #9DD2E2 !important;
}
print "financial return of outcome 1 = $%.2f" % (out1)
git branch --set-upstream <<origin/branch>>
is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>
To check the accurate usage for your services be it is free (as per always free or 12 months free) or Pay-As-You-Go, it is important to monitor the usage so that you know upfront on the cost incurred or when to upgrade your service tier.
To check your free service usage and its limits, Go to search in Portal, search with "Subscription" and click on it. you will see the details of each service that you have used.
In case of free azure from Microsoft, you get to see the cost incurred for each one.
Visit Check usage of free services included with your Azure free account
Hope this helps someone!
This is a handy function for getting filenames, with the specified format (usually .mat
) in a root folder!
function filenames = getFilenames(rootDir, format)
% Get filenames with specified `format` in given `foler`
%
% Parameters
% ----------
% - rootDir: char vector
% Target folder
% - format: char vector = 'mat'
% File foramt
% default values
if ~exist('format', 'var')
format = 'mat';
end
format = ['*.', format];
filenames = dir(fullfile(rootDir, format));
filenames = arrayfun(...
@(x) fullfile(x.folder, x.name), ...
filenames, ...
'UniformOutput', false ...
);
end
In your case, you can use the following snippet :)
filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
filename = filenames{i};
% do your job!
end
I propose use StringBuilder
string s1 = "'99024','99050','99070','99143','99173','99191','99201','99202','99203','99204','99211','99212','99213','99214','99215','99217','99218','99219','99221','99222','99231','99232','99238','99239','99356','99357','99371','99374','99381','99382','99383','99384','99385','99386','99391','99392'";
var stringBuilder = new StringBuilder();
foreach (var s in s1.Split(','))
{
stringBuilder.Append(s).Append(",").AppendLine();
}
Console.WriteLine(stringBuilder);
A lot of functions return None if there are no appropriate results. For example, an SQLAlchemy query's .first()
method returns None if there were no rows in the result. Suppose you were selecting a value that might return 0 and need to know whether it's actually 0 or whether the query had no results at all.
A common idiom is to give a function or method's optional argument the default value of None, and then to test that value being None to see if it was specified. For example:
def spam(eggs=None):
if eggs is None:
eggs = retrievefromconfigfile()
compare that to:
def spam(eggs=None):
if not eggs:
eggs = retrievefromconfigfile()
In the latter, what happens if you call spam(0)
or spam([])
? The function would (incorrectly) detect that you hadn't passed in a value for eggs
and would compute a default value for you. That's probably not what you want.
Or imagine a method like "return the list of transactions for a given account". If the account does not exist, it might return None. This is different than returning an empty list (which would mean "this account exists but has not recorded transactions).
Finally, back to database stuff. There's a big difference between NULL and an empty string. An empty string typically says "there's a value here, and that value is nothing at all". NULL says "this value hasn't been entered."
In each of those cases, you'd want to use if A is None
. You're checking for a specific value - None - not just "any value that happens to cast to False".
Any collection that you iterate over with foreach may not be modified during iteration.
So while you're running a foreach over rankings, you cannot modify its elements, add new ones or delete any.
What are dex files: Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app.
Reason for this exception: The DEX specification limits the total number of methods that can be referenced within a single DEX file to 65,536 (64K reference limit) —including Android framework methods, library methods, and methods in your own code.
Step 01. Add the following dependency as follows
For Non-Androidx Users,
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true //ADD THIS LINE
}
For Androidx Users,
dependencies {
implementation 'androidx.multidex:multidex:2.0.1'
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true //ADD THIS LINE
}
Step 02:
After adding those Sync projects and before you run the project make sure to Build a project before the run. otherwise, you will get an exception.
Exception object also contains original response e.response
, that could be useful if need to see error body in response from the server. For example:
try:
r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
r.raise_for_status()
except requests.exceptions.HTTPError as e:
print (e.response.text)
I spent ages trying to figure this out but it is simple! You can use length(·)
. length(mylist)
will tell you the number of objects mylist
contains.
... and just realised someone had already answered this- sorry!
You could merge two queries together:
$merged = $query_one->merge($query_two);
In our case, it's an iOS app, built on Xcode 11.5, using cocoapods (and cocoapods-binary if you will).
We were seeing this crash:
dyld: Library not loaded: @rpath/PINOperation.framework/PINOperation
Referenced from: /private/var/containers/Bundle/Application/4C5F5E4C-8B71-4351-A0AB-C20333544569/Tellus.app/Frameworks/PINRemoteImage.framework/PINRemoteImage
Reason: image not found
Turns out that I had to delete the pods cache and re-run pod install, so Xcode would point this diff:
As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below
e.g.
Exec N'Select bla..'
the N defines string literal is unicode.
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
Simple example
public class Simple
{
public int Propery { get; set; }
}
If you want to clear all the input fields after submitting the form, consider using reset method on the FormGroup.
This might help you
public static string TransformDocument(string doc, string stylesheetPath)
{
Func<string,XmlDocument> GetXmlDocument = (xmlContent) =>
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlContent);
return xmlDocument;
};
try
{
var document = GetXmlDocument(doc);
var style = GetXmlDocument(File.ReadAllText(stylesheetPath));
System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();
transform.Load(style); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
XmlReader xmlReadB = new XmlTextReader(new StringReader(document.DocumentElement.OuterXml));
transform.Transform(xmlReadB, null, writer);
return writer.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
pip defaults to installing Python packages to a system directory (such as /usr/local/lib/python3.4
). This requires root access.
--user
makes pip install packages in your home directory instead, which doesn't require any special privileges.
Just to add another option to Dónal's answer, you can also still use the good old java.lang.Object.getClass()
method.
My guess is that part of your problem is the parameter lists not matching.
int (* length)();
and
int length(PString * self)
are not the same. It should be int (* length)(PString *);
.
...woah, it's Jon!
Edit: and, as mentioned below, your struct pointer is never set to point to anything. The way you're doing it would only work if you were declaring a plain struct, not a pointer.
str = (PString *)malloc(sizeof(PString));
protected void Page_Load(object sender, EventArgs e)
{
myLabel.Text = "My text";
}
this is the base of ASP.Net, thinking in controls, not html flow.
Consider following a course, or reading a beginner book... and first, forget what you did in php :)
Thnaks for answer. I tried it myself too to an Empty Project and - lo behold allmighty creator of heaven and seven seas - it worked. I originally had ListBox inside which was inside of root . For some reason ListBox doesn't like being inside of StackPanel, at all! =)
-pom-
The only important question is "How is the code simpler, better readable, easier to understand?" If it is simpler with multiple returns, then use them.
Let me make it simple and clear. Lets use the re module in python to escape the special characters.
Python script :
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
Output :
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
Explanation :
Now observe that re.escape function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.
Hope this helps you.
You can use org.json.JSONObject and org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK
Here is an optimized version of the above method RemoveInvalidXmlChars which doesn't create a new array on every call, thus stressing the GC unnecessarily:
public static string RemoveInvalidXmlChars(string text)
{
if (text == null)
return text;
if (text.Length == 0)
return text;
// a bit complicated, but avoids memory usage if not necessary
StringBuilder result = null;
for (int i = 0; i < text.Length; i++)
{
var ch = text[i];
if (XmlConvert.IsXmlChar(ch))
{
result?.Append(ch);
}
else if (result == null)
{
result = new StringBuilder();
result.Append(text.Substring(0, i));
}
}
if (result == null)
return text; // no invalid xml chars detected - return original text
else
return result.ToString();
}
I think the number of lines added is highly dependent upon the state of the project, the rate of adding to a new project will be much higher than the rate of a starting project.
The work is different between the two - at a large project you usually spend most of the time figuring the relationships between the parts, and only a small amount to actually changing/adding. whereas in a new project - you mostly write... until it's big enough and the rate decreases.
If you can't change the datatype on the table itself to use varchar(max), then change your query to this:
SELECT *
FROM [Village]
WHERE CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'
Recently I wanted to learn how to compile Intel x86 on Mac OS X:
-o hello.tmp - outfile
-f macho - specify format
Linux - elf or elf64
Mac OSX - macho
-arch i386 - specify architecture (32 bit assembly)
-macosx_version_min 10.6 (Mac OSX - complains about default specification)
-no_pie (Mac OSX - removes ld warning)
-e main - specify main symbol name (Mac OSX - default is start)
-o hello.o - outfile
./hello.o - execution
nasm -o hello.tmp -f macho hello.s && ld -arch i386 -macosx_version_min 10.6 -no_pie -e _main -o hello.o hello.tmp && ./hello.o
Let me know if this helps!
I wrote how to do it on my blog here:
http://blog.burrowsapps.com/2013/07/how-to-compile-helloworld-in-intel-x86.html
For a more verbose explanation, I explained on my Github here:
You can simply use,
import json
json.loads(my_bytes_value)
In case you can't install the procps package (don't have proper permissions) you can use /proc directory.
The first few directories (named as numbers) are PIDs of your processes. Inside directories, you can find additional information useful to decipher which process is connected to each PID. For example, you can use the cat command to view "cmdline" file to check which process is connected to PID.
$ ls /proc
1 10 11 ...
$ ls -1 /proc/22
attr
autogroup
auxv
cgroup
clear_refs
cmdline
...
$ cat /proc/22/cmdline
/bin/sh
img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
If you are On Windows, and you are trying to setup MongoDB, run cmd as Admnistrator is the way forward as Enrique suggested above see it here
If your data is already in array form, it's really simple using jQuery:
$(data.msg).each(function()
{
alert(this.value);
alert(this.label);
//this refers to the current item being iterated over
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('#myDropDown').append(option);
});
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
An old post, but I love to share as I have the same case but I finally knew the problem :
Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.
Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.
But please inspect this sample that did not heed the above case :
<div class="btn-list" id="selected-country"></div>
Dynamically appended :
<button class="btn-map" data-country="'+country+'">'+ country+' </button>
This function is working good by clicking the button :
$(document).ready(function() {
$('#selected-country').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
})
or you can use body like :
$('body').on('click','.btn-map', function(){
var datacountry = $(this).data('country'); console.log(datacountry);
});
compare to this that not working :
$(document).ready(function() {
$('.btn-map').on("click", function() {
var datacountry = $(this).data('country'); alert(datacountry);
});
});
hope it will help
In my case, my problem was environmental. Meaning, I did something wrong in my bash session. After attempting nearly everything in this thread, I opened a new bash session and everything was back to normal.
Look into creating Applets if you want to make a website with Java. You most likely wont need to use anything but regular Java, unless you want something more specialized.
If you use ui-router you can use (on run)
$rootScope.$on("$stateChangeSuccess", function (event, currentState, previousState) {
$window.scrollTo(0, 0);
});
UPDATE `tbl_user` SET `name`=concat('tbl_user.first_name','tbl_user.last_name') WHERE student_roll>965
Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)
add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])
$(function() {
$("#MyTextBox").blur();
});
You cannot select a row like that. You have to specify a field whose values will be 3
Here is a query that will work, if the field you are comparing against is id
select * from customer where `id` = 3
If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.
Add a javascript class with all you KO extensions or extenders, and add the following:
ko.extenders.required = function (target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
Then in your viewModel extend you observable by:
self.dateOfPayment: ko.observable().extend({ required: "" }),
There are a number of examples online for this style of validation.
db.collection_name.find({"filed_name":{$exists:true}});
fetch documents that contain this filed_name even it is null.
Warning
db.collection_name.find({"filed_name":{$ne:null}});
fetch documents that its field_name has a value $ne to null but this value could be an empty string also.
My proposition:
db.collection_name.find({ "field_name":{$ne:null},$where:"this.field_name.length >0"})
The method find will return the character position in a string. Then, if you want remove every thing from the character, do this:
mystring = "123?567"
mystring[ 0 : mystring.index("?")]
>> '123'
If you want to keep the character, add 1 to the character position.
# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password
encrypted and test with the current Password not encrypted to verify
if it's the same User.
For example :
public function updateUser(Request $req)
{
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository(User::class);
$user = $repository->find($req->get(id)); /// get User from your DB
if($user == null){
throw $this->createNotFoundException('User don't exist!!', $user);
}
$password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
$passwordToUpdate = $req->get('password'); // not encrypted yet from request.
$passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);
////////////VERIFY IF IT'S THE SAME PASSWORD
$isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );
if($isPass === false){ // failure
throw $this->createNotFoundException('Your password it's not verify', null);
}
return $isPass; //// true!! it's the same password !!!
}